我需要將我域中所有 PC 的一些屬性匯出到 *.csv 表。必要的屬性之一是lastLogOn。問題是我有兩個域控制器,所以我需要從中選擇最新的lastLogOn。
我有一個解決方案,但是給我最后的計算機陣列確實需要很多時間(大約 1 分鐘)。這里是:
function getComputers([string]$dc) {
return Get-ADComputer -SearchBase ‘DC=mydomain,DC=com’ -Server $dc -Filter * `
-Properties name, samAccountName, DistinguishedName, lastLogOn, OperatingSystem | `
Sort samAccountName
}
function getComputersFromsBothDCs {
$compsDC1 = getComputers 'dc1'
$compsDC2 = getComputers 'dc2'
$comps = @()
for ($i = 0; $i -le $compsDC1.Length - 1; $i ) {
$comp1 = $compsDC1[$i]
$comp2 = $compsDC2[$i]
if ($comp1.lastLogOn -ge $comp2.lastLogOn) {
$comps = $comp1
} else {
$comps = $comp2
}
}
return $comps
}
$comps = getComputersFromsBothDCs
# Then export and some other stuff
函式getComputers每 1 DC 大約需要 1 秒,主要問題是選擇具有最新 lastLogon 的 PC。
有沒有更快的解決方案?
uj5u.com熱心網友回復:
試試這個,應該運行得更快。考慮一下,這個腳本只會找到lastLogon設定了屬性的計算機,它還會添加一個新的屬性 ( LastLogonDate),它是lastLogon FromFileTime的轉換。
$AllDCs = Get-ADDomainController -Filter * # Get all DCs in the Domain
$logons = [System.Collections.Generic.Dictionary[string,object]]::new()
$params = @{
LDAPFilter = '(LastLogon=*)' # Only find computers that have this Property
SearchBase = 'DC=mydomain,DC=com'
Properties = @(
'Name'
'samAccountName'
'DistinguishedName'
'lastLogon'
'OperatingSystem'
)
}
foreach($DC in $AllDCs)
{
$params.Server = $DC
# Find all computers using this target DC
$computerList = Get-ADComputer @params |
Select-Object @(
$params.Properties
@{
Name = 'LastLogonDate'
Expression = { [datetime]::FromFileTime($_.LastLogon) }
}
)
foreach($computer in $computerList)
{
if($logons[$computer.samAccountName].lastLogonDate -lt $computer.lastLogonDate)
{
# On first loop iteration should be always entering this
# condition:
# $null -lt $true # => True
# Assuming $computer.LastLogon is always a populated attribute
# which also explains my LDAPFilter = '(LastLogon=*)' from before
$logons[$computer.samAccountName] = $computer
}
}
}
$logons.Values # => Is your export
uj5u.com熱心網友回復:
我們可以按照以下方法獲取最新Lastlogon值的電腦
(1)- 從兩個 DC 獲取 ADComputers 串列并將結果保存在單個變數中
$DCs = ("DC01,"Dc02")
$ComputersList = @()
foreach ($DC in $DCs){
$ComputersList = Get-ADComputer -filter {Enabled -eq $true } -Properties lastlogon,OperatingSystem -Server $DC | where {$_.lastlogon -ne $null} | Sort-Object -Property SamAccountName
}
(2) - 按 SamAccountName 屬性對物件進行分組,并根據“lastlogon”屬性對分組結果進行排序,然后僅選擇最新值
$LatestList = $ComputersList | Group-Object -Property SamAccountName | % {$_.group | Sort-Object -Property lastlogon | select -Last 1}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/393831.html
