the powershell variable can't quote correctly in my script

70 Views Asked by At

greet !

at first i want to use powershell to generate a cmd and put some command in it

[CmdletBinding()]
param (
    [Parameter()]
    [string]
    $ParameterName
)

cmd /c "start cmd /k " $ParameterName

it work well when i input some prompt without space & 'C:\ex-sys\Program files\dre\dre.ps1' tasklist ,but when the prompt with space like &

'C:\ex-sys\Program files\dre\dre.ps1' 'F:\git hub\yt-dlp\yt-dlp (27).exe'

it output in cmd

'F:\git' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

which mean 'F:\git' isn't command or any runable bat ,Apparently the cmd miss my quote in powershell so is there anyway i could fix this problem

2

There are 2 best solutions below

0
mklement0 On BEST ANSWER

Replace:

cmd /c "start cmd /k " $ParameterName

with:

# Asynchronously starts an interactive cmd.exe session in a *new window*,
# in which the value of $ParameterName is executed as a command.
Start-Process cmd "/k `"$ParameterName`""

This avoids the unnecessary cmd /c call and uses embedded "..." quoting (`"...`") around the value of $ParameterName to ensure that cmd.exe recognizes it a single argument even if it contains spaces.

Start-Process is PowerShell's analog to cmd.exe's internal start command (and in PowerShell there's even a start alias for it).

0
123 123 On

the following answer work well in the script ,if you want to add the parameter at the prompt using & 'C:\ex-sys\Program files\dre\dre.ps1' '"F:\git hub\yt-dlp\yt-dlp (27).exe" --help' ,double quote the paramter