Powershell缩短文件路径


将很长的文件路径缩短,并且在powershell和windows中能够识别。下面有一个函数:

function Get-ShortPath($Path)
{
    $code = @'
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError=true)]
    public static extern uint GetShortPathName(string longPath,
    StringBuilder shortPath,uint bufferSize);
'@
    $API = Add-Type -MemberDefinition $code -Name Path -UsingNamespace System.Text -PassThru
    $shortBuffer = New-Object Text.StringBuilder ($Path.Length * 2)
    $rv = $API::GetShortPathName( $Path, $shortBuffer, $shortBuffer.Capacity )
    if ($rv -ne 0)
    {
        $shortBuffer.ToString()
    }
    else
    {
        Write-Warning "Path '$path' not found."
    }
}
#测试
PS C:mossfly> md "Powershell 缩短文件路径缩短文件路径缩短文件路径缩短文件路径缩短文件路径"


    目录: C:mossfly


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         2012/3/30     23:10            Powershell 缩短文件路径缩短文件路径缩短文件路径缩短文
                                             件路径缩短文件路径


PS C:mossfly> Get-ShortPath "Powershell 缩短文件路径缩短文件路径缩短文件路径缩短文件路径缩短
文件路径"
POWERS~1
PS C:mossfly> Test-Path POWERS~1
True
PS C:mossfly> cd POWERS~1
PS C:mossflyPowershell 缩短文件路径缩短文件路径缩短文件路径缩短文件路径缩短文件路径>
本文链接: https://www.pstips.net/powershell-short-path.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注