Powershell在命令中使用引号中的变量

时间:2017-12-14 18:31:32

标签: powershell variables quotes variable-expansion

我有这个有效(三重双引号不是错误,它的确如此) - 专注于Start-Process部分:

Start-Process powershell -Credential $cred -WorkingDirectory "$lettre_disque" -ArgumentList '-noprofile -command &{Start-Process """D:\WD Drive Unlock.exe""" -verb runas}'

现在我只是尝试用名为D:\WD Drive Unlock.exe的变量替换字符串$chemin_fichier,该变量包含完全相同的文本(D:\WD Drive Unlock.exe

我正在尝试:

 """$chemin_fichier"""

 ""$chemin_fichier""

 "$chemin_fichier"

 """"$chemin_fichier""""

什么都行不通......

如何显示该变量?这个命令很混乱,什么是正确的组合?我是否必须逃避某些事情?

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

我使用splatting将你的命令分成几部分:

$chemin_fichier = 'D:\WD Drive Unlock.exe'

$ArgList = @{
    FilePath = 'powershell'
    Credential = $cred
    WorkingDirectory = $lettre_disque
    ArgumentList = @(
        '-NoProfile'
        '-Command'
        "`"Start-Process -FilePath '$chemin_fichier' -Verb runas`""
    )
}
Start-Process @ArgList

不需要在脚本块中包装命令。

答案 1 :(得分:1)

我使用的命令带有这样的参数,它将store:Schema="abcd"替换为空字符串,将"转换为""""""至关重要,您应该给它尝试,测试和修改以确保脚本正常工作:

powershell -Command "$varStr='store:Schema=""abcd""""'; $filePath='%~dp0SomeFolder\SomeFile.txt'; (gc $filePath) -replace $varStr, '' | Out-File $filePath"