在单引号内展开变量

时间:2015-08-20 20:18:29

标签: powershell variable-expansion

如何在单引号内展开$pw

$pw = "$PsHome\powershell.exe"
cmd.exe /c 'schtasks /create /tn cleanup /tr "$pw -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile %TEMP%\exec.ps1" /sc minute /mo 1'

2 个答案:

答案 0 :(得分:16)

您可以使用格式并将其分配给另一个变量:

$pw = "$PsHome\powershell.exe";
$command = 'schtasks /create /tn cleanup /tr "{0} -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile %TEMP%\exec.ps1" /sc minute /mo 1' -f $pw;
cmd.exe /c $command

或者您可以使用双引号并使用引号转义内部引号:

$pw = "$PsHome\powershell.exe"
cmd.exe /c "schtasks /create /tn cleanup /tr ""$pw -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile %TEMP%\exec.ps1"" /sc minute /mo 1"

或者做同样的事情,但使用反叛(坟墓)来逃脱它们:

$pw = "$PsHome\powershell.exe"
cmd.exe /c "schtasks /create /tn cleanup /tr `"$pw -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile %TEMP%\exec.ps1`" /sc minute /mo 1"

答案 1 :(得分:12)

另一种选择是使用automatic variable $ExecutionContext

$pw = "$PsHome\powershell.exe"
$cmd = 'schtasks /create /tn cleanup /tr "$pw -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile %TEMP%\exec.ps1" /sc minute /mo 1'
$cmd = $ExecutionContext.InvokeCommand.ExpandString($cmd)
cmd.exe /c $cmd