用可分辨的名称解析规范名称

时间:2014-03-23 00:04:11

标签: regex powershell

我有一个小脚本,我可以通过不同的属性搜索人并提取某些信息。我拉了Memberof属性,但是它的完整路径有点难看。我想要的只是规范名称。

我认为我可以将Memberof传送到Where-Object并从cn匹配到第一个,

select Name, EmailAddress, SAMAccountName, SN, Memberof |
  Where-Object -FilterScript:{$_.Memberof -match "cn*,"} | fl

这比我想的更复杂,还是我忽略了什么?任何帮助都会很好。

5 个答案:

答案 0 :(得分:3)

假设你真正追求的是通用名称(cn),我使用它:

$regex = '^CN=(.+?),(?:CN|OU)=.+'
$cn = $dn -replace $regex,'$1'

通用名称可以包含逗号。它们必须使用反斜杠进行转义,但它们可以在那里,因此使用逗号作为锚是不可靠的。如果它是叶子对象,则DN中的下一个AD引用必须是OU或容器,因此它将是OU =或CN =。我一直认为这是可靠的。

答案 1 :(得分:2)

-match运算符需要正则表达式。你的第二个操作数是cn*,,这意味着"一个' c,然后是零次或多次' n',然后是逗号"。要将cn中的文字与下一个逗号匹配,请改为使用cn.*?,

在正则表达式中,特殊字符*具有"前面的表达式"的零或更多倍,并且点匹配除换行符之外的任何字符。 ?使得匹配非贪婪,因此您获得最短匹配而不是最长匹配。

但是,-match运算符只是将输入字符串与表达式匹配。它不会从输入中提取或删除任何内容。使用-replace运算符:

select Name, EmailAddress, SAMAccountName, SN,
    @{n='MemberOf';e={$_.MemberOf -replace '^(cn.*?),.*','$1'}}

答案 2 :(得分:0)

长功能传入。 Source。不记得我是否改变了什么。

#Paste the function below into your session.  Here's an example pulling all my groups:
    Get-ADUser cookiemonster -Properties memberof | select -ExpandProperty memberof | Translate-ADName -InputType dn -OutputType canonical

#Looking at your question more closely, you aren't looking for the canonical name.  There are several output types to the function below, maybe NT4 is what you are looking for:
    Get-ADUser cookiemonster -Properties memberof | select -ExpandProperty memberof | Translate-ADName -InputType dn -OutputType NT4

