Running PowerShell Scripts from Cmd.exe
One of the things that people often struggle with when they try to use PowerShell scripts as targets of Scheduled Tasks, or launch PowerShell scripts from cmd.exe is the following error message:
C:\Program Files\Windows PowerShell\v1.0>powershell.exe “c:\temp\has space\test.ps1”
‘c:\temp\has’ is not recognized as a cmdlet, function, operable program, or script file.
At line:1 char:12
+ c:\temp\has «« space\test.ps1
(By the way, you can speed this up by using the -noprofile parameter to powershell.exe)
This is because Powershell doesn’t natively support a parameter for a script to run. (Edit: As of V3, it does through the -File parameter) The default command-line argument is “-command,” which defines the command as though you had typed it at the prompt.
For example:
C:\temp\monad>powershell “2+2”
4
This happens to work on script names with no spaces or quotes, as our interpreter interprets that as a command execution. For scripts with spaces and quotes, you are doing the equivalent of:
[C:\temp]
PS:13 > c:\temp\has space\test.ps1
‘c:\temp\has’ is not recognized as a cmdlet, function, operable program, or script file.
At line:1 char:12
+ c:\temp\has «« space\test.ps1
[C:\temp]
PS:14 > “c:\temp\has space\test.ps1”
c:\temp\has space\test.ps1Suggestion: Did you mean to run the command in quotes? If so, try using & “”
So, the solution is:
[C:\temp]
PS:15 > & ‘C:\temp\has space\test.ps1’
Hello World
Or,
C:\temp\monad>powershell “& ‘c:\temp\has space\test.ps1’”
Hello World
This is something that we know to be a usability issue. We’re tracking it internally, but a bug (and votes) on Ms Connect would help us prioritize this properly.