What would be the equivalent of the following C# (pseudo) code in PowerShell?
string str = "abc def ghi";
str = str.Split(" ").Select(s => "\"" + MakeRootedPath(s) + "\"").Join(" ");
// Result:
str == @"""C:\root\abc"" ""C:\root\def"" ""C:\root\ghi""";
It splits the string at spaces, converts each token and puts it into quotes, then recombines the tokens with spaces.
I'm thinking about something like this:
$str = $str -Split " " | Select-Object "`"" + (MakeRootedPath $_) + "`"" | -Join " "
But that's mostly made up from fragments I found everywhere and I'm pretty sure it won't work like this. I know I could do it the .NET way and write many lines of [string].Join and all that, but I'm looking for an elegant PowerShell solution. I know it exists but it's complicated to learn the syntax.
PS: Here's the MakeRootedPath function for completeness.
# 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
}
The String.Split() method can be used just like in C#:
PS> $str = "abc def ghi"
PS> $str.Split(" ")
abc
def
ghi
The Select() and Join() extension methods are not available but you can use the PowerShell-specific ForEach() method and the -join operator:
$str.Split(" ").ForEach({"""$(MakeRootedPath $_)"""}) -join " "
The ForEach() extension method is introduced in PowerShell 4.0 - in older version you'll have to use a foreach(){} loop:
(foreach($s in $str.Split(" ")){"""$(MakeRootedPath $_)"""}) -join " "
or pipe to the ForEach-Object cmdlet:
($str.Split(" ")|ForEach-Object{"""$(MakeRootedPath $_)"""}) -join " "
# Suppose you have MakeRootedPath somewhere that does something usefull
# I provide a stub here so it is runnable in a console
function MakeRootedpath {"C:\$args"}
# option 1, use foreach-object
('abc def ghi' -split ' ' | foreach-object { "`"$(MakeRootedPath $_ )`""}) -join ' '
# option 2, use select-object (two times, as you need to expand property)
('abc def ghi' -split ' ' | select-object @{N='Item';E={"`"$(MakeRootedPath $_ )`" "}} |
Select -ExpandProperty Item) -join ' '
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With