ForEach loop Select-Object with custom column - duplicating header

Hello again, I need some extra help!

I have this script in powershell that collects all installed software from machines in a list:

#Set list path
$file= "C:\wklist.txt"
#Get credential
$cre1 = Get-Credential "Enter Credential"
#Loads list content
Get-Content $file |
ForEach-Object {
    #ICMP test 4 packets
    If(Test-Connection -ComputerName $_ -count 4 -Quiet ){
        #Check SO Architecture and query installed software 
        $OSArchitecture = (Get-WmiObject -Class Win32_OperatingSystem -ComputerName $_ -Credential $cre1 | Select-Object OSArchitecture -ErrorAction Stop).OSArchitecture         
        If($OSArchitecture -eq '64-bit'){
            Invoke-Command -cn $_ -ScriptBlock {
                Get-ItemProperty HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*,HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | 
                Select-Object DisplayName,DisplayVersion,InstallDate,@{N='MachineName';E={$env:ComputerName}} | Sort MachineName,DisplayName | ConvertTo-Csv -NoTypeInformation
            } -Credential $cre1
        }
        Else{
            Invoke-Command -cn $_ -ScriptBlock {
                Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*
            } -Credential $cre1
        }
    }
    #If ICMP fails
    Else{New-Object PSObject -Property @{DisplayName="OFFLINE";DisplayVersion="N/A";InstallDate="N/A";MachineName="$_"} | Select-Object DisplayName,DisplayVersion,InstallDate,MachineName
    }
} | Out-File "c:\temp\software_result.csv"

It's outputing the header for every single object in the loop! ATTENTION: I know that I must place the Select-Object outside the loop, then it will work just fine!

The thing is that those registry key do not contain machine names and so I made a custom column with the name of the current workstation in the loop:

@{N='MachineName';E={$env:ComputerName}}

My problem is, if I place the select outside the loop with the Out-File, the custome column will print the my workstation name, not the name of the current workstation inside the loop.

How can I fix it?

Thanks in Advance.


  • Edited by H Souza 1 hour 18 minutes ago
August 21st, 2015 1:51am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics