Mic*_*ael 5 powershell active-directory export-to-csv
基本上,我正在尝试做的是从Active Directory检索所有用户并使用PowerShell脚本将它们保存在.csv文件中.另外,我只想要列出属性"name"和"samaccountname".所以这是代码:
$strFilter = "somefilter"
$objCollection = @()
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
$colProplist = "name", "samaccountname"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults) {
$objItem = $objResult.Properties
$object = New-Object PSObject
$object | Add-Member -MemberType NoteProperty -Name Name -Value $objItem.name
$object | Add-Member -MemberType NoteProperty -Name SAMAccountname -Value $objItem.samaccountname
$objCollection+=$object
}
$objCollection # this gives me the output as wished
$objCollection | Export-CSV -NoTypeInformation -Path C:\temp\exportfile.csv # this doesn't work
Run Code Online (Sandbox Code Playgroud)
控制台输出如下所示:
Name SAMAccountname
---- --------------
{IUSR_PFTT-DC1} {IUSR_PFTT-DC1}
{IUSR_PFVM-DC1} {IUSR_PFVM-DC1}
{IUSR_PFXX-DC1} {IUSR_PFXX-DC1}
Run Code Online (Sandbox Code Playgroud)
但导出的.csv看起来像这样:
"Name","SAMAccountname"
"System.DirectoryServices.ResultPropertyValueCollection","System.DirectoryServices.ResultPropertyValueCollection"
"System.DirectoryServices.ResultPropertyValueCollection","System.DirectoryServices.ResultPropertyValueCollection"
"System.DirectoryServices.ResultPropertyValueCollection","System.DirectoryServices.ResultPropertyValueCollection"
"System.DirectoryServices.ResultPropertyValueCollection","System.DirectoryServices.ResultPropertyValueCollection"
Run Code Online (Sandbox Code Playgroud)
对此有何想法/解决方案?
如果你想坚持这种DirectorySearcher方法,改变这个:
foreach ($objResult in $colResults)
{$objItem = $objResult.Properties
$object = New-Object PSObject
$object | Add-Member –MemberType NoteProperty -Name Name -Value $objItem.name
$object | Add-Member –MemberType NoteProperty -Name SAMAccountname -Value $objItem.samaccountname
$objCollection+=$object
}
Run Code Online (Sandbox Code Playgroud)
进入这个:
$objCollection = $colResults | select -Expand Properties |
select @{n='Name';e={$_.name}}, @{n='SAMAccountName';e={$_.samaccountname}}
Run Code Online (Sandbox Code Playgroud)
您可以使用 Active Directory 模块获取域中的所有用户:
import-module activedirectory
get-ADuser -filter * | select name,SamAccountName | ConvertTo-CSV | ac "C:\yourCSVFile.csv"
Run Code Online (Sandbox Code Playgroud)
这将为您提供所有用户的类似输出。
"name","SamAccountName"
"MATTHE_G","matthe_g"
"PUTINE_I","putine_i"
"COBB_C","cobb_c"
"BULL_T","bull_t"
"BAYOL_B","bayol_b"
"CAPPON_P","CAPPON_P"
....
Run Code Online (Sandbox Code Playgroud)
注意:您需要打开活动目录窗口功能才能使用该activedirectory模块。这可以在 Windows 功能的“远程服务器管理工具”选项卡下找到。
| 归档时间: |
|
| 查看次数: |
3448 次 |
| 最近记录: |