#Add this function to your session before running the command above...
function Translate-ADName { 
<#
.SYNOPSIS
Translates Active Directory names between various formats.

.DESCRIPTION
Translates Active Directory names between various formats using the NameTranslate COM object. Before names can be translated, the NameTranslate object must first be initialized. The default initialization type is 'GC' (see the -InitType parameter). You can use the -Credential parameter to initialize the NameTranslate object using specific credentials.

.PARAMETER OutputType
The output name type, which must be one of the following:
  1779              RFC 1779; e.g., 'CN=Phineas Flynn,OU=Engineers,DC=fabrikam,DC=com'
  DN                short for 'distinguished name'; same as 1779
  canonical         canonical name; e.g., 'fabrikam.com/Engineers/Phineas Flynn'
  NT4               domain\username; e.g., 'fabrikam\pflynn'
  display           display name
  domainSimple      simple domain name format
  enterpriseSimple  simple enterprise name format
  GUID              GUID; e.g., '{95ee9fff-3436-11d1-b2b0-d15ae3ac8436}'
  UPN               user principal name; e.g., 'pflynn@fabrikam.com'
  canonicalEx       extended canonical name format
  SPN               service principal name format

.PARAMETER Name
The name to translate. This parameter does not support wildcards.

.PARAMETER InputType
The input name type. Possible values are the same as -OutputType, with the following additions:
  unknown          unknown name format; the system will estimate the format
  SIDorSIDhistory  SDDL string for the SID or one from the object's SID history
The default value for this parameter is 'unknown'.

.PARAMETER InitType
The type of initialization to be performed, which must be one of the following:
  domain  Bind to the domain specified by the -InitName parameter
  server  Bind to the server specified by the -InitName parameter
  GC      Locate and bind to a global catalog
The default value for this parameter is 'GC'. When -InitType is not 'GC', you must also specify the -InitName parameter.

.PARAMETER InitName
When -InitType is 'domain' or 'server', this parameter specifies which domain or server to bind to. This parameter is ignored if -InitType is 'GC'.

.PARAMETER ChaseReferrals
This parameter specifies whether to chase referrals. (When a server determines that other servers hold relevant data, in part or as a whole, it may refer the client to another server to obtain the result. Referral chasing is the action taken by a client to contact the referred-to server to continue the directory search.)

.PARAMETER Credential
Uses the specified credentials when initializing the NameTranslate object.

.FUNCTIONALITY
Active Directory

.EXAMPLE
PS C:\> Translate-ADName -OutputType dn -Name fabrikam\pflynn
This command outputs the specified domain\username as a distinguished name.

PS C:\> Translate-ADName canonical 'CN=Phineas Flynn,OU=Engineers,DC=fabrikam,DC=com'
This command outputs the specified DN as a canonical name.

PS C:\> Translate-ADName dn fabrikam\pflynn -InitType server -InitName dc1
This command uses the server dc1 to translate the specified name.

PS C:\> Translate-ADName display fabrikam\pflynn -InitType domain -InitName fabrikam
This command uses the fabrikam domain to translate the specified name.

PS C:\> Translate-ADName dn 'fabrikam.com/Engineers/Phineas Flynn' -Credential (Get-Credential)
Prompts for credentials, then uses those credentials to translate the specified name.

PS C:\> Get-Content DNs.txt | Translate-ADName -OutputType display -InputType dn
Outputs the display names for each of the distinguished names in the file DNs.txt.

.NOTES
    http://windowsitpro.com/active-directory/translating-active-directory-object-names-between-formats
#>

[CmdletBinding()]
param(

  [parameter(Mandatory=$TRUE,Position=0)]
  [validateset("NT4","1779","SPN","canonical","GUID","DN","UPN","display","domainSimple","enterpriseSimple","canonicalEx")]
    [String] $OutputType,

  [parameter(Mandatory=$TRUE,Position=1,ValueFromPipeline=$TRUE)]
    [String[]] $Name,

  [validateset("NT4","1779","SPN","canonical","GUID","DN","UPN","display","domainSimple","enterpriseSimple","canonicalEx","SIDorSidHistory","unknown")] 
    [String] $InputType="unknown",

  [validateset("domain","server","GC")]
    [String] $InitType="GC",

    [String] $InitName="",

    [Switch] $ChaseReferrals,

    [System.Management.Automation.PSCredential] $Credential
)

    begin {

      # Hash table to simplify output type names and values
      $OutputNameTypes = @{
        "1779"             = 1;
        "DN"               = 1;
        "canonical"        = 2;
        "NT4"              = 3;
        "display"          = 4;
        "domainSimple"     = 5;
        "enterpriseSimple" = 6;
        "GUID"             = 7;
        "UPN"              = 9;
        "canonicalEx"      = 10;
        "SPN"              = 11;
      }

      # Copy output type hash table and add two additional types
      $InputNameTypes = $OutputNameTypes.Clone()
      $InputNameTypes.Add("unknown", 8)
      $InputNameTypes.Add("SIDorSidHistory", 12)

      # Same as with previous hash tables...
      $InitNameTypes = @{
        "domain" = 1;
        "server" = 2;
        "GC"     = 3;
      }

      # Accessor functions to simplify calls to NameTranslate
      function invoke-method([__ComObject] $object, [String] $method, $parameters) {
        $output = $object.GetType().InvokeMember($method, "InvokeMethod", $NULL, $object, $parameters)
        if ( $output ) { $output }
      }
      function get-property([__ComObject] $object, [String] $property) {
        $object.GetType().InvokeMember($property, "GetProperty", $NULL, $object, $NULL)
      }
      function set-property([__ComObject] $object, [String] $property, $parameters) {
        [Void] $object.GetType().InvokeMember($property, "SetProperty", $NULL, $object, $parameters)
      }

      # Create the NameTranslate COM object
      $NameTranslate = new-object -comobject NameTranslate

      # If -Credential, use InitEx to initialize it; otherwise, use Init
      if ( $Credential ) {
        $networkCredential = $Credential.GetNetworkCredential()
        try {
          invoke-method $NameTranslate "InitEx" (
            $InitNameTypes[$InitType],
            $InitName,
            $networkCredential.UserName,
            $networkCredential.Domain,
            $networkCredential.Password
          )
        }
        catch [System.Management.Automation.MethodInvocationException] {
          write-error $_
          exit
        }
        finally {
          remove-variable networkCredential
        }
      }
      else {
        try {
          invoke-method $NameTranslate "Init" (
            $InitNameTypes[$InitType],
            $InitName
          )
        }
        catch [System.Management.Automation.MethodInvocationException] {
          write-error $_
          exit
        }
      }

      # If -ChaseReferrals, set the object's ChaseReferral property to 0x60
      if ( $ChaseReferrals ) {
        set-property $NameTranslate "ChaseReferral" (0x60)
      }

      # The NameTranslate object's Set method specifies the name to translate and
      # its input format, and the Get method returns the name in the output format
      function translate-adname2([String] $name, [Int] $inputType, [Int] $outputType) {
        try {
          invoke-method $NameTranslate "Set" ($inputType, $name)
          invoke-method $NameTranslate "Get" ($outputType)
        }
        catch [System.Management.Automation.MethodInvocationException] {
          write-error "'$name' - $($_.Exception.InnerException.Message)"
        }
      }
    }

    process {
      Foreach($item in $name){
        translate-adname2 $name $InputNameTypes[$InputType] $OutputNameTypes[$OutputType]
      }
    }
 }
祝你好运!

答案 3 :(得分:0)

如果你的正则表达式支持负面的后置断言,你可以使用^CN=(.+?)(?:(?<!\\),|$)usage example here)。

答案 4 :(得分:0)

这是我对这项任务的尝试:

function ConvertFrom-DistinguishedName ($DistinguishedName) {

    $Domain = ($DistinguishedName -split ',DC=' | Where-Object { $_ -notmatch '^CN=' }) -join '.'
    $CNPath = ($DistinguishedName -split ',DC=' | Where-Object { $_ -match '^CN=' }) -split ',\w\w='
    [array]::Reverse($CNPath)
    ($Domain + '/' + ($CNPath -join '/')) -replace 'CN=' -replace '\\'
}

ConvertFrom-DistinguishedName "CN=Bradshaw\, Jeremy,OU=PowerShell,DC=stackoverflow,DC=com"

...当然输出如下:

stackoverflow.com/PowerShell/Bradshaw, Jeremy

相关问题