如何使用从 Powershell 中选择的文件调用 Windows Explorer?

How do you call Windows Explorer with a file selected from Powershell?

我在编写我的第一个基本 PowerShell 实用程序时遇到了 运行 问题。我需要打开一个资源管理器 window 并选择一个文件,但无法正确获取命令的语法。

我在 SO 上找到了这个答案, and had a read of this excellent blog on external commands, http://edgylogic.com/blog/powershell-and-external-commands-done-right/ - 但仍然无法正常工作。

这是我的示例脚本 (test.ps1):

$myFile = "C:\Projects\Scripts\any.txt"
# The backslash-backticks are to escape the speech marks, once for PowerShell and then again for DOS
& "C:\Projects\Scripts\EchoArgs.exe" /select",\`"$myFile\`""
& "explorer" /select",\`"$myFile\`""

..这是调用它的批处理文件,以防我调用 PowerShell 脚本的方式出现问题:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Projects\Scripts\test.ps1'"

我尝试了几种不同的组合,echoargs 的输出表明语法是正确的(假设 explorer 的参数字符串被视为单个字符串)但是无论我尝试什么,都只会打开一个 explorer window 在 'my documents' 上,参数 ignored/being 被丢弃在某处。

explorer.exe 开关的 MSDN 页面上有一点说逗号是一个空参数,也许这就是我需要通过以不同方式格式化命令来提供的东西?

从 powershell 使用批处理命令有什么意义?你那样只会把自己弄糊涂.. 和我一样。

$myFile = "C:\Projects\Scripts\any.txt"
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = Split-Path $myFile -Parent 
$OpenFileDialog.FileName = Split-path $myfile -leaf
$OpenFileDialog.ShowDialog() | Out-Null

编辑

如果您需要继续走探索路线,试试这个:

Start-Process -FilePath C:\Windows\explorer.exe -ArgumentList "/select, ""$myFile"""

你也可以只使用:

$dir = "\PATH\TO\YOUR\DIRECTORY"
C:\Windows\explorer.exe "/select,$dir"