0

I have a csv as below :

  • Server OS HotFixID
  • Comp1 Win12 KB452
  • Comp1 Win12 KB453
  • svrname3 Win8 KB134

I have written below script for checking OS and if its matched then it should check if the server is having the same HotfixID or not.

$file = Import-Csv .\Desktop\hotfix.csv
if($Win12 = $file | where {$_.os -eq "Win12"} | select Source, HotFixID)
{
Get-HotFix -ComputerName ($Win12.Source) -Id ($Win12.HotFixID)
}
else
{
$Win8 = $file | where {$_.os -eq "Win8"} | select Source, HotFixID
Get-HotFix -ComputerName ($Win8.Source) -Id ($Win8.HotFixID)
}

problem is with output.. I have 2 Win12 server in csv, but I am getting 4 output 2 as duplicate.. I am able to understand that here one nested loop is running but unable to rectify it. Please!! let me know how can we fix this issue.

1
  • I'm a little confused. Your example data seem to reference only 1 Win12 server - "Comp1". Do you want to check only 1 specific HotfixID per remote computer? Commented Jan 3, 2020 at 14:52

2 Answers 2

1

Assumed I understood your task correct you should iterate over all elements in your CSV file and check each item indivually.

$CSVList = Import-Csv .\Desktop\hotfix.csv
foreach ($CSVItem in $CSVList) {
    if ($CSVItem.os -eq 'Win12' -or $CSVItem.os -eq 'Win8') {
        if (Test-Connection -ComputerName $CSVItem.Source) {
            Get-HotFix -ComputerName $CSVItem.Source -Id $CSVItem.HotFixID
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You have multiple entries with Win12 so $Win12 is an array of PSCustomObject. When you use ($Win12.Source) it will output an array of all sources. (Comp1,Comp1). Get-Hotfix accepts this array and tests $Win12.HotFixID (which is an array, too) with each of the sources. Thats the reason you get each Item the Number of times they apear in the CSV. To avoid this, process each line in the CSV on their own. If you want to keep your structure, your code would look like this:

if($Win12 = $file | where {$_.os -eq "Win12"} | select Source, HotFixID)
{
    $Win12 | foreach {
        Get-HotFix -ComputerName ($_.Source) -Id ($_.HotFixID)
    }
}
else
{
    $Win8 = $file | where {$_.os -eq "Win8"} | select Source, HotFixID
    $Win8 | foreach {
        Get-HotFix -ComputerName ($_.Source) -Id ($_.HotFixID)
    }

}

However the Code of Olaf is cleaner and does the same.

1 Comment

I couldn't have explained it better myself. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.