How to Create a PowerShell Script That Accepts Commands with Spaces?

0
2
Asked By DigitalExplorer23 On

I'm working with a setup that only allows me to run PowerShell scripts, but I can't execute commands directly from the terminal. The script I'm using accepts parameters, and I've got it partially working like this:

```powershell
param(
[Parameter(Mandatory = $true)]
[string]$Command
)

Powershell.exe "$Command"
```

I execute it using a command like `run PowerShellScript.ps1 -parameters Get-Process`. This works fine, but I'm hitting a snag when there's a space in the parameter. For example, `run PowerShellScript.ps1 -parameters Get-Process | where processname -like "*Teams*"` fails because it misinterprets the space as a separator for different parameters. Given that my terminal is quite limited, I'm hoping to find a solution that can be incorporated directly into my script. Any suggestions?

2 Answers

Answered By CuriousDev88 On

Is it possible for your script to initiate an interactive PowerShell session? Just a thought. Also, do you know if the scripts are executing under your user account or a service account? That could be relevant too.

DigitalExplorer23 -

No, I can't start an interactive PowerShell session with the script, and it runs as the system user.

Answered By TechWhiz42 On

Instead of using `Powershell.exe "$Command"`, try using `Invoke-Expression $Command`. This way, you can build your command more flexibly without running into issues with spaces.

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.