Powershell:正在Active Directory中检索登录日期



我有一个计算机列表,我正在检查它们是否已连接,是否未与AD和"吐出";一个超过3个月没有连接的。

如果已连接,则检查是否安装了服务。

这是我的代码:

Import-Module ActiveDirectory
$datecutoff = (Get-Date).AddDays(-90)
Get-Content "C:powershellpc.txt" | 
foreach {
if (-not (Test-Connection -comp $_ -quiet)){
Write-host "$_ is down" -ForegroundColor Red
$LastLog = Get-ADComputer -Identity $_ | Select LastLogonDate
if($LastLog -lt $datecutoff){
Write-host "$_ is offline for more than 3 months" -ForegroundColor Yellow  
}
} Else {
$service = get-service -name masvc -ComputerName $_ -ErrorAction SilentlyContinue
if ($service ){ 
write-host "$_  Installed"
} else {
Write-host "$_  Not Installed"
}
}
}

当它发现一台断开连接的计算机时,它会给我以下错误:

Cannot compare "@{LastLogonDate=}" to "2020.04.16 18:49:19" because the objects are not the same type or the object "@{LastLogonDate=}" does not implement "IComparable".
At line:10 char:20
+                 if($LastLog -lt $datecutoff){
+                    ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : PSObjectCompareTo

我知道错误的发生是因为我的变量保存了错误的信息,但我找不到只在AD中选择日期的方法。

有办法这样做吗?

提前谢谢。

您有几个问题。您需要请求返回LastLogonDateGet-ADComputer不是默认值。您需要使用点符号法从$LastLog对象中选择属性LastLogonDate,以便进行比较。

Import-Module ActiveDirectory
$datecutoff = (Get-Date).AddDays(-90)
Get-Content "C:powershellpc.txt" |
foreach {
if (-not (Test-Connection -comp $_ -Quiet)) {
Write-Host "$_ is down" -ForegroundColor Red
$LastLog = Get-ADComputer -Identity $_ -Properties LastLogonDate
if ($LastLog.LastLogonDate -lt $datecutoff) {
Write-Host "$_ is offline for more than 3 months" -ForegroundColor Yellow
}
} Else {
$service = Get-Service -Name masvc -ComputerName $_ -ErrorAction SilentlyContinue
if ($service ) {
Write-Host "$_  Installed"
} else {
Write-Host "$_  Not Installed"
}
}
}

欢迎来到stackoverflow,请阅读https://stackoverflow.com/help/someone-answers

旁注。您可以筛选像Get-ADComputer -Filter 'LastLogonDate -lt $datecutoff'这样的老化计算机

最新更新