【问题标题】:I am trying to execute a small String which contains a powershell script using -Command option but its not getting executed? how to resolve this?我正在尝试使用 -Command 选项执行一个包含 powershell 脚本的小字符串,但它没有被执行?如何解决这个问题?
【发布时间】:2021-07-17 10:31:30
【问题描述】:

我正在使用 PowerShell Core 来执行此操作。 命令:

pwsh -NoLogo -NonInteractive -InputFormat text -OutputFormat text -Command “& { $Password = ConvertTo-SecureString 'pswd' -AsPlainText -Force;$skipCN = New-PSSessionOption -SkipCNCheck -SkipCACheck;$Credential = New-Object System.Management.Automation.PsCredential 'Administrator’ , $Password;Invoke-Command -ComputerName hostname -Authentication Basic -Credential $remote_credential -ScriptBlock {{ Get-WmiObject -Class Win32_PerfRawData_PerfOS_Memory | Format-List * }} -useSSL -SessionOption $skipCN }”

输出为:

但是,如果我使用命令运行脚本

pwsh -NoLogo -NonInteractive -InputFormat text -OutputFormat text -Command absolute_file_path

它按预期工作。

我应该进行哪些更改以使其使用 -Command 选项作为字符串运行?

编辑:删除 -scriptblock 之后的双 {{ 并用单个 { 替换它没有帮助。

【问题讨论】:

  • 一方面,停止使用大引号(尤其是不要像'Administrator’ 那样混合使用它们)而是直引号。这些所谓的“智能引用”在 Word 文档中可能看起来不错,但在代码中可能会做一些奇怪的事情。另外,我建议您不要将所有内容都塞进一行代码中,这会使调试变得非常困难。
  • @Theo 我尝试使用直引号,但没有成功,整个代码作为字符串传递,每一行用分号 ' 分隔; ' .

标签: powershell powershell-remoting winrm powershell-core


【解决方案1】:

删除脚本块中多余的大括号,并使用直引号。

pwsh -NoLogo -NonInteractive -InputFormat text -OutputFormat text -Command "& { $Password = ConvertTo-SecureString 'pswd' -AsPlainText -Force;$skipCN = New-PSSessionOption -SkipCNCheck -SkipCACheck;$Credential = New-Object System.Management.Automation.PsCredential 'Administrator' , $Password;Invoke-Command -ComputerName hostname -Authentication Basic -Credential $remote_credential -ScriptBlock { Get-WmiObject -Class Win32_PerfRawData_PerfOS_Memory | Format-List * } -useSSL -SessionOption $skipCN }"

如果pwsh不起作用,请用powershell替换。

【讨论】:

  • Smith,仍然没有运气,我收到以下错误。解析器错误:行 | 1 | ... ct System.Management.Automation.PsCredential 'Administrator',;Invoke- ... | ~ |管道元素中“,”后缺少表达式。
  • 在您的脚本中,您将创建 $Credential,然后使用 $remote_credential。这是一个错字,还是您的脚本比发布的内容更多?
  • 是的,这是一个错字,修复它仍然无法工作,它在这条线上失败了我相信“$Credential = New-Object System.Management.Automation.PsCredential 'Administrator', $Password”我猜它没有获取 $Password 的值,也许这就是它打印 ParserError: Line | 的原因1 | ... ct System.Management.Automation.PsCredential 'Administrator',;Invoke- ... | ~ |管道元素中“,”后缺少表达式。 ——
  • 您是否在 PowerShell 中对此进行了测试?如果没有,请打开 PowerShell 并将代码粘贴在大括号之间,看看是否有效。您可以一次测试每一行代码(在“;”之间),看看是哪一行导致了错误。
  • 嗨@Mike Smith,我实际上是在使用这个脚本从远程计算机获取wmi-object。所以是的,它有效。
猜你喜欢
  • 2019-05-04
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 2013-12-24
  • 2021-03-19
  • 2018-08-28
  • 2014-12-13
  • 1970-01-01
相关资源
最近更新 更多