展开单引号内的变量

Expand variable inside single quotes

如何在单引号内扩展 $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'

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

$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"

另一种选择是使用 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