【问题标题】:PowerShell date parsing not working in AD queryPowerShell 日期解析在 AD 查询中不起作用
【发布时间】:2022-01-20 12:49:10
【问题描述】:

我正在尝试获取帐户过期超过 6 个月的 AD 用户列表。

这是我的代码:

Get-ADUser -Filter {Enabled -eq $False} -Properties employeeID,sn,givenName,LastLogonDate | Where-Object {[STRING]$_.LastLogonDate -ne "" -and (Get-Date) -gt ([datetime]::parseexact([STRING]$_.LastLogonDate, "dd/MM/yyyy HH:mm:ss", $null)).AddMonths(6)} | select employeeID,sn,givenName,sAMAccountName,LastLogonDate | Sort-Object -Property sn | Export-Csv -Path $filename

我得到错误: The DateTime represented by the string is not supported in the System.Globalization.GregorianCalendar

我还在 parseexact 中尝试过 (Get-Culture)。也不行。

当简单地执行类似[datetime]::parseexact("21/05/2015 16:14:37", "dd/MM/yyyy HH:mm:ss", $null) 它按预期工作。

我做错了什么?

谢谢

【问题讨论】:

  • 属性LastLogonDate 已经是[DateTime] 对象。这是一个 PowerShell 便利属性,其中 LDAP 属性 lastLogonTimeStamp 已为您转换为本地时间。您可以直接在属性上使用.AddMonths(6)
  • 这很有道理...非常感谢。刚刚发现我需要使用 $_。访问 LastLogonDate...祝您有美好的一天!

标签: powershell date datetime parsing active-directory


【解决方案1】:

您可以通过将LastLogonDate 添加到Filter 并删除Where-Object 来改进您的查询:

$limit = [datetime]::Now.AddMonths(-6).Date
$params = @{
    Filter = "LastLogonDate -lt '$limit' -and Enabled -eq '$false'"
    Properties = 'LastLogonDate', 'sn', 'EmployeeID'
}

Get-ADUser @params | Sort-Object sn | Export-Csv .... 

【讨论】:

  • @Theo 可能是个好主意,呵呵,[datetime]::Today.AddMonths(...) 也应该是一样的。谢谢
猜你喜欢
  • 2016-04-30
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多