C# PowerShell文件路径
我运行命令(),它返回文件的当前位置 示例:C# PowerShell文件路径,c#,file,powershell,path,C#,File,Powershell,Path,我运行命令(),它返回文件的当前位置 示例:c:\folder1\folder2\folder3\XXX\folder4\folder5 首先,从上面,我想得到XXX的值,让它等于一个变量。我该怎么做 其次,我想得到c:\folder1\folder2\folder3\XXX\folder4\的值,并让它等于一个变量。我该怎么做 我使用了占位符folder1,folder2等来进行说明。这些是动态的。要获取变量的路径,可以执行以下操作: $a = (Get-Location).Path $xx
c:\folder1\folder2\folder3\XXX\folder4\folder5
首先,从上面,我想得到XXX的值,让它等于一个变量。我该怎么做
其次,我想得到c:\folder1\folder2\folder3\XXX\folder4\
的值,并让它等于一个变量。我该怎么做
我使用了占位符
folder1
,folder2
等来进行说明。这些是动态的。要获取变量的路径,可以执行以下操作:
$a = (Get-Location).Path
$xxx = (Split-Paths "c:\folder1\folder2\folder3\XXX\folder4\folder5")[-5]
然后,如果要将路径中“XXX”部分的值设置为变量,可以使用split()函数:
$x = $a.split('\')[4]
您可以使用正则表达式:
$rawtext = "If it interests you, my e-mail address is tobias@powershell.com."
# Simple pattern recognition:
$rawtext -match "your regular expression"
*True*
# Reading data matching the pattern from raw text:
$matches
$matches
返回结果
有关详细信息,请选中(需要注册)。您可以使用正则表达式执行此操作:
PS> $path = 'c:\folder1\folder2\folder3\XXX\folder4\folder5'
PS> $path -match 'c:\\([^\\]+)\\([^\\]+)\\([^\\]+)\\([^\\]+)'
True
PS> $matches
Name Value
---- -----
4 XXX
3 folder3
2 folder2
1 folder1
0 c:\folder1\folder2\folder3\XXX
要首先回答第二个问题:要使父级访问完整路径,请使用“拆分路径”:
$var = Split-Path -parent "c:\folder1\folder2\folder3\XXX\folder4\folder5"
对于您的另一个问题,此函数将拆分路径中的所有元素并将它们返回到一个数组中:
function Split-Paths($pth)
{
while($pth)
{
Split-Path -leaf $pth
$pth = Split-Path -parent $pth
}
}
然后,您可以像这样抓取第五个元素:
$a = (Get-Location).Path
$xxx = (Split-Paths "c:\folder1\folder2\folder3\XXX\folder4\folder5")[-5]
请注意,该函数以“反向”顺序返回元素,因此使用负索引从数组末尾开始索引。其中一些答案非常接近,但每个人都忘记了它们的shell fu
$FirstAnswer = (Get-Item ..\..).Name
$SecondAnswer = (Get-Item ..).FullName