By José C. Nieves Pérez
# Connect to Active Directory
Import-Module ActiveDirectory
# Get list of computers from Active Directory
$computers = Get-ADComputer -Filter * -Property *
# Loop through each computer and output information
foreach ($computer in $computers) {
# Define a hashtable to store the properties we want to output
$output = @{
'ComputerName' = $computer.Name
'OperatingSystem' = $computer.OperatingSystem
'OperatingSystemVersion' = $computer.OperatingSystemVersion
'LastLogonDate' = $computer.LastLogonDate
'Description' = $computer.Description
'OU' = $computer.DistinguishedName
'Enabled' = $computer.Enabled
}
# Create a PSObject with the output hashtable, and export it to CSV
New-Object -TypeName PSObject -Property $output | Export-Csv -Path "C:\temp\computer_inventory.csv" -Append -NoTypeInformation
}
The script starts by importing the ActiveDirectory module and using the Get-ADComputer cmdlet to retrieve a list of all computers from Active Directory, just like before.
Next, the script loops through each computer in the $computers list using a foreach loop, just like before. For each computer, the script creates a hashtable called $output, which contains the properties we want to output to the CSV file. In addition to the properties from the previous version of the script, we’ve added the ‘OperatingSystem’ and ‘OU’ properties to this hashtable.
The ‘OperatingSystem’ property uses the OperatingSystem property of the computer object to retrieve the operating system of the computer. The ‘OU’ property uses the DistinguishedName property of the computer object to retrieve the distinguished name of the OU where the computer is located.
After defining the output hashtable, the script creates a PSObject with the hashtable as its properties using the New-Object cmdlet, just like before. This PSObject represents a single row of data that will be exported to the CSV file.
Finally, the script uses the Export-Csv cmdlet to export the PSObject to a CSV file, just like before. The -Path parameter specifies the path to the CSV file, which is set to C:\temp\computer_inventory.csv. The -Append parameter ensures that new data is added to the existing file instead of overwriting it. The -NoTypeInformation parameter removes the object type information from the CSV file, just like before.