支持2.0及以后版本。
某些時候報表中的路徑字符串是非常長的。如果需要你也可以縮寫它,但是這樣路徑就失去的使用價值。最好是使用內置的API它可以靈活的縮略路徑。
接下來要告訴你如何在Powershell腳本中使用C#代碼:
代碼如下:
$newType = @'
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace WindowsAPILib
{
public class Helper
{
[DllImport("shlwapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool PathCompactPathEx(System.Text.StringBuilder pszOut, string pszSrc, Int32 cchMax, Int32 dwFlags);
public static string CompactPath(string Path, int DesiredLength)
{
StringBuilder sb = new StringBuilder(260);
if (PathCompactPathEx(sb, Path, DesiredLength + 1, 0))
{ return sb.ToString(); }
else
{ return Path; }
}
}
}
'@
Add-Type -TypeDefinition $newType
一旦你執行這段代碼,就會產生一個新的.Net類,其中會增加一個新的靜態方法“CompactPath”,現在你就可以這樣使用它了:
代碼如下:
PS> $pshome
C:/Windows/System32/WindowsPowerShell/v1.0
PS> [WindowsAPILib.Helper]::CompactPath($pshome, 12)
C:/W.../v1.0
PS> [WindowsAPILib.Helper]::CompactPath($pshome, 18)
C:/Windows.../v1.0
PS> [WindowsAPILib.Helper]::CompactPath($pshome, 22)
C:/Windows/Sys.../v1.0
新聞熱點
疑難解答