Экспорт местоположения объекта из CSV

Мне нужно экспортировать расположение объектов серверов из списка. Я пробовал использовать следующий сценарий, но он проверяет только упомянутую OU, как я могу выполнить поиск по всему домену и экспортировать каноническое имя объекта в CSV.

Get-ADObject -Filter 'Name -like "*"' -Searchbase 'OU=ManagedGroups,DC=Fabrikam,DC=com' | Export-CSV ExportOU.csv
0
задан 20 July 2017 в 21:05
1 ответ

Get-ADObject предоставит вам гораздо больше информации, чем вы обычно хотите; однако это именно то, о чем вы просите.

Get-AdObject -Filter * | Export-CSV "ExportOU.csv" -NoTypeInformation

Я был бы рад помочь вам получить резонный запрос, если вы хотите описать, что вы пытаетесь сделать.


Чтобы найти объекты AD Computer, используйте:

Get-ADComputer -Filter * | Export-CSV "ExportOU.csv" -NoTypeInformation

] Для очистки старых учетных записей компьютеров я рекомендую следующее. Я написал это некоторое время назад для поиска любых компьютерных объектов, которые не были «зарегистрированы в системе» или не подключены к домену в течение определенного периода времени. НЕОБХОДИМО, чтобы «неактивное» подразделение находилось в корне домена (или только внутри уровня, на который вы указываете функцию).

Import-Module ActiveDirectory

function Disable-AdInactiveUsers {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string]$OuPath,

        [int]$MonthsInactive = 13
        )
    Write-Verbose "Looking for computer accounts older than $MonthsInactive months"
    Write-Verbose "Processing: $OuPath"

    if ($MonthsInactive -gt 0) 
    {
        $MonthsInactive = $MonthsInactive * -1
    }

    # Get users inside a specific OU with the needed properties
    $users = Get-ADComputer -Filter * -Properties LastLogonDate,Description,MemberOf,Info,Created -SearchScope Subtree -SearchBase $OuPath

    # Create an array and filter the users by last login,                                                 only enabled users,    and not created recently 
    $inactive = @()
    $inactive += $users | Where-Object {$_.LastLogonDate -lt (Get-Date).AddMonths($MonthsInactive) -and ($_.Enabled -eq "True") -and ($_.Created -lt (Get-Date).AddMonths($MonthsInactive))} 

    # List users here that should be ingored, make sure to have at least two entries. They can both be "".
    $whitelist = "DC1",""

    $processedUsers = @()
    $skippedServers = @()

    if ($inactive.Count -gt 0){
        Write-Verbose "- Found inactive computer accounts:"

        # This ForEach loop adds their group memberships to the notes field, then removes group memberships
        $inactive | ForEach-Object {
            # If computer is whitelisted, skip this loop
            if ($whitelist -contains $_.samAccountName) {Write-Verbose "- Skipping whitelisted user: $($_.samAccountName)"; return}

            # If computer is in a server OU, skip
            if ($_.DistinguishedName -like "*Server*") {$skippedServers += $_ ;Write-Verbose "- Skipping Server: $($_.Name)"; return}


            Write-Verbose "- - Computer: $($_.UserPrincipalName) `tLastLogon: $($_.LastLogonDate)"

            # Add notes for original location, group memberships, and LastLogonDate
            $notes = "Orig Path: `r`n$($_.DistinguishedName) `r`n`r`nMemberships: `r`n$($_.MemberOf -join "`r`n") `r`n`r`nLastLogon: $($_.LastLogonDate)`r`n$($_.Info)"
            Set-ADUser $_ -Description $("Disabled $(Get-Date -Format yyyy-MM-dd) (Inactive) - " + $_.Description) -Replace @{info=$notes}

            # Add current user to the output
            $processedUsers += $_
        }

        Write-Verbose "- Disabling inactive accounts..."
        $processedUsers | Disable-ADAccount

        Write-Verbose "- Moving inactive objects..."
        $processedUsers | Move-ADObject -TargetPath "OU=Inactive,$OuPath"

        Write-Host "Done. These Servers were skipped:"
        Write-Host $($skippedServers.Name)

        $processedUsers
    }
    else {
        Write-Verbose "No inactive accounts found."
    }

    Write-Verbose ""
}

# Create an empty container for the users that get disabled
$DisabledUsers = @()

$DisabledUsers += Disable-AdInactiveUsers -OuPath "DC=Example,DC=com"

# If users were disabled, build and send an email with user information
if($DisabledUsers.Count -gt 0) {
    $emailBody = "<head>
<style>
table{
  border-collapse: collapse;
  border: 1px solid black;
}
th,td {
  border-color:black;
  border-width:1px;
  border-style:solid;
  padding: 5px;
}
</style>
</head>
<body>
 <p>These users have been disabled for inactivity:</p> 
 <table>
   <tr>
     <td>Computer</td>
     <td>LastLogon</td>
     <td>DN</td>
   </tr>"

    $DisabledUsers | ForEach-Object {$emailBody = $emailBody + "`r`n  <tr>`r`n    <td>$($_.Name)</td>`r`n    <td>$($_.LastLogonDate)</td>`r`n    <td>$($_.DistinguishedName)</td>`r`n  </tr>" }
    $emailBody = $emailBody + "`r`n </table>`r`n <p>Sent via script on $($env:COMPUTERNAME)</p>`r`n</body>"

    Send-MailMessage -SmtpServer "mail.example.com" -To "user@example.com" -From "script@example.com" -Subject "[Script] Computers ($($DisabledUsers.Count)) disabled due to inactivity" -Body $emailBody -BodyAsHtml
}
0
ответ дан 5 December 2019 в 07:44

Теги

Похожие вопросы