loops - Proper way to create pscustomobject to add to array -
what proper way create / clear / initialize object inside loop using following method/syntax? there performance increases using method.
$objcomputer = [pscustomobject] @{}
i noticed if 1 of systems not exist in ad , returns error or null information previous entry/object used in array. example computer-03 valid blah (which not) pulls previous entry of computer-03.
function get-adcomputers ($namelist) { $arraycomputer = @(); foreach ($line in $namelist.split("`r`n") | ? { $_ }) { $pcname = $line.trim() $computer = (get-adcomputer -identity $pcname -properties *) $objcomputer = [pscustomobject] @{ computer = $pcname active = $computer.enabled date = $computer.passwordlastset daysold = (get-daysold $computer.passwordlastset) ou = $computer.distinguishedname } write-host $objcomputer $arraycomputer += $objcomputer $objcomputer = $null; } return $arraycomputer }
results
computer active date daysold computer-01 true 4/12/2015 8:16 -29 computer-02 true 5/4/2015 7:11 -7 computer-03 true 4/20/2015 9:01 -21 blah true 4/20/2015 9:01 -21 computer-03 true 4/6/2015 8:14 -35 computer-04 true 5/9/2015 17:17 -1 computer-05 true 4/17/2015 12:04 -24
thank help! :)
edit example try catch:
function get-adcomputers ($namelist) { $arraycomputer = @(); foreach ($line in $namelist.split("`r`n") | ? { $_ }) { $computer = $null $pcname = $line.trim() try { $computer = (get-adcomputer -identity $pcname -properties *) $objcomputer = [pscustomobject] @{ computer = $pcname active = $computer.enabled date = $computer.passwordlastset daysold = (get-daysold $computer.passwordlastset) ou = $computer.distinguishedname } } catch { $objcomputer = [pscustomobject] @{ computer = "$pcname" active = "missing" date = "n/a" daysold = "n/a" ou = "n/a" } } write-host $objcomputer $arraycomputer += $objcomputer $objcomputer = $null; } return $arraycomputer }
if call get-adcomputer
fails, $computer
not cleared out. you'll need handle error in 1 way or another. simple solution:
$computer = $null $computer = (get-adcomputer -identity $pcname -properties *) if(!$computer) { #handle missing computer $objcomputer = [pscustomobject] @{ computer = "computer not found" active = "false" date = "n/a" daysold = "n/a" ou = "n/a" } }
you can use try/catch block. if don't care much, can use -erroraction silentlycontinue
.
Comments
Post a Comment