Hi,
I’m very new to PS scripting, I have the following script to pull some data from AD and write it to an existing CSV file. My question is what would be the best way for me to verify that the script has actually extracted some data before writing to the CSV? What I want to avoid is the script for whatever reason failing to write any data to the CSV. If the script doesn’t successfully pull any data for e.g. AD isn’t accessible I would like it to just exit or be able send an email and exit.
# Define CSV location
$Csvfile = "C:\Output\Users.csv"
# Import Active Directory module
Import-Module ActiveDirectory
# Set security group as searchbase, you can use one security group or multiple groups
$DNs = @(Get-ADGroupMember -Identity "SEC-Office")
# Create empty array
$AllADUsers = @()
# Loop through every DN
foreach ($DN in $DNs) {
$Users = Get-ADUser -SearchBase $DN -Filter * -Properties *
# Add users to array
$AllADUsers += $Users
}
# Create list
$AllADUsers | Sort-Object Name | Select-Object `
@{Label = "First name"; Expression = { $_.GivenName } },
@{Label = "Last name"; Expression = { $_.Surname } },
@{Label = "Display name"; Expression = { $_.DisplayName } },
@{Label = "User logon name"; Expression = { $_.SamAccountName } },
@{Label = "User principal name"; Expression = { $_.UserPrincipalName } },
@{Label = "Street"; Expression = { $_.StreetAddress } },
@{Label = "City"; Expression = { $_.City } },
@{Label = "State/province"; Expression = { $_.State } },
@{Label = "Zip/Postal Code"; Expression = { $_.PostalCode } },
@{Label = "Country/region"; Expression = { $_.Country } },
@{Label = "Job Title"; Expression = { $_.Title } },
@{Label = "Department"; Expression = { $_.Department } },
@{Label = "Company"; Expression = { $_.Company } },
@{Label = "Manager"; Expression = { % { (Get-AdUser $_.Manager -Properties DisplayName).DisplayName } } },
@{Label = "Description"; Expression = { $_.Description } },
@{Label = "Office"; Expression = { $_.Office } },
@{Label = "Telephone number"; Expression = { $_.telephoneNumber } },
@{Label = "E-mail"; Expression = { $_.Mail } },
@{Label = "Mobile"; Expression = { $_.mobile } },
@{Label = "Notes"; Expression = { $_.info } },
@{Label = "Account status"; Expression = { if (($_.Enabled -eq 'TRUE') ) { 'Enabled' } Else { 'Disabled' } } },
@{Label = "Last logon date"; Expression = { $_.lastlogondate } }|
# Export report to CSV file
Export-Csv -Append -Encoding UTF8 -Path $Csvfile
Any help is much appreciated.
Thanks