So in an effort to prepare for SharePoint 2010 I’ve begun to start ramping up my PowerShell scripts. One of the first hurdles I found was the simple act of scheduling a PowerShell script to run via Windows Scheduler.

My chosen approach was to send the script output to a text file for logging. In order to do this I created a batch file to call the PowerShell script and issue a simple pipe command to send the PS output to the log file like so:

powershell.exe c:\my scripts\testscript.ps1 > log.txt

(Note, the purpose of the script is irrelevant for this post)

Running this script is going to return an entirely not unexpected issue with the fact that PS doesn’t like the spaces in the path:

The term 'c:\my' is not recognized as a cmdlet, function, operable program, 
or script file. Verify the term and try again.
At line:1 char:8 + c:\my  <<<< my scripts\testscript.ps1

 

Changing the batch file so it property encapsulates the command in quotes like so:

powershell.exe “c:\my scripts\testscript.ps1” > log.txt

doesn’t actually do anything.

In PowerShell what you need to do is tell PS to actually execute the script and you do that by placing an ampersand in front of the script like so:

powershell.exe &“c:\my scripts\testscript.ps1” > log.txt

Now the problem is going to be that everything after the call to PowerShell is expected to be PS commands (or parameters to the commands) and the cmd shell pipe character is not a valid PS command or parameter so all that happens with the above is a PS command environment is started.

The ay to fix this is to completely define exactly what we want the PS command processor to execute. You do this by using the command argument:

powershell.exe –command “&’c:\my scripts\testscript.ps1’” > log.txt

The above syntax does exactly as you’d expect it to. PS executes the command inside the quotes and the output is passed back to the cmd shell which pipes it out the log file.

Note that in the above syntax I switched the original double quotes to single quotes to avoid escaping issues. While in this case single quotes will work, single quotes and double quotes are not interchangeable in PS, so be sure to research the proper usage.