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 缩短文件路径缩短文件路径缩短文件路径缩短文件路径缩短文件路径>
|