Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does -join ";" work?

This answer includes a Powershell like of code that splits $env:path, applies a filter and puts the result together, to store it in $env:path.

$path = ($path.Split(';') | Where-Object { $_ -ne 'ValueToRemove' }) -join ';'

I was reading this code, and then, suddenly, a wild -join ';' appears. How does this work? What is the concept behind this? I would expect (<expression) would eventually become some object, but then this like reads <object> -join ';', so the join part would still be some independent token. How is it evaluated? I can see that it obviously does "the right thing", but how and why does it work? How exactly does Powershell evaluate this line? Looks like very dark magic to me.

like image 879
user1129682 Avatar asked Jan 17 '26 10:01

user1129682


1 Answers

As stated out by the docs the -Join Operator can be used mainly in two ways:

-Join <String[]>
<String[]> -Join <Delimiter>

Most of PowerShells operators work this way (and look similiar to method parameters). You got some values on the left side of an operator and execute an action (in this case joining) with the right-side-token, in your case the semicolon ;.

Take a look at the help (by typing Get-Help <section_name>) sections about_Join and about_Operators

Also a nice example copied from the docs (without the need of splitting beforehand) is:

PS> $a = "WIND", "S P", "ERSHELL"
PS> $a -join "OW"
WINDOWS POWERSHELL
like image 130
Clijsters Avatar answered Jan 20 '26 02:01

Clijsters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!