是否可以从MemberOf Active Directory返回单个值并插入到SQL表中

时间:2018-06-15 18:18:56

标签: powershell active-directory

我试图从MemberOf列中获取单个值,是否可以解析该值并仅返回该字符串的一部分,例如值0012? 这是catagory成员的输出。

CN=Active VMS Users,OU=VMS,DC=evilcorp,DC=net CN=JOJOE\, MOE- 0012,
OU=Site Groups,OU=VMS,DC=evilcorp,DC=net

这是我的代码

$ADARRAY= Get-ADGroupMember -Identity "Domain Users" -Recursive | 
Get-ADUser -Filter "Mail -like '*'" -and "MemberOf -like '*'"| 
Get-ADUser -Properties ('Mail','MemberOf')

<# this was my first try #>
    # $CN = $CN -split '^CN=(.+?-,\),(?:OU|CN)=.+','$1'

ForEach($OBJECT in $ADARRAY){ 

    $NAME = $OBJECT.Name 
    $USER = $OBJECT.SamAccountName
    $EMAIL = $OBJECT.Mail

<# this was my second try #>
    ForEach($OBJECT in $ADARRAY.Memberof){
          $CN = New-Object PSCustomObject -Property @{'CN' = $CN}

        $CN.OBJECT = $CN.Split(',')[0]

    $INSERT = "INSERT INTO $TABLE VALUES ('$USER','$CN','$EMAIL', '$NAME');"
        $SQL.CommandText = $INSERT 

        $SQL.ExecuteNonQuery()

    } 
  }
}

$SQLCON.Close()

1 个答案:

答案 0 :(得分:1)

是的,您可以使用RegEx执行此操作。 只需搜索您想要的数据,拆分和/或提取您想要的数据。

  

Windows PowerShell:使用正则表达式提取字符串

DOMParser
  

&#39; techtalk.gfi.com/windows-powershell-extracting-strings-using-regular-expressions'

     

PowerShell - 使用RegEx从字符串中获取子字符串

     

PowerShell方式

const stringContainingXMLSource = `<your xml string>`;
var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingXMLSource, "application/xml");
console.log(Array.from(doc.querySelectorAll('Envelope > Body > GetClientsResponse > GetClientsResult > Client')).map(n => n.textContent));
  

使用RegEx

$input_path = ‘c:\ps\emails.txt’ $output_file =
‘c:\ps\extracted_addresses.txt’ $regex =
‘\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b’ select-string
-Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
  

&#39; lazywinadmin.com/2013/10/powershell-get-substring-out-of-string.html'

请在此处查看完整的PoSH RegEx:

  

&#39; community.idera.com/powershell/powertips/b/ebookv2'第13章文字   和正则表达式   &#39; community.idera.com/powershell/powertips/b/ebookv2/posts/chapter-13-text-and-regular-expressions'