首页 > 解决方案 > Powershell:在 Active Directory 中检索 LogonDate

问题描述

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

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

这是我的代码:

    Import-Module ActiveDirectory
$datecutoff = (Get-Date).AddDays(-90)
Get-Content "C:\powershell\pc.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 中选择日期的方法。

有没有办法做到这一点?

提前致谢。

标签: powershellactive-directory

解决方案


你有几个问题。您需要请求它不是默认LastLogonDate返回的。Get-ADComputer您需要使用LastLogonDate$LastLog对象中选择属性的点表示法,以便您的比较有效。

Import-Module ActiveDirectory
$datecutoff = (Get-Date).AddDays(-90)
Get-Content "C:\powershell\pc.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'


推荐阅读