Powershell在scriptblock中扩展变量

时间:2014-08-28 14:53:53

标签: variables powershell scriptblock

我正在尝试关注this article以扩展scriptblock中的变量

我的代码试试这个:

$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

2 个答案:

答案 0 :(得分:4)

你绝对不需要为这个场景创建一个新的脚本块,请参阅链接文章底部的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。

答案 1 :(得分:3)

要阅读本文,您需要确保利用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
相关问题