Andy Walker
Andy Walker

Reputation:

Powershell Joins

Im trying to join a number of elements of an array into a string using this;

$a = "h","e","l","l","o"
$b = [string]::join("", $a[0,1,2,3])

But I get a 'Missing ')' in method call' error. The join documentation only mentions joining all the elements of an array, not elements at specific indexes. Can this be done?

Cheers

Andy

Upvotes: 10

Views: 2647

Answers (3)

Shay Levy
Shay Levy

Reputation: 126902

PS > & {$ofs=""; "$($a[0,1,2,3])"}  
hell

Upvotes: 8

Peter Reavy
Peter Reavy

Reputation: 165

More idiomatic: use PowerShell's built-in join operator like this:

PS> $a[0,1,2,3] -join ""
hell

Upvotes: 1

dance2die
dance2die

Reputation: 36955

Wrap the content of "$a[0,1,2,3]" with "$()" or "()"

PS> [string]::join("", $($a[0,1,2,3]))
hell
PS> [string]::join("", ($a[0,1,2,3]))
hell

-- Or --

you can use range operator ".."

PS> [string]::join("", $a[0..3])
hell

Upvotes: 13

Related Questions