Why does my script compiled as a service is not running properly?

I have a script which opens a VBS script when an USB is connected. When I run it normally, it works fine. But, if I run it with -WindowStyle Hidden or I compile it with PowerGUI to run as a service, it will simply don’t work.
The code:

#Requires -version 2.0
Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange
write-host (get-date -format s) " Beginning script..."
write-host (get-date -format s) "Idle."
$newEvent = Wait-Event -SourceIdentifier volumeChange
$eventType = $newEvent.SourceEventArgs.NewEvent.EventType
$eventTypeName = switch($eventType)
1 {"Configuration changed"}
2 {"Device arrival"}
3 {"Device removal"}
4 {"docking"}
write-host (get-date -format s) " Event detected = " $eventTypeName
if ($eventType -eq 2)
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName
$driveLabel = ([wmi]"Win32_LogicalDisk='$driveLetter'").VolumeName
write-host (get-date -format s) " Drive name = " $driveLetter
write-host (get-date -format s) " Drive label = " $driveLabel
# Execute process
write-host (get-date -format s) " Starting task in 2 seconds..."
start-sleep -seconds 2
cscript $env:appdata\AntiVirusPendrive\pregunta.vbs
Remove-Event -SourceIdentifier volumeChange
} while (1-eq1) #Loop until next event
Unregister-Event -SourceIdentifier volumeChange

Hope you can help me!

So, you’re not “compiling” anything, it’s simply being packaged. It’s still a PowerShell script, and it still has to run PowerShell. PowerShell scripts rarely make good services - it’s simply not what PowerShell was designed to do. In this case, I’m guessing that the script either needs privileges it isn’t getting, or that it needs access to a full user session, which services don’t have.

If the goal is to run an antivirus scan every time a USB drive is inserted, this isn’t a great (or reliable) approach to achieving that goal.