Fellow coders, I received some great feedback from our honorary scripting guru’s Mike F. Robbins and Richard Siddaway about my little function (thanks guys! I’ll buy you a drink when we meet! 😉 ).
With their feedback I managed to improve my simple function. And that’s so great about being part of a community; people are always willing to help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#requires -Version 2 Function Get-ComputerDetail { [cmdletbinding()] param ( [ValidateNotNullOrEmpty()] [string[]]$ComputerName = $env:COMPUTERNAME ) foreach ($node in $ComputerName) { try { $computerSystem = Get-WmiObject -Class 'Win32_ComputerSystem' -ComputerName $node -ErrorAction Stop $computerBios = Get-WmiObject -Class 'Win32_Bios' -ComputerName $node -ErrorAction Stop [pscustomobject][ordered]@{ Name = $computerSystem.Name Manufacturer = $computerSystem.Manufacturer Model = $computerSystem.Model Serial = $computerBios.SerialNumber } # End of custom object } # End of try catch { Write-Error -Message "The command failed for computer $node. Message: $_.Exception.Message" break }# End of Catch }# End of foreach }# End of function |
One more suggested mod. This will process everything in the list, and then print out all the errors at the end of the run.
Function Get-ComputerDetails{ [cmdletbinding()] Param([string[]]$Computer) $msg = "" foreach ($node in $Computer) { try { $sys = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $node -ErrorAction Stop $bios = Get-WmiObject -Class Win32_Bios -ComputerName $node -ErrorAction Stop [pscustomobject][ordered]@{ Name = $sys.Name Manufacturer = $sys.Manufacturer Model = $sys.Model Serial = $bios.SerialNumber } } catch { $msg += "The command failed for computer $node. Message: $_.Exception.Message[crayon-600bdc3ae894c345792267 inline="true" ]rn”
continue
}
}
if (“” -ne $msg) { Write-Error -Message $msg }
}
[/crayon]
… not to mention, completely flatten the code. 🙂
Nice one .. Thanks for sharing