-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathShow-OpenFileDialog.ps1
More file actions
51 lines (41 loc) · 1.94 KB
/
Show-OpenFileDialog.ps1
File metadata and controls
51 lines (41 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function Show-OpenFileDialog {
<#
.DESCRIPTION
This function is a PowerShell call to the OpenFileDialog box using WPF.
We'll see many examples of OpenFileDialog using Windows Forms, but we'll try to
get off Windows Forms as it's legacy tech.
.EXAMPLE
PS_>Show-OpenFileDialog
This will open a dialog box to enable the user to select a file. The output of
the function is the full path of that file. It's useful for example to Import-CSV
from a CSV file, or to select an Office document to be opened with PowerShell
application automation...
.EXAMPLE
PS_>$FileName = Show-OpenFileDialog
This will open a dialog box to enable the user to select a file, and the file name
will be stored in the $FileName variable to be reused as described on the first example.
.EXAMPLE
PS_>$FileName = Show-OpenFileDialog -Title "Open an .XLSX file to be parsed" -Filter "Excel file|*.xlsx" -InitialDirectory c:\MyExcelFiles
This will open a dialog box to select a file, with a customized title, and with a default filter on *.xlsx Excel files. This
dialog box will open the C:\MyExcelFiles directory to look for files. User can select later any other folder to look for.
.LINK
https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32?view=net-5.0
#>
param
($Title = 'Select a file to use', $Filter = 'Comma Separated|*.csv|Text|*.txt',$InitialDirectory = "c:\temp")
Add-Type -AssemblyName PresentationFramework
$dialog = New-Object -TypeName 'Microsoft.Win32.OpenFileDialog'
$dialog.Title = $Title
$dialog.Filter = $Filter
If (!(Test-Path $InitialDirectory)){$InitialDirectory = "$($env:Userprofile)\Documents"} #If the default C:\temp doesn't exist, defaults to user's Document folder
$dialog.InitialDirectory = $InitialDirectory
if ($dialog.ShowDialog() -eq $true)
{
Return $dialog.FileName
}
else
{
Write-Warning 'Cancelled'
}
}
Show-OpenFileDialog