GwenGuts
GwenGuts

Reputation: 509

Split with string in Powershell

I have a problem with a quick function I wrote for splitting Sharepoint specific ids ({id};#{name}):

function GetOnlyValue {
param( 
[string] $fullValue
)

if(![string]::IsNullOrEmpty($fullValue))
{
    # On regarde si on a la valeur
    if($fullValue -Like "*;#*")
    {
        $array = $fullValue -split ";#", 2, "simplematch"

        return $array[-1]
    }
}

return $fullValue
}

But this function does half the job because, for instance, when I pass a value formated like that : myId;#myName the function return me this value: "#myName" instead of "myName".

Thanks for your help !

06/02/2016 EDIT: This function is included in a module that I import in a script. I use it in correlation with a Sharepoint 2013 site, browsing each SPListItem of a SPList:

$formation = GetOnlyValue -fullValue $spItem["Formation"]

Upvotes: 1

Views: 182

Answers (2)

Martin Brandl
Martin Brandl

Reputation: 58931

I can't reproduce your problem, but you can simplify your script using a -replace:

function GetOnlyValue {
    param( 
        [string] $fullValue
    )

    $fullValue -replace '^.*#'
}

Upvotes: 0

beatcracker
beatcracker

Reputation: 6920

I'd use a regex with capture groups:

function GetOnlyValue
{
    Param
    ( 
        [string]$fullValue
    )

    if($fullValue -match '(.*);#(.*)'){
        $Matches[2]
    }
}

Upvotes: 1

Related Questions