脚本专栏 
首页 > 脚本专栏 > 浏览文章

Powershell使用C#实现缩写路径

(编辑:jimmy 日期: 2025/3/13 浏览:3 次 )

支持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

上一篇:Powershell脚本中包含文件资源的例子
下一篇:Powershell实现从注册表获取用户配置脚本分享
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap