文件浏览器
2016.3.20 更新:
由于 PowerShell 是当今几乎所有现代 Windows 安装的本机组件,因此我声明不再需要 C# 回退。如果您仍然需要它来兼容 Vista 或 XP,我 moved it to a new answer。从这个编辑开始,我将脚本重写为 Batch + PowerShell 混合体,并结合执行多选的能力。它更容易阅读和根据需要进行调整。
<# : chooser.bat
:: launches a File... Open sort of file chooser and outputs choice(s) to the console
:: https://stackoverflow.com/a/15885133/1683264
@echo off
setlocal
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
echo You chose %%~I
)
goto :EOF
: end Batch portion / begin PowerShell hybrid chimera #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
$f.ShowHelp = $true
$f.Multiselect = $true
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
这会导致一个文件选择器对话框。
选择的结果将You chose C:\Users\me\Desktop\tmp.txt 输出到控制台。如果要强制选择单个文件,只需将$f.Multiselect 属性更改为$false。
(PowerShell 命令无情地从Just Tinkering Blog 中窃取。)有关您可以设置的其他属性,请参阅OpenFileDialog Class 文档,例如Title 和InitialDirectory。
文件夹浏览器
2015.08.10 更新:
由于invoking a folder chooser已经有了COM方法,所以很容易构建一个可以打开文件夹选择器并输出路径的PowerShell单行器。
:: fchooser.bat
:: launches a folder chooser and outputs choice to the console
:: https://stackoverflow.com/a/15885133/1683264
@echo off
setlocal
set "psCommand="(new-object -COM 'Shell.Application')^
.BrowseForFolder(0,'Please choose a folder.',0,0).self.path""
for /f "usebackq delims=" %%I in (`powershell %psCommand%`) do set "folder=%%I"
setlocal enabledelayedexpansion
echo You chose !folder!
endlocal
在BrowseForFolder() 方法中,第四个参数指定层次结构的根。有关有效值的列表,请参阅 ShellSpecialFolderConstants。
这会导致一个文件夹选择器对话框。
选择的结果将You chose C:\Users\me\Desktop 输出到控制台。
请参阅FolderBrowserDialog class 文档了解您可以设置的其他属性,例如RootFolder。如果需要,可以在此答案的revision 4 中找到我原来的 .NET System.Windows.Forms PowerShell 和 C# 解决方案,但这种 COM 方法更易于阅读和维护。