The code below works when I manually set the csvpath to the path of the csv file.
Using the windows forms and selecting the csv file it fails at $csv = import-csv -Path $csvPath
Add-Type -AssemblyName System.Windows.Forms
$csvpath = New-Object System.Windows.Forms.OpenFileDialog -Property @{ InitialDirectory = [Environment]::GetFolderPath('Desktop') }
$null = $csvpath.ShowDialog()
function Log {
#Create a logging function that writes to console, and colour codes according to whether it's an Error or not
Param($l, $type)
$time = get-date -f HH:mm:ss
if ($type -match "error"){
write-host $time -f Gray -NoNewline ; write-host " ERROR: " -f Red -NoNewline ; write-host $l -f DarkYellow
}
elseif ($type -match "warn"){
write-host $time -f Gray -NoNewline ; write-host " WARNING: " -f Magenta -NoNewline ; write-host $l -f Yellow
}
else {
write-host $time -f Gray -NoNewline ; write-host " INFO: " -f Cyan -NoNewline ; write-host $l -f Green
}
}
try{
log -l "Trying to import Active Directory module"
$csv = import-csv -Path $csvPath #Attempt to import the CSV
}
catch{
log -l "Unable to import CSV. Please check the file exists" -type "ERROR"
log -l "Stopping script..." -type "ERROR"
pause #Pause the script if the CSV cannot be loaded
}
finally{
if (!($error[0])){ #If the CSV loaded, then
try{
import-module ActiveDirectory #Try to import the AD module
}
catch{
log -l "Unable to import Active Directory module" -type "ERROR"
log -l "Stopping script..." -type "ERROR"
pause #Pause the script if the AD module cannot be imported
}
}
}