获取AD专有名称

时间:2015-07-30 13:11:28

标签: csv powershell active-directory ldap distinguishedname

我正在尝试从CSV文件中获取输入,该文件包含组名称(规范名称)列表并从中获取可分辨名称,然后输出到另一个CSV文件。代码:

#get input file if passed    
Param($InputFile)

#Set global variable to null
$WasError = $null

#Prompt for file name if not already provided
If ($InputFile -eq $NULL) {
  $InputFile = Read-Host "Enter the name of the input CSV file (file must have header of 'Group')"
}

#Import Active Directory module
Import-Module -Name ActiveDirectory -ErrorAction SilentlyContinue

$DistinguishedNames = Import-Csv -Path $InputFile -Header Group | foreach-Object {
  $GN = $_.Group
  $DN = Get-ADGroup -Identity $GN | Select DistinguishedName
}
$FileName = "RESULT_Get-DistinguishedNames" + ".csv"

#Export list to CSV
$DNarray | Export-Csv -Path $FileName -NoTypeInformation

我尝试了多种解决方案,似乎没有一种方法可行。目前,它会抛出错误,因为

  

无法验证参数'Identity'的参数。参数为null。提供非null参数并再次尝试该命令。

我也尝试使用-Filter,在之前的尝试中我使用了这段代码:

Param($InputFile)

#Set global variable to null
$WasError = $null

#Prompt for file name if not already provided
If ($InputFile -eq $NULL) {
  $InputFile = Read-Host "Enter the name of the input CSV file(file must have header of 'GroupName')"
}

#Import Active Directory module
Import-Module -Name ActiveDirectory -ErrorAction SilentlyContinue

$DistinguishedNames = Import-Csv -Path $InputFile | foreach {
  $strFilter = "*"

  $Root = [ADSI]"GC://$($objDomain.Name)" 

  $objSearcher = New-Object System.DirectoryServices.DirectorySearcher($root) 
  $objSearcher.Filter = $strFilter 
  $objSearcher.PageSize = 1000
  $objsearcher.PropertiesToLoad.Add("distinguishedname") | Out-Null

  $objcolresults = $objsearcher.FindAll() 
  $objitem = $objcolresults.Properties 
  [string]$objDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
  [string]$DN = $objitem.distinguishedname
  [string]$GN = $objitem.groupname

  #Get group info and add mgr ID and Display Name
  $props = @{'Group Name'= $GN;'Domain' = $objDomain;'Distinguished Name' = $DN;}
  $DNS = New-Object psobject -Property $props 
}
$FileName = "RESULT_Get-DistinguishedNames" + ".csv"

#Export list to CSV
$DistinguishedNames | Sort Name | Export-Csv $FileName -NoTypeInformation

过滤器与我在这里使用的过滤器不一样,我找不到我正在使用的过滤器,我目前所拥有的是一个破碎的尝试。

无论如何,我遇到的主要问题是它会得到组名,但是在错误的域中搜索它(它不包括组织单位),导致它们都找不到。当我在PowerShell中搜索一个组时(使用Get-ADGroup ADMIN),他们会显示正确的DN和所有内容。任何提示或代码示例都表示赞赏。

1 个答案:

答案 0 :(得分:1)

你似乎错过了$variable = cmdlet|foreach {script-block}任务的重点。应返回要分配给$variable的对象(通过脚本块传递),以便最终进入$variable。这两个主循环都包含行$somevar=expectedOutput的结构,其中expectedOutputNew-Object psobjectGet-ADGroup调用。对$someVar的赋值会抑制输出,因此脚本块没有任何要返回的内容,$variable保持为空。要修复,不要将应该返回对象的调用添加到具有赋值的外部变量中。

$DistinguishedNames = Import-Csv -Path $InputFile -Header Group | foreach-Object {
    $GN = $_.Group
    Get-ADGroup -Identity $GN | Select DistinguishedName # drop '$DN=`
}
$DistinguishedNames | Export-CSV -Path $FileName -NoTypeInformation

与第二个脚本相同的问题。

相关问题