.NET 对PowerShell驱动器一无所知(通常也有不同的工作目录),因此需要转换为文件系统本地路径:
在 PowerShell 代码中:
用于Convert-Path
将基于 PowerShell 驱动器的路径转换为 .NET 类型可以理解的本机文件系统路径:
$attributes=[System.IO.File]::GetAttributes((Convert-Path "mydrive:\path\"))
默认情况下(使用位置参数)和 with -Path
,Convert-Path
执行通配符解析;要抑制后者,请使用-LiteralPath
参数。
警告:Convert-Path
仅适用于现有路径。解除该限制是GitHub 上此功能请求的主题。
在 C# 代码中:
在PSCmdlet
- 派生的 cmdlet 中:
这是一个简单的临时编译的 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
New-PSDrive
[1] 如果输入路径中引用的 PS 驱动器(使用 创建)是根据UNC路径定义的,则生成的本机路径也将是 UNC 路径。