If strings starts with in PowerShell

PowershellIf StatementStartswith

Powershell Problem Overview


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
    }
}

Powershell Solutions


Solution 1 - Powershell

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJocSchView Question on Stackoverflow
Solution 1 - PowershellM.GView Answer on Stackoverflow