powershell - 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 中选择日期的方法。
有没有办法做到这一点?
提前致谢。
解决方案
你有几个问题。您需要请求它不是默认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'
推荐阅读
- c++ - 为什么我不能创建一个包含 vec3 对象的联合?
- javascript - 如何解决无法在“节点”上执行“removeChild”?
- javascript - React js applicationd不要将数据添加到表中
- android - 在片段 getActivity() 与 mActivity 参考中显示 toast
- swift - 如何将标签栏添加到不在标签栏菜单中的其他页面
- git - 找不到远程存储库 - 但可以在浏览器中访问 Stash
- http - 通过 HTTP 的 VLC HTTP 流总是在 10 秒后停止
- javascript - 循环遍历可点击元素列表并将 html 写入相应的文件
- mysql - MySQL加载数据infile错误并附上
- visual-studio-code - funcList 自定义语言的 Visual Studio 代码正则表达式