【问题标题】:Powershell: How can I get the UNC path from an OpenFileDialog without the leaf?Powershell:如何在没有叶子的情况下从 OpenFileDialog 获取 UNC 路径?
【发布时间】:2023-02-09 23:59:52
【问题描述】:

我仍然是 Powershell 的初学者...... 我正在使用 OpenFileDialog 让用户可以选择网络上的文件。

为 OpenFileDialog 和 MessageBox 添加一些 .net 程序集

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName PresentationFramework

这是 OpenFileDialog 定义

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog

有了这个,OpenFileDialog 将被打开并显示给用户选择一个文件

$null = $FileBrowser.ShowDialog()

这是用户在 OpenFileDialog 中选择的带有扩展名的 UNC 文件名

$full_filename = $FileBrowser.FileName

这只是用户在 OpenFileDialog 中选择的带有扩展名 (leaf) 的文件名

$filename = $FileBrowser.SafeFileName

这会将数组元素转换为字符串

$full_filename_string = [string]$full_filename
$filename_string = [string]$filename

到目前为止,一切都很好。 我还需要的是仅来自子目录的 UNC 路径,用户在其中选择了一个文件(没有叶子的 UNC 路径)。

这怎么可能实现呢?

【问题讨论】:

  • 您需要的描述有点令人困惑 - 您能否展示一个 $full_filename_string 的示例以及您想要的结果是什么样的?
  • 感谢您的评论。 $full_filename_string 的示例:\\contoso.com\data\sub11\sub12\sub13\leaf.txt

标签: powershell path openfiledialog unc


【解决方案1】:

使用 Split-Path cmdlet:

PS ~> '\hostnamesharepath	odirectorywith_file.exe' |Split-Path -Parent
\hostsharepath	odirectory

请注意,在 Linux 文件系统上,Split-Path 会将 转换为 /,以避免您必须在最后一次出现 时手动拆分字符串:

PS ~> $path,$name = '\hostnamesharepath	odirectorywith_file.exe' -split '\(?=[^\]*$)'
PS ~> $path
\hostnamesharepath	odirectory
PS ~> $name
with_file.exe

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多