Home > OS >  Accessing a script in a directory with special characters via Task Scheduler
Accessing a script in a directory with special characters via Task Scheduler

Time:06-04

I want to run the following thing:

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -command "& "^""\\srv01\sysvol\ad.contoso.com\Policies\{AC6E02A7-BEDE-4D4D-A171-D4DA1E0AF2CA}\Machine\Scripts\Startup\removeAutoStartKey.ps1"^"

In order to remove a protected 'Run' registry key that a Microsoft program which uses some internal loophole to get around permission issues keeps re-creating when ran as a user. Since NT/SYSTEM has full permissions and can remove it, the task needs to be run as the system/root account with maximum possible permissions.

I keep running into 0x8070005 "File Not Found" errors after endlessly trying more and more convoluted escape sequences. What in the world needs to go into the "Add arguments (optional)" field in order to run a script in a directory with non-basic characters in it (like spaces, brackets, dashes, etc.)?

CodePudding user response:

Since all you're doing is to invoke a .ps1 file, it is sufficient and syntactically easier to use the -File CLI parameter in lieu of -Command: simple double-quoting of the script file path will do:

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "\\srv01\sysvol\ad.contoso.com\Policies\{AC6E02A7-BEDE-4D4D-A171-D4DA1E0AF2CA}\Machine\Scripts\Startup\removeAutoStartKey.ps1"

To invoke via -Command - which would only be necessary if you needed the command(s) to be interpreted as PowerShell code - escape any embedded " as \" (sic):

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -Command "& \"\\srv01\sysvol\ad.contoso.com\Policies\{AC6E02A7-BEDE-4D4D-A171-D4DA1E0AF2CA}\Machine\Scripts\Startup\removeAutoStartKey.ps1\""

That said, since your script file path doesn't need quoting, even just
-Command "\\path\to\your.ps1" would have worked.

See also:

  • Related