我的一个powershell脚本表现得很奇怪。当命令与调用操作符(&)一起执行时,它将按照预期的方式工作。因为我不喜欢快捷方式,而且操作符也不容易阅读,所以我想用调用表达式代替。无论如何,这对我来说并不是什么问题,但我很想知道这是Powershell中的一个bug,还是我做错了什么。但是,这会导致错误:Invoke-表达式:没有找到与参数名称"file“匹配的参数。D:\Job_Monday.PS1:10字符:34个
剧本:
` [String] $cmd1 = "C:\Tools\WOL2\WOL2.exe"
` [String] $fil1 = "C:\Tools\WOL2\WOL2.profile4.xml"
` [String] $nas1 = "SyBackup"
` # wake-on-LAN with call operator
` # & $cmd1 -file $fil1 -wake $nas1 -close
` # Wake-On-LAN with Invoke expression
` Invoke-Expression -command $cmd1 -file $fil1 -wake $nas1 -closeMany greetings from Aachen
inl1ner发布于 2022-03-25 17:30:14
首先,强制性的警告
Invoke-Expression (**iex**)固有的安全风险,通常应该避免使用,并将其作为最后的手段使用。通常都有更好的替代方案。如果真的没有其他选择,那么只在您自己提供或完全信任的输入上使用它--请参阅这个答案。Invoke-Expression只接受一个包含任意PowerShell代码的字符串,因此它与&无关,呼叫操作员接受多个参数,第一个参数是命令名或路径,其余的参数都传递给该命令。
因此,& 只是直接执行命令的语法变体,仅在以下两种情况下才需要:
例如,以下语句是等价的:
# Direct execution
C:\Tools\WOL2\WOL2.exe -command $cmd1 -file $fil1 -wake $nas1 -close
# Direct execution, of necessity via & in this case,
# because the executable path is *quoted*
& "C:\Tools\WOL2\WOL2.exe" -command $cmd1 -file $fil1 -wake $nas1 -close
# You can also use Invoke-Command, but that is *rarely useful*
# in *local* calls; also, inside the script block the rules re
# the & operator still apply.
Invoke-Command { & "C:\Tools\WOL2\WOL2.exe" -command $cmd1 -file $fil1 -wake $nas1 -close }Direct 是目前为止最典型的调用形式,因为它保证:
相比之下,启动过程 仅在 exceptional 中才被调用。
-Wait)-Wait (直接执行GUI应用程序异步启动)。-Verb RunAs-Credential启动命令请注意,没有直接的方法来捕获Start-Process-launched进程的输出--您唯一的选择是使用-RedirectStandardOutput和-RedirectStandardError重定向到文件。
请注意,还有Invoke-Command cmdlet,您可以将其看作等同于&操作符的cmdlet;但是:
&。https://stackoverflow.com/questions/71620269
复制相似问题