如何在PowerShell中获取具有正确(规范)案例的路径?

Gle*_*enn 6 powershell

我有一个脚本,接受一个目录作为用户的参数.我想显示在Windows中显示的目录路径的名称.也就是说,

PS C:\SomeDirectory> cd .\anotherdirectory
PS C:\AnotherDirectory> . .\myscript.ps1 "c:\somedirectory"
C:\SomeDirectory
Run Code Online (Sandbox Code Playgroud)

给定"c:\ somedirectory"时如何检索"C:\ SomeDirectory"?

Ryn*_*ant 6

这应该工作:

function Get-PathCanonicalCase {
    param($path)

    $newPath = (Resolve-Path $path).Path
    $parent = Split-Path $newPath

    if($parent) {
        $leaf = Split-Path $newPath -Leaf

        (Get-ChildItem $parent| Where-Object{$_.Name -eq $leaf}).FullName
    } else {
        (Get-PSDrive ($newPath -split ':')[0]).Root
    }
}
Run Code Online (Sandbox Code Playgroud)

  • [System.IO.Directory] ​​:: GetDirectories("c:\","nameoffolder")正在努力进行单行调用 (2认同)

Aar*_*sen 6

接受的答案只能获得文件的正确大小写.父路径留有用户提供的案例.这是我的解决方案.

$getPathNameSignature = @'
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern uint GetLongPathName(
    string shortPath, 
    StringBuilder sb, 
    int bufferSize);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError=true)]
public static extern uint GetShortPathName(
   string longPath,
   StringBuilder shortPath,
   uint bufferSize);
'@
$getPathNameType = Add-Type -MemberDefinition $getPathNameSignature -Name GetPathNameType -UsingNamespace System.Text -PassThru


function Get-PathCanonicalCase
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]
        # Gets the real case of a path
        $Path
    )

    if( -not (Test-Path $Path) )
    {
        Write-Error "Path '$Path' doesn't exist."
        return
    }

    $shortBuffer = New-Object Text.StringBuilder ($Path.Length * 2)
    [void] $getPathNameType::GetShortPathName( $Path, $shortBuffer, $shortBuffer.Capacity )

    $longBuffer = New-Object Text.StringBuilder ($Path.Length * 2)
    [void] $getPathNameType::GetLongPathName( $shortBuffer.ToString(), $longBuffer, $longBuffer.Capacity )

    return $longBuffer.ToString()
}
Run Code Online (Sandbox Code Playgroud)

我已将上述代码集成到Resolve-PathCase中,这是Carbon PowerShell模块的一部分.免责声明:我是Carbon的所有者/维护者.