当前位置: 移动技术网 > IT编程>脚本编程>Shell > Powershell使用C#实现缩写路径

Powershell使用C#实现缩写路径

2017年12月08日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网