View difference between Paste ID: fdYgscKv and wSbF9J3x
SHOW: | | - or go back to the newest paste.
1-
$CsvFile = "path\users.csv"
1+
$CsvFile = "path\GetLoggedOnUsersv2.csv"
2-
Get-ADComputer -Filter * -SearchBase "DC=lab,DC=corp"  -Properties * | ForEach-Object {
2+
3-
    $ADComputer = $_
3+
Get-ADComputer -Filter * -SearchBase "DC=lab,DC=corp" | ForEach-Object {
4-
    
4+
	$ADComputer = $_
5-
    Write-Host "Processing $($ADComputer.Name) ... " -BackgroundColor Red -NoNewline
5+
	Write-Host "Processing $($ADComputer.Name) ..." -ForegroundColor White -NoNewline
6
	Try {
7-
    Try {
7+
		$CS = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ADComputer.Name -ErrorAction Stop | Select-Object -Property `
8-
    
8+
			@{n='Computername'; e={$ADComputer.Name}},
9-
            $CS = Get-WmiObject -Class win32_computersystem -ComputerName $ADComputer.Name -ErrorAction Stop | Select-Object -Property `
9+
			@{n='DNSHostName'; e={$ADComputer.DNSHostName}},
10-
                @{n='Computername'; e={$ADComputer.Name}},
10+
			@{n='Department'; e={
11-
			    @{n='DNSHostName'; e={$ADComputer.DNSHostName}},
11+
				If ($_.Username) {
12-
			    @{n='Department'; e={$ADComputer.Department}},
12+
					Try {(Get-ADUser -Identity $_.Username.Split('\')[1] -Property Department -ErrorAction Stop).Department} Catch {"ERROR: $($_.Exception.Message)"}
13-
			    Username,
13+
				}
14-
			    Manufacturer,
14+
			}},
15-
			    Model
15+
			Username,
16-
            Write-Host " OK ($($CS.Manufacturer) $($CS.Model))." -ForegroundColor Green
16+
			Manufacturer,
17-
		    $CS
17+
			Model
18-
     }
18+
		Write-Host " OK ($($CS.Manufacturer) $($CS.Model))." -ForegroundColor Green
19-
    
19+
		$CS
20-
     Catch {
20+
	} Catch {
21
		Write-Host " ERROR: $($_.Exception.Message)" -ForegroundColor Red
22-
            Write-Host " ERROR: $($_.Exception.Message)" -ForegroundColor Red
22+
		$_.Exception.Message | Select-Object -Property @{n='Computername'; e={$ADComputer.Name}}, @{n='Error'; e={$_}}
23-
		    $_.Exception.Message | Select-Object -Property @{n='Computername'; e={$ADComputer.Name}}, @{n='Error'; e={$_}}
23+
	}
24-
     }
24+
} | Select-Object Computername, DNSHostName, Department, Username, Manufacturer, Model, Error |
25
	Export-Csv -Path $CsvFile -NoTypeInformation