How to Pass Commands with Spaces in a PowerShell Script?

0
14
Asked By TechWhiz101 On

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?

4 Answers

Answered By ScriptingGuru24 On

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.

Answered By DevNinja42 On

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.

Answered By CodeCrafter89 On

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*'"```.

Answered By PowerShellPro77 On

If `Invoke-Expression` doesn't work for whatever reason, try calling `Powershell.exe` with `-EncodedCommand` or `-File`. This could handle special characters better.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.