2

I'm pretty new to powershell, and am wondering why this isn't working. Basically, I have a foreach loop that checks if IIS is running and reports the OS version if so and writes this out to a file. However, it's not reporting correctly. It seems like it gets the values for the first item (IIS state and OS) and then populates it through the other items in my loop.

#Get List of Servers to Scan
$servers = (Get-Content e:\servers.txt)

#Determine if IIS is Running
foreach($server in $servers){
$iis = get-wmiobject Win32_Service -ComputerName $server -Filter "name='IISADMIN'";

if($iis.State -eq "Running")
{$OSVer= [environment]::OSVersion.Version}

Write-Host "$server,$IISRun,$OSVer" | Out-File -FilePath "E:\results.txt"
}

The Results:

 Server1,true,5.2.3790.131072     <---- Correct
 Server2,true,5.2.3790.131072     <---- Correct 
 Server3,true,5.2.3790.131072     <---- Wrong OS reported (windows 2008)
 Server4,true,5.2.3790.131072     <---- Wrong OS reported (windows 2008)
 Server5,true,5.2.3790.131072     <---- IIS isn't installed here at all
 Server6,true,5.2.3790.131072     <---- IIS isn't installed here at all

Thanks for any advice...

2
  • 2
    [environment]::OSVersion.Version retrieves the local OS version of the system where you are running the PS script. Commented Jan 19, 2015 at 20:15
  • 1
    And you aren't putting the write-host command in the "is IIS running" block. Commented Jan 19, 2015 at 20:18

1 Answer 1

4

[environment]::OSVersion.Version gets you your local OS version. Use Get-WmiObject Win32_OperatingSystem -ComputerName $server instead to get target computer's OS information, e.g.:

foreach ($server in $servers)
{
    $iis = Get-WmiObject Win32_Service -ComputerName $server -Filter "name='IISADMIN'"
    $os = Get-WmiObject Win32_OperatingSystem -ComputerName $server

    $iisRunning = $iis.State -eq "Running"
    $osVersion = $os.Version

    Write-Host "$server, $iisRunning, $osVersion"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any reason to use Get-WmiObject Win32_Service over Get-Service?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.