方法调用失败,因为 [Selected.Microsoft.ActiveDirectory.Mangement.ADGroup] 不包含名为 'substring' 的方法

Method invocation failed because [Selected.Microsoft.ActiveDirectory.Mangement.ADGroup] doesn't contain a method named 'substring'

我很难过。我有我认为应该在脚本中工作的东西来拉动所有组并从 AD 中获取这些组中的用户。

    $ADGroupList = Get-ADGroup -Filter * | Select Name | Sort Name
    ForEach($Group in $ADGroupList)
    {
        $GroupName = $Group.substring($Group.length -7, $Group.length -8)
        $members = Get-ADGroupMember -Identity "$GroupName" | Select Name, SAMAccountName | Sort Name
        ForEach($member in $members)
        {
            Write-Host ($member.Name + "," + $member.SAMAccountName  + "," + $Group.name)
        }
    }

它一直失败并出现以下错误:

Method invocation failed because [Selected.Microsoft.ActiveDirectory.Mangement.ADGroup] doesn't contain a method named 'substring'

我哪里做错了?我以为 SubString 是 PowerShell 方法?

您要获取对象名称的子字符串。将您的小组声明更改为此,

$GroupName = $Group.Name.substring($Group.Name.length -7, $Group.Name.Length -8)
             #    string.substring(startIndex           , number of characters)

备注 Powershell 的 substring 方法从该索引中获取索引和所需的字符数。 .substring 方法不像人们想象的那样有开始和结束。

文档:

Substring()
Return part of a longer string.

Syntax
      .Substring( StartIndex [, length] )


Key
   StartIndex  Characters to skip from the start of the string.
               Use 0 to start from the beginning of the string.
               Cannot be less than zero.

   length      The number of characters to return.
               Cannot be less than zero or longer than the string.
               If omitted all remaining characters will be returned.

以防将来有人无意中发现这里是最终结果,包括输出到 csv:

    $ADGroupList = Get-ADGroup -Filter * | Select Name | Sort Name
    "Group,UserName,Name" | Out-File -FilePath OutputUserGroups.csv -Append -Encoding ASCII
    ForEach($Group in $ADGroupList)
    {
        $GroupName = $Group.Name.substring(7)
        $members = Get-ADGroupMember -Identity "$GroupName" | Select Name, SAMAccountName | Sort Name   
        ForEach($member in $members)
        {
            ($Group.name + "," + $member.SAMAccountName + "," + $member.Name) | Out-File -FilePath OutputUserGroups.csv -Append -Encoding ASCII
        }
    }