Function SelectFile(optional $InitialDir, $Filter)
; If $InitialDir is omitted, the dialog does NOT default to @scriptdir or the
; current working directory - it opens wherever the user last browsed to in
; ANY prior OpenFileDialog on this machine. Pass $InitialDir explicitly if
; starting location matters.
Dim $objSHELLexec, $CMD, $objSHELL, $fh, $paramFile, $rc, $builtFilter
$SelectFile = ""
$paramFile = "%TEMP%\_selectfile_params.txt"
; $Filter accepts any bare extension - txt, pdf, exe, or whatever else - and
; gets built into a full "Label|*.ext" filter automatically, e.g. "txt"
; becomes "TXT files (*.txt)|*.txt". If the caller already passed a full
; filter string (detected by the presence of "|"), it's used exactly as
; given, untouched.
If $Filter <> "" And InStr($Filter, "|") = 0
If Left($Filter, 1) = "."
$Filter = SubStr($Filter, 2)
EndIf
$builtFilter = UCase($Filter) + " files (*." + $Filter + ")|*." + $Filter
Else
$builtFilter = $Filter
EndIf
$fh = FreeFileHandle()
$rc = Open($fh, $paramFile, 5)
$rc = WriteLine($fh, $builtFilter + @CRLF)
$rc = WriteLine($fh, $InitialDir + @CRLF)
$rc = Close($fh)
$CMD = 'powershell.exe -NoProfile -STA -Command "' +
'Add-Type -AssemblyName System.Windows.Forms; ' +
'$p = Get-Content ' + Chr(39) + $paramFile + Chr(39) + '; ' +
'$f = New-Object System.Windows.Forms.OpenFileDialog; ' +
'if ($p[0]) { $f.Filter = $p[0] }; ' +
'if ($p[1]) { $f.InitialDirectory = $p[1] }; ' +
'if ($f.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $f.FileName }"'
$objSHELL = CreateObject("WScript.Shell")
$objSHELLexec = $objSHELL.Exec($CMD)
If Not $objSHELLexec.StdOut.AtEndOfStream
$SelectFile = $objSHELLexec.StdOut.ReadLine()
EndIf
Del $paramFile
EndFunction