脚本块中的 Powershell 扩展变量 [英] Powershell expand variable in scriptblock

查看:52
本文介绍了脚本块中的 Powershell 扩展变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试关注 这篇文章 在脚本块中扩展变量

I am trying to follow this article to expand a variable in a 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

推荐答案

要阅读本文,您需要确保利用 PowerShell 的功能来扩展字符串中的变量,然后使用 [ScriptBlock]::Create() 它接受一个字符串来创建一个新的 ScriptBlock.您当前尝试的是在 ScriptBlock 中生成 ScriptBlock,这是行不通的.它应该看起来更像这样:

To follow the article, you want to make sure to leverage PowerShell's ability to expand variables in a string and then use [ScriptBlock]::Create() which takes a string to create a new ScriptBlock. What you are currently attempting is to generate a ScriptBlock within a ScriptBlock, which isn't going to work. It should look a little more like this:

$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

这篇关于脚本块中的 Powershell 扩展变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