If strings starts with in PowerShell

JocSch picture JocSch · Feb 26, 2016 · Viewed 134.1k times · Source

Is there a way to check if a string starts with a string?

We are checking the groupmembership from the AD user. Our AD groups look like this: S_G_share1_W

The script for connecting the networkshares should only run if the groupname starts with "S_G_", because we have some other groups too.

$GroupArray = Get-ADPrincipalGroupMembership $env:USERNAME | select samaccountname

foreach ($Group in $GroupArray) {

    if ($Group.StartsWith("S_G_")) {

        $Group = $Group -replace "S_G_", $FileServerRV
        Write-Host $Group

        $Group = $Group.Substring(0, $Group.Length-2)
        Write-Host $Group

        #erstellen des Anzeigennames
        $Groupname = $Group.Replace($FileServerRV, "")
        Write-Host "Call Function with parameter "$Group $Groupname
    }
}

Answer

M.G picture M.G · Feb 26, 2016

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").