Below is how I’d do it. Note that I’d probably add in additional checks – like whether I can ping or tnc to some port on the computer before I tried to open the CimSession. Maybe also a resolve-dnsname. But with the try/catch blocks, that all gets detected/handled anyway.
# kbuff-test.ps1
$comps = Get-ADComputer -filter * -searchbase "ou=1,ou=2,dc=example,dc=com" |
Sort-Object name |
Select-Object -expand name
foreach( $comp in $comps )
{
try
{
$laps = Get-LapsADPassword -Identity $comp -ErrorAction Stop -AsPlainText
}
catch
{
Write-Error "Cannot retrieve LAPs data for '$comp'"
continue
}
$LAAccount = $laps.Account
$LAPSPwd = $laps.Password
$LAPwd = ConvertTo-SecureString -String $LAPSPwd -AsPlainText -Force
$LACred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "$comp\$LAAccount", $LAPwd
try
{
New-CimSession -Computername $comp -Credential $LACred -Name $comp -ErrorAction Stop
}
catch
{
Write-Error "Cannot open CimSession to '$comp'"
continue
}
try
{
$cs = Get-CimInstance -Classname Win32_ComputerSystem -CimSession $comp -ErrorAction Stop
}
catch
{
Write-Error "Cannot get Win32_ComputerSystem for '$comp'"
Remove-CimSession $comp
continue
}
$Log = [PSCustomObject] @{
Name = $cs.name
Model = $cs.model
Serial = $cs.serialnumber
Address = Get-NetIPAddress -CimSession $comp |
Select-Object -expand ipv4address | Where-Object { $_ -like "10.*" }
}
$Log | Export-Csv -append -notype -encoding ascii -delim "`t" c:\temp\data.csv
Remove-CimSession $comp
}
From: ntpowe...@googlegroups.com <ntpowe...@googlegroups.com>
On Behalf Of Kurt Buff
Sent: Wednesday, July 31, 2024 7:12 PM
To: ntpowe...@googlegroups.com
Subject: [ntpowershell] Odd issue with a fairly simple script
I'm gathering data from Dell machines in some parts of our environment, and it's working fairly well, but I'm seeing occasional duplicate lines, which baffles me.
--
To view this discussion on the web visit https://groups.google.com/d/msgid/ntpowershell/1d610e8599564451a0f1717278a641b5%40smithcons.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ntpowershell/1d610e8599564451a0f1717278a641b5%40smithcons.com.
I’m not seeing either of those at all.
How are you testing this? Are you testing from a script file? What version of PS? Please tell me you aren’t using PS-ISE?
To view this discussion on the web visit https://groups.google.com/d/msgid/ntpowershell/CADy1Ce7r09%2B4cgZhpZ9txo0dt23RoGWEJkDzJmNf1VQJF9_SSA%40mail.gmail.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ntpowershell/f9e002c091f845c3906cd899ff6142e8%40smithcons.com.
MyInvocation and PSScriptRoot and Host are set to very odd values for REPL. (Well, they aren’t odd for a REPL host, but they aren’t what you need/want for a scripting host.)
To view this discussion on the web visit https://groups.google.com/d/msgid/ntpowershell/CADy1Ce5afWUbU9p45evhbpV147qgEPEDU_KB%3DQHMi7nDT%2BMWew%40mail.gmail.com.