如果在PowerShell中字符串以什么开头

59

有没有一种方法可以检查一个字符串是否以另一个字符串开头?

我们正在检查来自AD用户的组成员身份。我们的AD组看起来像这样:S_G_share1_W

只有当组名以"S_G_"开头时,连接网络共享的脚本才应该运行,因为我们还有其他几组。

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

1
$Group.StartsWtih("string") - Matt
1
答案展示了如何使用startswith,这正是您所要求的。 - Matt
1
你的回答提供了一个“如何使用StartsWith()函数”的链接,这是正确的。但是@JocSch在这种情况下遇到的问题是,他试图在对象$Group上使用StartsWith()函数,而不是在该对象的实际属性$Group.samaccountname上使用。 - M.G
1个回答

88

$Group 是一个对象,但实际上您需要检查 $Group.samaccountname.StartsWith("string") 是否成立。

$Group.StartsWith("S_G_") 更改为 $Group.samaccountname.StartsWith("S_G_")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接