Odd issue with a fairly simple script

34 views
Skip to first unread message

Kurt Buff

unread,
Jul 31, 2024, 7:12:03 PM7/31/24
to ntpowe...@googlegroups.com
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.

Is there some reason why that might happen with this script? The only thing I can think of is that it's not removing the cimsession correctly, but I don't know why that would be the case.

However, I am getting errors of various kinds, including no name resolution, so I'm wondering if that has anything to do with it.

Thanks,
Kurt

$comps = Get-ADComputer -filter * -searchbase "ou=1,ou=2,dc=example,dc=com" | sort name | select -expand name
foreach ( $comp in $comps ) {
$LAPSPwd = Get-LapsADPassword -Identity $comp -ErrorAction SilentlyContinue -AsPlainText | select -expand Password
$LAPwd = ConvertTo-SecureString -String $LAPSPwd -AsPlainText -Force
$LAAccount = Get-LapsADPassword -Identity $comp -ErrorAction SilentlyContinue -AsPlainText | select -expand Account
$LACred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "$comp\$LAAccount", $LAPwd
New-CimSession -computername $comp -credential $LACred
$Log = [PSCustomObject] @{
Name     = get-ciminstance -classname Win32_ComputerSystem -cimsession $comp | select -expand name
Model    = get-ciminstance -classname Win32_ComputerSystem -cimsession $comp | select -expand model
Serial   = get-ciminstance -classname Win32_SystemEnclosure -cimsession $comp | select -expand serialnumber
Address  = Get-NetIPAddress -cimsession $comp | select -expand ipv4address | where { $_ -like "10.*" }
}
   $Log | Export-Csv -append -notype -encoding ascii -delim "`t" c:\temp\data.csv
   Remove-CimSession -computername $comp
   }
}

Michael B. Smith

unread,
Jul 31, 2024, 7:33:17 PM7/31/24
to ntpowe...@googlegroups.com
So, I would do a couple of things differently, but the most important thing is to wrap the loop with a try/catch, so you catch errors.

I won't be in front of a computer until tomorrow, when I'll make some other suggestions.


From: ntpowe...@googlegroups.com <ntpowe...@googlegroups.com> on behalf of Kurt Buff <kurt...@gmail.com>
Sent: Wednesday, July 31, 2024 7:11:47 PM
To: ntpowe...@googlegroups.com <ntpowe...@googlegroups.com>
Subject: [ntpowershell] Odd issue with a fairly simple script
 
--
You received this message because you are subscribed to the Google Groups "ntpowershell" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ntpowershell...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ntpowershell/CADy1Ce5MyekQe%2BNxaWoyN6%2BMnqDLm7%2Bz5GDXa19toZQyWpE9-A%40mail.gmail.com.

Michael B. Smith

unread,
Aug 1, 2024, 9:26:06 AM8/1/24
to ntpowe...@googlegroups.com

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.

--

Kurt Buff

unread,
Aug 1, 2024, 2:16:10 PM8/1/24
to ntpowe...@googlegroups.com
Got it. The try/catch is a good idea. I've got other scripts that test for connectivity prior to issuing commands - I'll add that in too.

Thanks,
Kurt

Kurt Buff

unread,
Aug 1, 2024, 5:20:45 PM8/1/24
to ntpowe...@googlegroups.com
I added some try/catch stanzas, but I'm seeing some odd results from them.

The most common oddity is that if a try fails, I get a warning (usually), then (always) error text that includes the entire script, with an error appended and in no case do I see the catch's write-error text written to the screen.

Copy of script follows - I chose two hosts specifically to test various errors, and populated variables in the script that in some cases I don't use, just to suppress output to the screen. I can provide more context if needed.

$comps = "itkurt-vm", "itkurt-desk"

foreach ( $comp in $comps ) {
    try {
       $ADAccount = Get-ADComputer -Identity $comp -ErrorAction Stop
    }
    catch {
        Write-Error "Cannot find '$comp' in Active Directory"
        continue
    }
    try {
       $PingResult = test-connection -ComputerName $comp -count 2 -Quiet -ErrorAction Stop
    }
    catch {
        Write-Error "Cannot ping '$comp'"
        continue
    }
    try {
      $Port5985 = Test-NetConnection -ComputerName $comp -Port 5985 -InformationLevel Quiet -ErrorAction Stop
    }
    catch {
        Write-Error "Port 5985 for '$comp' is not open"
        continue
    }
    try {
      $WSMANTest = Test-WSMan -ComputerName $comp -ErrorAction Stop
    }
    catch {
        Write-Error "WSMan for '$comp' is not responding"
        continue
    }
    try {
        $laps = Get-LapsADPassword -Identity $comp -AsPlainText -ErrorAction Stop

    }
    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
        $se = Get-CimInstance -Classname Win32_SystemEnclosure -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  = $se.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
}
On Thu, Aug 1, 2024 at 7:26 AM Michael B. Smith <mic...@smithcons.com> wrote:

Michael B. Smith

unread,
Aug 5, 2024, 3:35:30 PM8/5/24
to ntpowe...@googlegroups.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?

Kurt Buff

unread,
Aug 5, 2024, 4:28:09 PM8/5/24
to ntpowe...@googlegroups.com
LOL - no, not ISE.I really don't like that interface.

PowerShell 5.1, elevated session, and I was copying the script out of Notepad++ into an elevated session, and that is when I get those errors.

Now that I've copied the script to a file called Get-DellDetails.ps1, and am executing it normally, I'm not getting those errors.

I went back and confirmed that the errors appear when pasting the script, rather executing it as a script.

Why that would make a difference is of minor interest, but I can live without an explanation.

What I'm going to do now is set up a second variable to accumulate the errors in the catch sections, so we can pay attention to those.

Thanks for the hint.

Kurt

Kurt



Michael B. Smith

unread,
Aug 5, 2024, 5:10:22 PM8/5/24
to ntpowe...@googlegroups.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.)

Reply all
Reply to author
Forward
0 new messages