Alex
Alex

Reputation: 664

PowerShell is not splitting param

I have a PowerShell script (below) which accepts an argument (string) and then splits it. For some reason, the code below doesn't work unless I use an intermediate variable like so. My question - why is that the case?

$name2 = $name.Split(" ")

function New-Name {

    param(
    [parameter(Mandatory=$True)]
    [string] $name
    )

    $name = $name.Split(" ")

    Write-Debug $name

    if( $name.Count -gt 1 ) {
        Write-Debug "2+"
    }
    else {
        Write-Debug "1"
    }

}

Upvotes: 1

Views: 294

Answers (2)

Theo
Theo

Reputation: 61253

As cbaconnier says: .Split() returns an array of substrings.
For instance, if you have:

$name = 'John Doe'
$firstname = $name.Split(" ")[0]  # returns "John"
$lastname  = $name.Split(" ")[1]  # returns "Doe"

Instead of using the .Net .Split() method, you could also do the PowerShell -split which uses regular expression and has the advantage of doing the above in one go:

$name = 'John Doe'
$firstname, $lastname = $name -split ' '

Have a look at the String.Split Method for the many overloads you can use and also look at About Split.

Hope that explains @cbaconnier answer

Upvotes: 3

Clément Baconnier
Clément Baconnier

Reputation: 6108

It's happening because you're declaring $name as string but $name.Split(" ") returns an array.

Upvotes: 3

Related Questions