Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 拆分、选择、加入PowerShell_C#_Powershell - Fatal编程技术网

C# 拆分、选择、加入PowerShell

C# 拆分、选择、加入PowerShell,c#,powershell,C#,Powershell,在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"""; 它在空格处拆分字符串,将每个标记转换为引号,然后用空格重新组合标记 我在想这样的事情:

在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
}
如果MakeRootedPath所做的只是返回一个绝对路径,请使用带有适当参数的连接路径。这样,

$s = "abc def ghi"
$r = "c:\root"
$o = $s -split " " | % { join-path $r $_ }

# Check output for single result
$o[1]
c:\root\def

# Print the whole array
$o
c:\root\abc
c:\root\def
c:\root\ghi
至于添加的逻辑,让我们使用.Net方法检查绝对路径。可以使用正则表达式来测试输入。既然已经有了一个库方法,为什么还要费心重新发明轮子呢

function RootedPath($s, $rootPath) {
    if(-not [System.IO.Path]::IsPathRooted($s)) { 
        return join-path $rootPath $s 
    } else { return $s } 
}
$s = "abc d:\def ghi" # NB: 2nd value is absolute path
$o = $s -split ' ' | % { RootedPath $_ "c:\myRoot" }

# Let's generate a fancy output
$p = '"' + $($o -join '" "') + '"'
$p # print output
"c:\myRoot\abc" "d:\def" "c:\myRoot\ghi"
String.Split方法可以像在C中一样使用:

PS> $str = "abc def ghi"
PS> $str.Split(" ")
abc
def
ghi
选择和联接扩展方法不可用,但您可以使用特定于PowerShell的方法和:

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

或ForEach对象cmdlet的管道:


你能提供一个前后示例吗?我已经添加了C伪代码的输出。我在我的问题中添加了这个函数,因为它比这个稍微多一些。我在脚本中使用它使调用东西变得容易。此外,这个答案中缺少连接。我需要一个字符串,就像我在这个问题中所描述的一样。我只想用不同的方式来代替你可以把它串成一个字符串。“Matt true,但是保存显式连接分隔符比不依赖默认行为更好地传达意图。ForEach不为人知。PowerShell 3.0对此是否太旧?@LonelyPixel是的,在PowerShell 4.0中引入了ForEach{}扩展方法
PS> $str = "abc def ghi"
PS> $str.Split(" ")
abc
def
ghi
$str.Split(" ").ForEach({"""$(MakeRootedPath $_)"""}) -join " "
(foreach($s in $str.Split(" ")){"""$(MakeRootedPath $_)"""}) -join " "
($str.Split(" ")|ForEach-Object{"""$(MakeRootedPath $_)"""}) -join " "