如何在不使用任何 3rd 方工具或手动的情况下将 UNC Windows 文件路径转换为文件 URI?

Gab*_*air 7 windows file-management windows-explorer unc uri

在Microsoft的一篇博客文章中,他们说明了如何编写 URI 来指定本地系统文件路径。

当共享网络共享文件的路径时,一些聊天程序会在浏览器中打开这些文件。

所以我手工编写了将 Windows 路径转换为文件 URI 所需的更改

UNC Windows path: \\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt
Run Code Online (Sandbox Code Playgroud)

变成

URI: file://sharepoint.business.com/DavWWWRoot/rs/project%201/document.txt
Run Code Online (Sandbox Code Playgroud)

我每次都厌倦了手动编码,想知道是否有一种方法可以快速转换为文件 URI。

我在我的机器上没有管理员权限,所以我无法安装软件。

And*_*ker 7

最简单的方法是使用 PowerShell 代码中的 .Net URI 类:

[System.Uri]'\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt' 会给你一个 URI,然后“AbsoluteURI”属性会给你一个字符串。所以:

([System.Uri]'\\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt').AbsoluteUri
Run Code Online (Sandbox Code Playgroud)

会给你你想要的。


Dev*_*cer 5

PowerShell 是自动执行上述繁琐的重复任务的绝佳方法!

使用PowerShell

使用 PowerShell(所有版本)将上述 UNC 路径转换为文件 URI 非常简单,只需要格式替换运算符,例如:

$Path = "\\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt"

# replace back slash characters with a forward slash, url-encode spaces,
# and then prepend "file:" to the resulting string

# note: the "\\" in the first use of the replace operator is an escaped
# (single) back slash, and resembles the leading "\\" in the UNC path
# by coincidence only

"file:{0}" -f ($Path -replace "\\", "/" -replace " ", "%20")
Run Code Online (Sandbox Code Playgroud)

产生以下结果:

file://sharepoint.business.com/DavWWWRoot/rs/project%201/document.txt
Run Code Online (Sandbox Code Playgroud)

作为可重用函数

最后,应尽可能将上述重复任务制作成 PowerShell 函数。这可以节省将来的时间,并确保每个任务始终以完全相同的方式执行。

以下函数与上面的函数等效:

function ConvertTo-FileUri {
    param (
        [Parameter(Mandatory)]
        [string]
        $Path
    )

    $SanitizedPath = $Path -replace "\\", "/" -replace " ", "%20"
    "file:{0}" -f $SanitizedPath
}
Run Code Online (Sandbox Code Playgroud)

定义函数(并加载到当前 PowerShell 会话中)后,只需按名称调用该函数并提供要转换的 UNC 路径作为参数,例如:

ConvertTo-FileUri -Path "\\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt"
Run Code Online (Sandbox Code Playgroud)