powershell 从OU获取计算机描述和上次登录的用户

eni9jsuy  于 2023-01-05  发布在  Shell
关注(0)|答案(2)|浏览(196)

如何获取特定OU中的计算机列表沿着.csv格式的描述和上次登录用户?

$userName = (Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $machine -ErrorAction:SilentlyContinue).UserName
$DisComp = Get-ADComputer -LDAPFilter "(Name=LN-*)" -SearchBase "OU=Computers - Disabled,DC=XXXXX,DC=com" | Select-Object Name

$results = foreach ($Machine in $DisComp) {

$Description = Get-AdComputer -Identity $Machine -Properties * | Select-Object Description

   $UserName 
   $Machine
   $Description
}
$results | Export-Csv -Path C:\XXXXX
rta7y2nd

rta7y2nd1#

定义OU和CSV文件路径

$ouPath = "OU=Workstations,DC=contoso,DC=com"
$csvPath = "C:\temp\computer-list.csv"

使用Get-ADComputer cmdlet获取OU中的计算机列表

$computers = Get-ADComputer -SearchBase $ouPath -Filter * -Properties lastlogondate,description

遍历每台计算机并获取描述和上次登录的用户

foreach ($computer in $computers) {
      $description = $computer.Description
      $lastLoggedOnUser = $computer.LastLogonUser
      $data = [PSCustomObject]@{
      "Computer Name" = $computer.Name
      "Description" = $description
      "Last Logged On User" = $lastLoggedOnUser
      }

将计算机数据添加到CSV文件

$data | Export-Csv -Path $csvPath -Append -NoTypeInformation
}
8i9zcol2

8i9zcol22#

AFAIK没有名为LastLogonUser的AD计算机属性或任何其他包含此信息的属性。若要获取上次登录的用户,您需要查询该计算机上的windows事件日志,并搜索ID为4672的事件
另外,如果除了返回的默认属性之外,您只想返回Description属性,则不要使用-Properties *
试试看:

$searchBase = "OU=Computers - Disabled,DC=XXXXX,DC=com"
$Computers  = Get-ADComputer -LDAPFilter "(Name=LN-*)" -SearchBase $searchBase -Properties Description

$results = foreach ($machine in $Computers) {
    # to get the username who last logged on, you need to query the Security log
    $events = Get-WinEvent -ComputerName $machine.Name -FilterHashtable @{Logname='Security';ID=4672} -MaxEvents 50 -ErrorAction SilentlyContinue
    $lastLogon = if ($events) { 
                    (($events | Where-Object {$_.Properties[1].Value -notmatch 'SYSTEM|NETWORK SERVICE|LOCAL SERVICE'})[0]).Properties[1].Value
                 }
                 else { 
                    "Unknown" 
                 }
    # output an object
    [PsCustomObject]@{
        ComputerName     = $machine.Name
        Description      = $machine.Description
        LastLoggedOnUser = $lastLogon
        CurrentUser      = (Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $machine.Name -ErrorAction SilentlyContinue).UserName
    }
}
$results | Export-Csv -Path 'C:\Somewhere\Computers.csv' -NoTypeInformation

P.S.您当然需要管理员权限来查询事件日志,因此(如果您不是域管理员)您可能还需要在Get-WinEvent行上使用-Credential参数。

相关问题