I have been working on a script that allows a user to select a csv file from their PC to be operated on, the code I have to get the CSV file is as follows
#function to open a file selection dialouge at the $InitialDirectory, with filetype filter $FileTypeFilter and return the file name
function Get-File($InitialDirectory, $FileTypeFilter) {
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
if ($initialDirectory) {
$OpenFileDialog.initialDirectory = $initialDirectory
}
$OpenFileDialog.filter = $FileTypeFilter
#setup modalform to allow the form object to always be on top
$modalform = New-Object System.Windows.Forms.Form
$modalform.TopMost = $true
#open the dialouge box and ensure a file is selected
if($NULL -ne $OpenFileDialog.ShowDialog($modalform).FileName){
return $OpenFileDialog.FileName
}
else {
#if no file error and exit the script
Throw "No File Selected!"
}
}
the issue I am seeing however is when the user selects a file, it fails the if statement and then throws the error. during debugging however I can see that the filename property of the $openfiledialog object is set to the appropriate filepath string
Image of variable tracking in Powershell Debugging
I have tried first opening the Dialog and then setting a variable = to the FileName as per below, however this leaves the variable blank with no contents and that too fails the check
#function to open a file selection dialouge at the $InitialDirectory, with filetype filter $FileTypeFilter and return the file name
function Get-File($InitialDirectory, $FileTypeFilter) {
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
if ($initialDirectory) {
$OpenFileDialog.initialDirectory = $initialDirectory
}
$OpenFileDialog.filter = $FileTypeFilter
#setup modalform to allow the form object to always be on top
$modalform = New-Object System.Windows.Forms.Form
$modalform.TopMost = $true
$OpenFileDialog.ShowDialog($modalform)
$file = $OpenFileDialog.FileName
#open the dialouge box and ensure a file is selected
if($NULL -ne $File){
return $OpenFileDialog.FileName
}
else {
#if no file error and exit the script
Throw "No File Selected!"
}
}
any help much appreciated
KairiRovco is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.