Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Powershell and WMI - Foreach gives RPC error

$
0
0

Hello, I am having a very strange experience with WMI connectivity. Trying to read a CSV file with a list of server names into a variable and run a Foreach loop to get WMI information.

------------- This code gives an error --------------

$computers = $Null
$namespace = "ROOT\CIMV2"
$classname = "Win32_Service"
$inputfile = "C:\ServerList.csv"
$Computers = import-csv $inputfile

Foreach ($Computer in $Computers){
  $Computer    #This gives me the computer name for testing
  Get-WmiObject -Class $classname -ComputerName $Computer -Namespace $namespace |
  Select-Object DisplayName, State | ? {$_.DisplayName -like "*SQL Server (*"} |
  Format-Table @{Label="Server"; Expression={$Computer}}, DisplayName, State -auto}

------------  Error Below - I get this for every server object  -----------------------------
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:3 char:14
+ Get-WmiObject <<<<  -Class $classname -ComputerName $Computer -Namespace $namespace |
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

_______________________________________________________________________

So here comes the very interesting part that has me really confused. When I run the code below, It executes perfectly assigning server names one by one. This is obviously without the Foreach loop.  So why would the Foreach give me the RPC error?

--------  Working Code without the Loop ---------------------

$namespace = "ROOT\CIMV2"
$classname = "Win32_Service"
$Computer = "ComputerName"

Get-WmiObject -Class $classname -ComputerName $Computer -Namespace $namespace |
Select-Object DisplayName, State | ? {$_.DisplayName -like "*SQL Server (*"} |
Format-Table @{Label="Server"; Expression={$Computer}}, DisplayName, State -auto

 

 

 


Viewing all articles
Browse latest Browse all 6937

Trending Articles