PowerShell不支持UNC路径异常。

3
我已经为此苦苦挣扎了很久。我有一个项目需要比较两个文件夹,一个在两个服务器上的每个文件夹中各有一个。我们将比较源服务器上的文件与目标服务器上的文件,并创建一个需要在目标服务器完成更新后刷新源文件的列表。
以下是我的脚本(非常感谢原作者http://quickanddirtyscripting.wordpress.com):
param ([string] $src,[string] $dst)

function get-DirHash()
{
    begin 
    {
        $ErrorActionPreference = "silentlycontinue"
    }
    process 
    {
        dir -Recurse $_ | where { $_.PsIsContainer -eq $false -and ($_.Name -like "*.js" -or $_.Name -like "*.css"} | select Name,FullName,@{Name="SHA1 Hash"; Expression={get-hash $_.FullName -algorithm "sha1" }}
    }
    end 
    {
    }
}  

function get-hash 
{
    param([string] $file = $(throw 'a filename is required'),[string] $algorithm = 'sha256')
    try
    {
        $fileStream = [system.io.file]::openread((resolve-path $file));
        $hasher = [System.Security.Cryptography.HashAlgorithm]::create($algorithm);
        $hash = $hasher.ComputeHash($fileStream);
        $fileStream.Close();
    }
    catch
    {
        write-host $_
    }
    return $hash
}

Compare-Object $($src | get-DirHash) $($dst | get-DirHash) -property @("Name", "SHA1 Hash")

现在,如果我使用本地路径运行此命令,例如c:\temp\test1 c:\temp\test2,则可以正常工作。但是,当我使用两台服务器之间的UNC路径运行它时,我会收到以下异常消息:

Exception calling "OpenRead" with "1" argument(s): "The given path's format is not supported."

请指导一下。最终结果应该是文件列表,但由于某种原因它不喜欢UNC路径。

脚本名称为compare_js_css.ps1,调用方式如下:

.\compare_js_css.ps1 c:\temp\test1 c:\temp\test2 <-- 这个能工作

.\compare_js_css.ps1 \\\\devserver1\c$\websites\site1\website \\\\devserver2\c$\websites\site1\website <-- 返回上述异常。

为什么?

3个回答

7
这将给出你需要的路径,而不需要使用 Microsoft.PowerShell.Core\FileSystem:::
(Resolve-Path $file).ProviderPath

不需要使用字符串替换。

运行得很好,但我们为什么需要它? - NealWalters
我鼓励你考虑下面 @piers7 的回复。 - Parth Shah

1

1

OpenRead 支持 UNC 路径。 Resolve-Path 返回一个对象。使用 (Resolve-Path MyFile.txt).Path.Replace('Microsoft.PowerShell.Core\FileSystem::', '') 作为 OpenRead 的参数。当使用 UNC 路径时,Resolve-Path 返回的路径包含 PowerShell 的完全限定模式,其中包含一个标题,该标题不受 OpenRead 方法支持,因此需要省略。


嗯...还是出现了相同的错误。我知道这不是权限问题,因为我在两台服务器上都有管理员访问权限。 - Bob Lyman
我得到了 Microsoft.PowerShell.Core\FileSystem::\ltlymanb\test1\style.min.css。 - Bob Lyman
抱歉,以下是我一直在尝试的内容。.\compare_js_css.ps1 \ltlymanb\c$\temp\test1 \ltlymanb\c$\temp\test2 - Bob Lyman
我也运行了这个命令,结果一样。 .\compare_js_css.ps1 \ltlymanb\c$\websites\test\website \c2devweb4\c$\websites\test\website - Bob Lyman
@BobLyman OpenRead 不支持路径中的 Microsoft.PowerShell.Core\FileSystem:: 部分。你可以这样做:(Resolve-Path $file).Path.Replace('Microsoft.PowerShell.Core\FileSystem::', '') - Andy Arismendi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接