Reputation: 3
I've got a simple script that works, takes in a list of user Ids and outputs a CSV with their Id, Enabled True / False, and their name. I'm trying to figure out how I can wrap into it a test where if a user is not found based on the Id in the input file, my output will include a "User [Id] is purged." or something similar.
I've been playing around but I'm not sure if I'm going to have to change my output plan to incorporate something like that. Here's what I have working, minus the check for if nothing found, write a message.
Get-Content $ENV:USERPROFILE\desktop\testusers.txt | ForEach {
Get-ADUser -Filter "SamAccountName -eq '$_'" -Properties SamAccountName,Enabled,Name |
Select SamAccountName,Enabled,Name
} | Export-CSV -path $ENV:USERPROFILE\desktop\output.csv -NoTypeInformation
Upvotes: 0
Views: 1939
Reputation: 61218
If I understand correctly, you want to store users Get-ADUser
cannot find as error in the output csv too.
In that case, simply try to get the user but swallow error messages and use an if{..} else {..}
construct where in both cases you output objects with the same properties:
Get-Content "$env:USERPROFILE\desktop\testusers.txt" | Where-Object { $_ -match '\S' } | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$_'" -ErrorAction SilentlyContinue
if ($user) {
# output the properties you need in the csv
$user | Select-Object SamAccountName, Enabled, Name
}
else {
# user does not exist; output a similar object with the error
[PsCustomObject]@{
SamAccountName = "User '$_' does not exist"
Enabled = $null
Name = $null
}
}
} | Export-CSV -path "$env:USERPROFILE\desktop\output.csv" -NoTypeInformation
Upvotes: 1
Reputation: 61083
This will display a warning for those users that could not be found.
Note, -Properties SamAccountName,Enabled,Name
is not needed in this case, the 3 properties are default properties of the cmdlet.
$dom = (Get-ADRootDSE).defaultNamingContext
Get-Content $ENV:USERPROFILE\desktop\testusers.txt | ForEach-Object {
if([string]::IsNullOrWhiteSpace($_)){
continue # go to next iteration if this element is just white space
}
$usr = Get-ADUser -Filter "SamAccountName -eq '$_'" | Select SamAccountName,Enabled,Name
if(-not $usr){
Write-Warning "$_ could not be found on $dom"
continue
}
$usr
} | Export-CSV -path $ENV:USERPROFILE\desktop\output.csv -NoTypeInformation
Upvotes: 0