Home > Enterprise >  PowerShell import-Csv from dialog box
PowerShell import-Csv from dialog box

Time:10-06

I have a script which prompts the user to enter the path to a Csv file which is then imported. I would like to provide the user with a dialog box which they can use to navigate to the file and then I can pass the file path to Csv-import.

I have tried the following which does open the dialog box but what is getting passed to csv-import is System.Windows.Forms.OpenFileDialog: Title: , FileName: C:\temp\test.csv and not C:\temp\test.csv as I hoped. Is there a way to correct this or am I just using the wrong approach?

Thanks

$fileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{ 
    InitialDirectory = [Environment]::GetFolderPath('Desktop') 
    Filter = 'Documents (*.csv)|*.csv'
}
$null = $fileBrowser.ShowDialog()

$csv = import-Csv $fileBrowser -delimiter ","

CodePudding user response:

The path to the selected file is stored in the FileName property of the dialog:

if ($fileBrowser.ShowDialog() -eq 'OK'){
  $csv = Import-Csv $fileBrowser.FileName -Delimiter ","
}
else {
  # user didn't select a file
}
  • Related