Prompt Windows for file (will not import csv)

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
        }
    }
}

That’s because you are not bringing a filename along for the ride.
You’re just popping the file lookup dialog.

$csvpath = New-Object System.Windows.Forms.OpenFileDialog -Property @{ InitialDirectory = [Environment]::GetFolderPath('Desktop') }
$null = $csvpath.ShowDialog()


CheckFileExists              : True
Multiselect                  : False
ReadOnlyChecked              : False
ShowReadOnly                 : False
SafeFileName                 : 
SafeFileNames                : {}
AddExtension                 : True
CheckPathExists              : True
DefaultExt                   : 
DereferenceLinks             : True
FileName                     : 
FileNames                    : {}
Filter                       : 
FilterIndex                  : 1
InitialDirectory             : C:\Users\postanote\Desktop
RestoreDirectory             : False
ShowHelp                     : False
SupportMultiDottedExtensions : False
Title                        : 
ValidateNames                : True
CustomPlaces                 : {}
AutoUpgradeEnabled           : True
Tag                          : 
Site                         : 
Container                    : 




$csvpath

# Results

CheckFileExists              : True
Multiselect                  : False
ReadOnlyChecked              : False
ShowReadOnly                 : False
SafeFileName                 : hostlist.txt
SafeFileNames                : {hostlist.txt}
AddExtension                 : True
CheckPathExists              : True
DefaultExt                   : 
DereferenceLinks             : True
FileName                     : E:\Temp\hostlist.txt
FileNames                    : {E:\Temp\hostlist.txt}
Filter                       : 
FilterIndex                  : 0
InitialDirectory             : C:\Users\postanote\Desktop
RestoreDirectory             : False
ShowHelp                     : False
SupportMultiDottedExtensions : False
Title                        : 
ValidateNames                : True
CustomPlaces                 : {}
AutoUpgradeEnabled           : True
Tag                          : 
Site                         : 
Container                    : 

So… change your import line to this…

{
    log -l "Trying to import Active Directory module"
    $csv = import-csv -Path $csvPath.FileName                    #Attempt to import the CSV
}

Hi There,

I have refactored some of your code to make things easier. (Please find the attached link) A couple of points:

  • Use "Requires" statements when you want to import module. PowerShell preloads the module into memory when it starts the script. If the module is not present, Powershell will throw a terminating error.
  • If printing to the screen, use the different logging streams (Write-Warning, Write-Error & Write-Verbose). Write Error will not produce a terminating error.
  • Load functions before the main code. PowerShell executes from top to bottom, therefore the function will be in memory.

https://gist.github.com/ZanattaMichael/9eee5b319c61b87a2b844d656f7d1a0f

Hope this helps!

PSM