简体   繁体   English

Powershell 获取OU中所有服务器的lastlogonDate

[英]Powershell get lastlogonDate of all servers in OU

I am trying to get the last logonDate of all servers in OU with Powershell.我正在尝试使用 Powershell 获取 OU 中所有服务器的最后登录日期。

My script is able to collect the data but unable to write it to the csv report.我的脚本能够收集数据,但无法将其写入 csv 报告。 (The current version populates only the Server name and not the OS and LogonDate fields in the csv file) Need help with adjusting the output and if you can suggest improvements would also be great (当前版本仅填充 csv 文件中的服务器名称,而不填充 OS 和 LogonDate 字段)需要帮助调整 output,如果您能提出改进建议也很好

$allservers = get-adcomputer -filter * -searchbase "ou=important, ou=Member Servers, dc=contoso, dc=com" | select-object -expand name
$File = "$(Get-Date -Format ddMMyy_HHmmss)"

foreach ($server in $allservers) {
    Get-ADComputer -Identity $server -Properties * | format-table Name, LastLogonDate, OperatingSystem 
    $Props = [ordered]@{
        ServerName      = $server
        OperatingSystem = $server.OperatingSystem
        LastLogonDate   = $server.LastLogonDate
    }

    $Obj = New-Object psobject -Property $Props
    $obj | Export-Csv -Path .\$File.csv -NoTypeInformation -Encoding UTF8 -Append
}

I suspect you think that the first call in the foreach block is actually doing something with the $server variable.我怀疑您认为 foreach 块中的第一个调用实际上是在使用$server变量。 You are indeed loading all the properties from AD, but they are only printed to the console with Format-Table , not assigned to $server .您确实正在从 AD 加载所有属性,但它们仅使用Format-Table打印到控制台,而不是分配给$server

If you change second Get-ADComputer call to this, it will work.如果您将第二个Get-ADComputer调用更改为此,它将起作用。 Replace代替

Get-ADComputer -Identity $server -Properties * | format-table Name, LastLogonDate, OperatingSystem

with this:有了这个:

$server = Get-ADComputer -Identity $server -Properties * 
$server | format-table Name, LastLogonDate, OperatingSystem 

However, I would probably replace the entire thing with this, which will do the same:但是,我可能会用这个替换整个东西,它会做同样的事情:

$File = "$(Get-Date -Format ddMMyy_HHmmss)"
Get-ADComputer -Filter * -SearchBase "ou=important, ou=Member Servers, dc=contoso, dc=com" -Properties LastLogonDate,OperatingSystem | 
    Select-Object DistinguishedName, LastLogonDate, OperatingSystem | 
    Export-Csv -Path .\$File.csv -NoTypeInformation -Encoding UTF8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM