文章目录

最近公司的项目完成得七七八八了,所以要开始抓日常管理了,首先从清理账号开始。
要查AD里面长期没登陆的账号,然后看是不是已经禁用了,再去确认是不是可以删掉。
本来呢是有工具可以用,比如说AD INFO也不要钱,用起来也不错。不过总要装点东西觉得有点不爽。让别人去用的话还得附上软件,所以就想着用Powershell试试吧。
PowerShell写的少,只是依稀记得里面对数组的支持蛮差的,就没兴趣了,但是这个也有好处,Win10 Win7预装,只要写好一个脚本,到处就都可以用了,不过好像VBScript也是一样的。。。
不管了,网上看了一下,要抓AD里面的信息的话,基本上有两种法子,用[ADSI]接口,或者直接用Get-ADUser,两种方法我本来以为应该差不多的,用了之后才发现其实差别还蛮大的。
先说 ADSI 接口:
这是基于COM上的AD接口,可以用来访问和管理AD,同时支持LDAP和WinNT。
用[ADSI]的话,写起来就很简单了,直接就可以去拿自己要的Object,查了一下网上的资料,根据别人做的改了一下:

$objOU=[ADSI]"LDAP://OU=China,OU=Users,OU=Root2,DC=yourdomain,DC=com"

然后做一个directoryservices.directorysearcher

$searcher=new-object directoryservices.directorysearcher($objOU)

然后筛选一下只要user的信息,findall一下

$Searcher.SearchScope = "Subtree"
$users=$searcher.findall()

之后构建一下Excel表

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $True
$workbook = $excel.Workbooks.add()
$workbook.WorkSheets.item(1).Name = "UsersInfo"
$sheet = $workbook.WorkSheets.Item("UsersInfo")
$sheet.cells.item(1,1) = "Name"
$sheet.cells.item(1,2) = "Description"
$sheet.cells.item(1,3) = "Dep"
$sheet.cells.item(1,4) = "Tel"
$sheet.cells.item(1,5) = "Win200Name"
$sheet.cells.item(1,6) = "Last Logon time"
$sheet.cells.item(1,7) = "ProfilePath"
$intRow=2

完了只要向Excel里面填内容就是了

foreach ( $user in $users){
$Path=$user.Path
$account=[ADSI]$Path
$sheet.cells.item($intRow,1) = $account.Name.Value
$sheet.cells.item($intRow,2) = $account.description.Value
$sheet.cells.item($intRow,3) = $account.physicaldeliveryofficename.Value
$sheet.cells.item($intRow,4) = $account.telephonenumber.Value
$sheet.cells.item($intRow,5) = $account.sAMAccountName.Value
$sheet.cells.item($intRow,6) = $account.profilePath.Value
$sheet.cells.item($intRow,7) = $account.lastLogonTimeStamp.Value
$intRow++
}

多简单啊,程序也整齐。
然后就华丽丽的报错了,last login信息拿不到。

左思右想,想不出来,只能一步一步的去跑一下,然后发现了这个,当我去拿lastLogonTimeStamp的时候,是没有Value属性的,显示是这个:

 $user.lastlogon
System.__ComObject

然后去查了一下,就这几个时间有关的是ComObject, 其他Name啊什么的,都是String类型的…
哎,急着出活,就简单把LastLogonDate用Get-ADUser 抓了一下,Get-ADUser要有AD组件支持ADWS ,然后速度还慢,不过能用了,这样自动打开一个Excel,然后一行一行,慢慢的填充上去。
什么时候再研究一下ADSI接口,完善一下吧。

Github地址