Glo*_*wie 5 variables powershell scriptblock
我正在尝试按照这篇文章扩展脚本块中的变量
我的代码尝试这样做:
$exe = "setup.exe"
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock {cmd /c 'C:\share\[scriptblock]::Create($exe)'}
Run Code Online (Sandbox Code Playgroud)
如何修复错误:
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
Run Code Online (Sandbox Code Playgroud)
您绝对不需要为此场景创建新的脚本块,请参阅链接文章底部的 Bruce 评论,了解为什么不应该这样做的一些充分理由。
Bruce 提到将参数传递给脚本块,并且在这种情况下效果很好:
$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { param($exe) & "C:\share\$exe" } -ArgumentList $exe
Run Code Online (Sandbox Code Playgroud)
在 PowerShell V3 中,有一种更简单的方法可以通过 Invoke-Command 传递参数:
$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { & "C:\share\$using:exe" }
Run Code Online (Sandbox Code Playgroud)
请注意,PowerShell 可以很好地运行 exe 文件,通常没有理由先运行 cmd。
为了阅读本文,您需要确保利用 PowerShell 的功能来扩展字符串中的变量,然后使用[ScriptBlock]::Create()which 采用字符串来创建新的 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5788 次 |
| 最近记录: |