Search code examples
powershellwmi

Powershell script in columns instead of rows


I was trying to write a script which would use a text file with hostnames and needs to generate a file with the extra data. I can only manage to get it in rows instead of columns:

Model: 
Bios Version: 
TPM OEM Ver: 
User logged In:

I would also like to get the emailaddress from the logged on user. I was thinking to use get-aduser. Could I add another foreach after the current code, using the column with the usernames? How would I do this? All help is greatly appreciated!

My code is:

$output = foreach ($hostname in Get-Content C:\temp\hostnames.txt)
{
$computerinfo = get-ciminstance -computername $hostname Win32_ComputerSystem
$computerBIOS = get-ciminstance -computername $hostname Win32_BIOS
$tpm = Get-ciminstance -class Win32_Tpm -namespace root\CIMV2\Security\MicrosoftTpm -ComputerName $hostname
"Hostname: " + $computerinfo.name
"Model: " + $computerinfo.Model 
"Bios Version: " + $computerBIOS.smbiosbiosversion
"TPM OEM Ver: " + $tpm.ManufacturerVersion
"User logged In: " + $computerinfo.UserName
} 
$output | out-file 'C:\Temp\hostnames3.txt' -append

Solution

  • You should use the CSV file format instead of plain text for structured data. That makes it easier to use them for further steps if needed.

    $output = 
    foreach ($hostname in Get-Content C:\temp\hostnames.txt) {
        $computerinfo = Get-CimInstance -ComputerName $hostname -ClassName Win32_ComputerSystem
        $computerBIOS = Get-CimInstance -ComputerName $hostname -ClassName Win32_BIOS
        $tpm = Get-CimInstance -Namespace root\CIMV2\Security\MicrosoftTpm -ComputerName $hostname -ClassName Win32_Tpm
        [PSCustomObject]@{
            Hostname       = $computerinfo.name
            Model          = $computerinfo.Model
            Bios_Version   = $computerBIOS.smbiosbiosversion
            TPM_OEM_Ver    = $tpm.ManufacturerVersion
            User_logged_In = $computerinfo.UserName
        }
    } 
    $output | 
        Export-Csv -Path 'C:\Temp\hostnames3.csv' -NoTypeInformation
    

    In my experience the UserName property of the CIM-Class Win32_ComputerSystem is unreliable to determine the logged on user. I usually use good old quser.exe like this:

    $UserQuery = ( C:\Windows\System32\quser.exe /server:$hostname 2> null)
            if ($UserQuery) {
                $UserQuery[1].Trim() -match "^(\S+)\s+.*((\d{2}\.){2}\d{4}\s+\d{2}:\d{2})" | Out-Null
                $LoggedOnUser = $Matches[1]
                $LogonTime = Get-Date -Date $Matches[2]
            }
    

    Then you can use $LoggedOnUser and $LogonTime to include it in your output object if you like.

    Of course you can include a additional AD query for more information about the logged on user.