我正在尝试遵循this article在脚本块中扩展变量
我的代码尝试这样做:
$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的功能来扩展字符串中的变量,然后使用[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