PowerShell - 获取文件夹名称的一部分

3

我使用powershell需要获取文件夹名称的一部分并将其设置为变量。例如,我有一个名为"test-123"的文件夹,路径是c:\tmp\test-123。

我只需要将"-123"设置为变量,并将其用于插入到.txt文件中(替换其他文本)。是否有任何方法可以做到这一点?


你能使用正则表达式来捕获破折号后面的项目吗? - neontapir
我不知道你在想什么。 - charles
2个回答

5
用内置的字符串操作非常简单。
$FullFolderPath = 'C:\tmp\test-123';

#Depending on PowerShell version, you may need ToString() here.
$FolderName = (Split-Path $FullFolderPath -Leaf).ToString();

#Gets the index of the first dash in the file name.  If you know you
#need the last dash, use LastIndexOf('-') instead.
$DashIndex = $FolderName.IndexOf('-');

#Return a substring from a starting position to the end of the string
$FolderNameFromDashToEnd = $FolderName.SubString($DashIndex);

$FolderNameFromDashToEnd 现在的值应该为 -123


谢谢,太好了。还有一个问题,如果我想替换.txt文件中的所有行(第二行),而该行末尾始终有不同的数字(或字符),语法应该是什么? - charles
@fojtyy 我一时也不确定。我不确定你具体在问什么,或者你想要做什么。我建议你发布另一个问题,提供更多细节、样例输入和期望结果。 - Bacon Bits

1
或许是:

或者:

$TestPath = "c:\tmp\test-123";

$TestPath.Split('-') | % { $Wanted = "-" + $_ }

$Wanted

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接