【问题标题】:"The RPC server is unavailable" only when running script仅在运行脚本时出现“RPC 服务器不可用”
【发布时间】:2018-05-30 03:08:26
【问题描述】:

我在使用 Powershell 时遇到问题。我尝试运行我的脚本

Param (
[string]$ComputerName
)
$ComputerName = $ComputerName -replace " ", ","
Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName | select csname, @{LABEL='LastBootUpTime' ;EXPRESSION=  {$_.ConverttoDateTime($_.lastbootuptime)}}

我运行它:

.\GetBootTime.ps1 -ComputerName localhost,<another computer>

我收到错误消息:

Get-WmiObject : RPC 服务器不可用。 (例外来自 HRESULT: 0x800706BA)。

但是,如果我运行:

Get-WmiObject Win32_OperatingSystem -ComputerName localhost,<another computer> | select csname, @{LABEL='LastBootUpTime' ;EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}

这是脚本中的主线 然后它工作。 有什么建议吗?

【问题讨论】:

  • 错误很可能是告诉您它无法与&lt;another computer&gt; 上的 WMI 通信。您可以将测试简化为 .\GetBootTime.ps1 -ComputerName &lt;another computer&gt;。您问题的“但是,如果我运行:”部分不是很清楚 - $ComputerName 在这种情况下有什么价值?
  • @FrankBoyne 如果我运行 .\GetBootTime.ps1 -ComputerName 它工作正常,似乎是当我使用两台计算机时它不起作用。也希望让它更清楚

标签: windows powershell


【解决方案1】:

您的问题是您将Computername 定义为字符串[string] 而不是字符串数组[string[]]。所以输入localhost,example 不会被解释为两台计算机,而是一台名为“localhost,example”的计算机。如果您使用[string[]](或不定义它),则, 字符将被解析为字符串数组中的分隔符。由于Get-WmiObject 可以接受一个数组,因此它将为数组的每个元素运行一次。

您可以使用-split 自己解析空格和逗号,但最好首先使用格式正确的数组。使用 -split 是因为 $ComputerName -replace " ", "," 只会使用逗号而不是空格来创建 [string],而不是拆分为数组中的多个元素。

Param (
    [string[]]$ComputerName
 )
 # Manual parsing to split space delimited into two elements 
 # e.g. 'localhost Example' into @(localhost,Example) - Not a good practice
 $ComputerName = $ComputerName -split " "
 Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName | select csname, @{LABEL='LastBootUpTime' ;EXPRESSION=  {$_.ConverttoDateTime($_.lastbootuptime)}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 2019-12-04
    • 2011-11-29
    • 2017-05-18
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多