"The RPC server is unavailable" only when running script

0

I am having issue with Powershell.I try and run my script which is

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

I run it with:

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

I get Error Message:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA).

However if I run:

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

which is the main line in the script then it works. Any suggestions?

windows
powershell
asked on Stack Overflow May 29, 2018 by Jacob White • edited May 29, 2018 by Jacob White

1 Answer

1

Your issue is that you define Computername as a string [string] rather than a string array [string[]]. So the input localhost,example isn't interpreted as two computers but one computer named "localhost,example". If you use [string[]] (or don't define it) then the , character is parsed as the delimiter in an array of string. Since Get-WmiObject can take an array, then it would run once for each element of the array.

You could do your own parsing for spaces and commas with -split, but its better to use provide a properly formatted array in the first place. -split is used because $ComputerName -replace " ", "," will just make a [string] with commas instead of spaces rather than splitting into multiple elements in an array.

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)}}
answered on Stack Overflow May 29, 2018 by BenH • edited May 29, 2018 by BenH

User contributions licensed under CC BY-SA 3.0