Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split, Select, Join in PowerShell

Tags:

c#

powershell

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
}
like image 573
ygoe Avatar asked Mar 18 '26 01:03

ygoe


2 Answers

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 " "
like image 169
Mathias R. Jessen Avatar answered Mar 20 '26 15:03

Mathias R. Jessen


# 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 ' '
like image 28
Sigitas Avatar answered Mar 20 '26 13:03

Sigitas