How to Pass Commands with Spaces in a PowerShell Script?
Asked by
WhereDidItGo
I'm working on a system where I can only execute PowerShell scripts directly, not individual commands. The script accepts parameters, and I've been able to use it basically like this:
```powershell
param(
[Parameter(Mandatory = $true)]
[string]$Command
)
Powershell.exe "$Command"
```
This allows me to run a command like **run PowerShellScript.ps1 -parameters Get-Process**, which works fine. However, I run into issues when the parameter includes spaces, like in **run PowerShellScript.ps1 -parameters Get-process | where processname -like "*Teams*"**. The script fails because it sees the space as a separator for different parameters. I'm looking for a workaround that I can implement directly in the script, as the terminal I'm using is quite limited. Any suggestions?
Answers
If `Invoke-Expression` doesn't work for whatever reason, try calling `Powershell.exe` with `-EncodedCommand` or `-File`. This could handle special characters better.
Reply to this answer
If you're unable to start an interactive PowerShell session from your script, make sure your script is running as the user youโre logged in as. It might cause conflicts with how commands are executed. Also, check if you can run it like this with quotes: ```PowerShellScript.ps1 -Parameters "Get-Process | where processname -like '*Teams*'"```.
Reply to this answer
Did you consider using `$args` to capture the parameters? You could do something like this: `$command = $args -join ' '`. This lets you pass commands with spaces easily.
Reply to this answer
You might want to try switching from `Powershell.exe "$Command"` to `Invoke-Expression $Command`. It can handle commands with spaces better since it's designed to execute strings as PowerShell commands directly.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions