在脚本块中扩展变量的Powershell

6
我将尝试按照这篇文章的方法,在脚本块中扩展变量。
我的代码如下:
$exe = "setup.exe"

invoke-command -ComputerName $j -Credential $credentials -ScriptBlock {cmd /c 'C:\share\[scriptblock]::Create($exe)'}

如何修复错误:
The filename, directory name, or volume label syntax is incorrect.
    + CategoryInfo          : NotSpecified: (The filename, d...x is incorrect.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : remote_computer

这里是关于变量替换在PowerShell脚本块中的文章,由于微软已经移动或删除原始内容,可以在[WaybackMachine](http://blogs.technet.com/b/heyscriptingguy/archive/2013/05/22/variable-substitution-in-a-powershell-script-block.aspx)上找到参考资料。 - KevH
2个回答

5

在这种情况下,您绝对不需要创建新的脚本块,请参考链接文章底部Bruce的评论,他列举了一些不需要这样做的好理由。

Bruce提到将参数传递给脚本块,在这种情况下效果很好:

$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { param($exe) & "C:\share\$exe" } -ArgumentList $exe

在PowerShell V3中,通过Invoke-Command传递参数的方法更加简单:
$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { & "C:\share\$using:exe" }

请注意,PowerShell可以很好地运行exe文件,通常没有必要先运行cmd。


我是否错过了链接的文章? - aggieNick02
1
请查看问题中的链接,而不是答案中的链接。 - Jason Shirk
1
啊,谢谢。要避免使用[scriptblock]::create,因为如果引号使用不当,可能会创建/运行意外的代码。您描述的使用方法很棒,这意味着没有类似于“eval”的东西正在进行,所以我肯定会首先尝试那种方式。 - aggieNick02

4
为了遵循这篇文章,你需要确保利用PowerShell字符串中的变量扩展能力,然后使用[ScriptBlock] :: Create()来创建新的ScriptBlock。您目前正在尝试在ScriptBlock中生成ScriptBlock,这是行不通的。它应该看起来更像这样:
$exe = 'setup.exe'
# The below line should expand the variable as needed
[String]$cmd = "cmd /c 'C:\share\$exe'"
# The below line creates the script block to pass in Invoke-Command
[ScriptBlock]$sb = [ScriptBlock]::Create($cmd) 
Invoke-Command -ComputerName $j -Credential $credentials -ScriptBlock $sb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接