如何通过脚本将超过180天未登录的账户列出?列出的账户带OU

瑶 景 1,270 信誉分
2024-12-02T05:31:36.1933333+00:00

工程师您好,

  有一个脚本,将超过180天未登录的账户列出,但是只能列出账户和最后一次登陆时间,没法确认账户是哪个OU下的,请问有什么脚本能将将超过180天未登录的带OU的账户列出?

Get the current date

$currentDate = Get-Date

Calculate the threshold date (2 days ago)

$thresholdDate = $currentDate.AddDays(-2)

Find all user accounts in Active Directory that have not logged in since the threshold date

$inactiveUsers = Get-ADUser -Filter {

lastLogonTimestamp -lt $thresholdDate

} -Property lastLogonTimestamp, DisplayName, SamAccountName

Display the inactive users

Write-Output "用户超过2天未登录的账户:"

foreach ($user in $inactiveUsers) {

$lastLogonDate = [DateTime]::FromFileTime($user.lastLogonTimestamp)

Write-Output ("用户名: {0}, 最后登录日期: {1}" -f $user.SamAccountName, $lastLogonDate)

}

谢谢!

Windows Server
Windows Server
支持企业级管理、数据存储、应用程序和通信的 Microsoft 服务器操作系统系列。
300 个问题
0 个注释 无注释
{count} 票

1 个答案

排序依据: 非常有帮助
  1. Ian Xue 38,936 信誉分 Microsoft 供应商
    2024-12-02T06:09:53.8533333+00:00

    你好,

    账户所在的OU可以通过账户的DistinguishedName来获取,比如像下面这样

    # Get the current date
    $currentDate = Get-Date
    # Calculate the threshold date (2 days ago)
    $thresholdDate = $currentDate.AddDays(-2)
    # Find all user accounts in Active Directory that have not logged in since the threshold date
    $inactiveUsers = Get-ADUser -Filter {lastLogonTimestamp -lt $thresholdDate} -Property lastLogonTimestamp, DisplayName|Select-Object -Property SamAccountName,lastLogonTimestamp,@{n='OU';e={$_.DistinguishedName -replace '^.*?,(?=[A-Z]{2}=)'}}
    # Display the inactive users
    Write-Output "用户超过2天未登录的账户:"
    foreach ($user in $inactiveUsers) {
    $lastLogonDate = [DateTime]::FromFileTime($user.lastLogonTimestamp)
    Write-Output ("用户名: {0}, 最后登录日期: {1}, OU: {2}" -f $user.SamAccountName,$lastLogonDate,$user.OU)
    }
    

    祝好

    Ian Xue


    如果回答是有帮助的,请点击“接受答案”。


你的答案

问题作者可以将答案标记为“接受的答案”,这有助于用户了解已解决作者问题的答案。