"\"" + Ma-6ren">
gpt4 book ai didi

c# - 在 PowerShell 中拆分、选择、加入

转载 作者:行者123 更新时间:2023-11-30 20:38:37 26 4
gpt4 key购买 nike

PowerShell 中的以下 C#(伪)代码等效于什么?

string str = "abc def ghi";
str = str.Split(" ").Select(s => "\"" + MakeRootedPath(s) + "\"").Join(" ");
// Result:
str == @"""C:\root\abc"" ""C:\root\def"" ""C:\root\ghi""";

它按空格分割字符串,转换每个标记并将其放入引号中,然后将标记与空格重新组合。

我正在考虑这样的事情:

$str = $str -Split " " | Select-Object "`"" + (MakeRootedPath $_) + "`"" | -Join " "

但这主要是由我随处发现的碎片组成的,我很确定它不会像这样工作。我知道我可以用 .NET 方式来完成,并编写许多行 [string].Join 等等,但我正在寻找一个优雅的 PowerShell 解决方案。我知道它存在,但学习语法很复杂。

PS:为了完整性,这是 MakeRootedPath 函数。

# Returns a rooted path. Non-rooted paths are interpreted relative to $rootDir.
#
function MakeRootedPath($path)
{
if (![System.IO.Path]::IsPathRooted($path))
{
return "$rootDir\$path"
}
return $path
}

最佳答案

String.Split() 方法的使用方式与 C# 中一样:

PS> $str = "abc def ghi"
PS> $str.Split(" ")
abc
def
ghi

Select()Join() 扩展方法不可用,但您可以使用 PowerShell 特定的 ForEach() method-join operator :

$str.Split(" ").ForEach({"""$(MakeRootedPath $_)"""}) -join " "

PowerShell 4.0 中引入了 ForEach() 扩展方法 - 在旧版本中,您必须使用 foreach(){} 循环:

(foreach($s in $str.Split(" ")){"""$(MakeRootedPath $_)"""}) -join " "

或通过管道连接到 ForEach-Object cmdlet:

($str.Split(" ")|ForEach-Object{"""$(MakeRootedPath $_)"""}) -join " "

关于c# - 在 PowerShell 中拆分、选择、加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35013577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com