Hi,
Today I found myself needing to run a PowerShell command from the command line. I ran powershell /? and had a look at the switches and there is a -Command switch. My first attempt to use the switch looked like:
1 |
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -Command {Get-Process | Out-File "$ENV:UserProfile\Desktop\Processes.txt"} |
The above doesn’t work – It gives an error about Out-File not being recognized as an internal or external command.
It turns out that you need to enclose the command with quotes to make it a recognizable string, and the first character in the string must be the “&” character. Just like in PowerShell where you can use the & character to run a command, it’s used here to tell PowerShell to run the string we’re passing it.
The final (working) command looks like:
1 |
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -Command "& {Get-Process | Out-File "$ENV:UserProfile\Desktop\Processes.txt"}" |
Happy Scripting!