I have a script that was working jsut fine and now suddenly stopped working. The issue is that my script takes a spreadsheet and uses the email addresses on it to query AD and then find the users email, manager and manager email address. My script needs to be able to put blank liones in the output spreadsheet so that the output spreadsheet has the exact same number of lines as the input spreadsheet and everything is in the exact same order.
Currently if my script finds a user who has no manager listed it stops and will not run. How can I alter my script so that it is basically foolproof, and that if it cant find the necessary information it needs to put a 'NA' or 'Not Found' in the output spreadsheet.
#NOTE: Source file must have email as the column header for this script to work!!!
#Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# Import the data from CSV file and assign it to variable
Import-Module ActiveDirectory
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$ErrorActionPreference = 'Stop'
$OpenFIleDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select a CSV File to process"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.Filter = "CSV (*.csv) | *.csv"
$OpenFileDialog.ShowDialog() | Out-Null
$Path = $OpenFileDialog.Filename
$user = Import-Csv -Path $Path
Function Get-FileName($initialDirectory) {
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveFileDialog.Title = "Where do you want to save the file?"
$SaveFileDialog.initialDirectory = $initialDirectory
$SaveFileDialog.filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*";
$SaveFileDialog.ShowDialog() | Out-Null
$SaveFileDialog.filename
}
$SaveMyFile = Get-Filename
$params = @{
Properties = 'mail', 'samaccountname', 'manager'
}
$object = {
param(
$mail,
$samAccountName = 'Not Found',
$manager = 'Not Found',
$managerEmail = 'Not Found'
)
[pscustomobject]@{
Mail = $mail
SamAccountName = $samAccountName
Manager = $manager
ManagerEmail = $managerEmail
}
}
[System.Windows.Forms.MessageBox]::Show('Script Starting . . .','Begin Script')
$user | ForEach-Object {
# if there is no value in this column for this object
if([string]::IsNullOrWhiteSpace($_.email)) {
#skip it, go next
return
}
$params['Filter'] = "mail -eq '$($_.email)'"
$aduser = Get-ADUser @params
if(-not $aduser) {
return & $object -Mail $_.email
}
$manager = $aduser.Manager | Get-ADUser -Properties mail
& $object $aduser.Mail $aduser.SamAccountName $manager.Name $manager.mail
} | Export-CSV -Path $SaveMyFile -NoTypeInformation
[System.Windows.Forms.MessageBox]::Show('Script Complete.','Completed')