59

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
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JocSch
  • 613
  • 1
  • 6
  • 5
  • 1
    `$Group.StartsWtih("string")` – Matt Feb 26 '16 at 14:43
  • 1
    Answer shows how to use startswith which is what you are asking for. – Matt Feb 26 '16 at 14:52
  • 1
    It's wright, that your answer provides a link to "How to use the StartsWith() function", but the problem which @JocSch has in this case is, that he tries to use the `StartsWith()` function on the object $Group and not on the acutal property of this object which is `$Group.samaccountname` – M.G Feb 29 '16 at 07:36

1 Answers1

88

$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_").

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
M.G
  • 1,061
  • 9
  • 19