执行PowerShell脚本时出现"The RPC server is unavailable"错误,直接运行命令正常求助
看起来你遇到了一个典型的PowerShell参数解析问题,我来帮你拆解原因并给出针对性的解决方案:
问题根源
你的脚本里写了$ComputerName = $ComputerName -replace " ", ",",但你运行脚本时传入的参数是localhost,<another computer>——这里面根本没有空格,所以这个替换操作完全没生效。最终$ComputerName是一个包含逗号的单个字符串,而Get-WmiObject的-ComputerName参数如果收到单个带逗号的字符串,会把它当成一整个计算机名去查找,自然找不到对应的机器,就抛出了RPC不可用的错误。
而你直接运行核心命令时,PowerShell会自动把localhost,<another computer>解析成字符串数组(逗号在PowerShell里是数组分隔符),所以Get-WmiObject能正确识别两个独立的计算机名,执行也就正常了。
解决方案
方案1:移除多余的替换代码(最快修复)
既然你本来就用逗号分隔计算机名,那脚本里的替换操作完全没必要,直接删掉这行:
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>
PowerShell会自动把逗号分隔的字符串解析为数组,传给-ComputerName参数。
方案2:将参数定义为数组类型(更规范)
把参数的类型从[string]改成[string[]],这样参数本身就是数组类型,不管是传逗号分隔的字符串还是多个空格分隔的参数,都能正确识别:
Param ( [string[]]$ComputerName ) # 不需要任何替换,直接使用参数数组 Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName | select csname, @{LABEL='LastBootUpTime' ;EXPRESSION= {$_.ConverttoDateTime($_.lastbootuptime)}}
运行脚本时两种方式都支持:
- 逗号分隔:
.\GetBootTime.ps1 -ComputerName localhost,<another computer> - 空格分隔多个参数:
.\GetBootTime.ps1 -ComputerName localhost <another computer>
方案3:兼容空格分隔的输入(如果需要)
如果你原本的需求是支持用户用空格分隔计算机名(比如.\GetBootTime.ps1 -ComputerName localhost <another computer>),那可以保留替换逻辑,但要把结果转换成数组:
Param ( [string]$ComputerName ) # 把空格换成逗号,再分割成数组 $computerList = $ComputerName -replace " ", "," -split "," Get-WmiObject Win32_OperatingSystem -ComputerName $computerList | select csname, @{LABEL='LastBootUpTime' ;EXPRESSION= {$_.ConverttoDateTime($_.lastbootuptime)}}
这样不管用户用空格还是逗号分隔,都能正确解析为多个计算机名。
额外建议
另外,推荐你改用Get-CimInstance代替Get-WmiObject——WMI系列的cmdlets已经被微软标记为弃用,CIM是更现代的替代方案,不仅用法类似,还自带时间类型转换(不需要手动调用ConverttoDateTime),对数组参数的支持也更友好:
Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName | select csname, LastBootUpTime
内容的提问来源于stack exchange,提问作者Jacob White

