gpt4 book ai didi

powershell - 无法通过-Command将脚本 block 作为参数传递给powershell.exe

转载 作者:行者123 更新时间:2023-12-03 00:35:25 25 4
gpt4 key购买 nike

我正在尝试

$Global:commandBlock={
Start-Transcript -path $projectFolder\gruntLog.txt;
grunt $argList;
Stop-Transcript
}

$cmdProc=start-process powershell -ArgumentList ('-command `$Global:commandBlock') -WorkingDirectory $fwd -PassThru -NoNewWindow:$NoNewWindow

并继续获取 $commandBlock : The term '$Global:commandBlock' is not recognized as the name of a cmdlet, function, script file, or operable program.
我的猜测是它与范围有关。但是,使变量成为全局变量并没有帮助。像这样添加 -args $commandBlock:
-ArgumentList ('-command `$Global:commandBlock -args "-commandBlock:$commandBlock"') 
-ArgumentList ('-command `$Global:commandBlock -args $commandBlock"')

没有帮助

而且我不确定是否可以在块中正确转义变量,请阅读 this,但是不确定如何将其应用于我的脚本。

最佳答案

我认为有些事情使它无法正常工作。首先,当您使用单引号'时,您将指示PowerShell实际运行。这意味着它不会扩展变量。不是您要找的。

更好的方法是使用这样的子表达式来实现。

$Global:commandBlock={
'ham' >> C:\temp\test.txt
}

$cmdProc=start-process powershell -ArgumentList ("-command $($Global:commandBlock)") -PassThru -NoNewWindow:$NoNewWindow

这将为您提供所需的结果。

子表达式非常好用。它使您可以在字符串中嵌入一个迷你脚本块,然后将其扩展到父字符串中。
"today's date is $(get-date), on system: $($env:COMPUTERNAME)"

today's date is 02/14/2017 11:50:49, on system: BEHEMOTH

关于powershell - 无法通过-Command将脚本 block 作为参数传递给powershell.exe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42231489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com