powershellshellbatch-filecmdps1

the powershell variable can't quote correctly in my script


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


Solution

  • 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).