.NET对 PowerShell 驱动器一无所知(通常也具有不同的工作目录),因此转换为本机文件系统 em>路径是必需的:
在PowerShell代码中:
使用Convert-Path
将基于PowerShell驱动器的路径转换为.NET类型可以理解的本机文件系统路径:
$attributes=[System.IO.File]::GetAttributes((Convert-Path "mydrive:\path\"))
默认情况下(使用位置参数),-Path
使用Convert-Path
执行通配符解析;要抑制后者,请使用-LiteralPath
参数。
注意:Convert-Path
仅适用于现有路径。解除限制是this feature request on GitHub的主题。
使用C#代码:
在PSCmdlet
派生的cmdlet中:
-
使用GetUnresolvedProviderPathFromPSPath()
将基于PS驱动器的路径转换为基于本地驱动器的路径 [1] 未解决除了翻译驱动器部分:
- 未验证路径是否存在(但驱动器名称必须存在)
执行- 和 no 通配符解析。
-
使用GetResolvedProviderPathFromPSPath()
解析基于PS驱动器的路径到基于本机驱动器的路径,这意味着除了转换驱动器部件之外:>
进行- 通配符解析 ,可能会产生多条路径,甚至没有。
- 文字路径成分必须存在。
-
使用提供者ID为"FileSystem"
的{{3}}方法作为System.Management.Automation.PathInfo
实例获取当前文件系统位置的路径;该实例的.Path
属性和.ToString()
方法返回路径的PS形式;使用.ProviderPath
属性获取本机表示形式。
这是一个简单的即席编译的cmdlet,可同时使用两种方法:
# Compiles a Get-NativePath cmdlet and adds it to the session.
Add-Type @'
using System;
using System.Management.Automation;
[Cmdlet("Get","NativePath")]
public class GetNativePathCommand : PSCmdlet {
[Parameter(Mandatory=true,Position=0)]
public string PSPath { get; set; }
protected override void ProcessRecord() {
WriteObject("Current directory:");
WriteObject(" PS form: " + CurrentProviderLocation("FileSystem"));
WriteObject(" Native form: " + CurrentProviderLocation("FileSystem").ProviderPath);
//
WriteObject("Path argument in native form:");
WriteObject(" Unresolved:");
WriteObject(" " + GetUnresolvedProviderPathFromPSPath(PSPath));
//
WriteObject(" Resolved:");
ProviderInfo pi;
foreach (var p in GetResolvedProviderPathFromPSPath(PSPath,out pi))
{
WriteObject(" " + p);
}
}
}
'@ -PassThru | % Assembly | Import-Module
您可以如下进行测试:
# Create a foo: drive whose root is the current directory.
$null = New-PSDrive foo filesystem .
# Change to foo:
Push-Location foo:\
# Pass a wildcard path based on the new drive to the cmdlet
# and have it translated to a native path,both unresolved and resolved;
# also print the current directory,both in PS form and in native form.
Get-NativePath foo:\*.txt
如果当前目录为C:\Temp
,并且恰好包含文本文件a.txt
和b.txt
,您将看到以下输出:
Current directory:
PS form: foo:\
Native form: C:\Temp\
Path argument in native form:
Unresolved:
C:\Temp\*.txt
Resolved:
C:\Temp\a.txt
C:\Temp\b.txt
[1]如果根据 UNC 路径定义了输入路径中引用的PS驱动器(使用New-PSDrive
创建),则本机路径将为也是UNC路径。
本文链接:https://www.f2er.com/3155472.html