В настоящее время у меня есть скрипт, который работает, за исключением двух функций поиска. Поиск активного пользователя, который ограничен двумя OU, и пользователь Disabled, который ограничен двумя отдельными OU. Все это содержится в цикле while, который выполняет поиск по всей AD. Мне трудно заставить работать эти два подзапроса. Они возвращают результат всем пользователям AD, несмотря ни на что. У меня есть несколько разных представлений в поиске Disabled.

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

    #Requires -Version 2.0
#Connection and Startup Strings
cls
Import-Module ActiveDirectory
if ( (Get-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue) -eq $null ){
Add-PSSnapin Quest.ActiveRoles.ADManagement
}


#-Set Window title
$host.UI.RawUI.WindowTitle = $MyInvocation.MyCommand.Name + " - " + (Get-Item $MyInvocation.MyCommand.Path).LastWriteTime.ToString("yyyy-MM-dd_HH:mm:ss")


#Requires -Version 2.0

$ADServer = 'childDomain.domain.com'
$Aous = 'OU=Users,OU=Production,DC=childdomain,DC=domain,DC=com','OU=Onboarding,OU=Production,DC=childdomain,DC=domain,DC=com'
$Dous = 'OU=Terminated,DC=childdomain,DC=domain,DC=com', 'OU=Disability Leave,OU=Production,DC=childdomain,DC=domain,DC=com'
$ADous = 'OU=Users,OU=Production,DC=childdomain,DC=domain,DC=com','OU=Onboarding,OU=Production,DC=childdomain,DC=domain,DC=com','OU=Terminated,DC=childdomain,DC=domain,DC=com', 'OU=Disability Leave,OU=Production,DC=childdomain,DC=domain,DC=com'
$Exportpath = "C:\domain\ExportADUsers\"
if(!(test-path $Exportpath)){ New-Item -ItemType Directory -Force -Path $Exportpath }
$Logfile = "C:\domain\UserSearch_errors.txt"

#-determine Service Desk agent; used in Signature as well as Push-Button
if($env:UserName -Match "x_\w.*"){ $SDAgent = $env:UserName.Substring(2) }
else{ $SDAgent = $env:UserName }


#--Prompt/menu strings
$noADuserErrorString = "`n---..--  No Account found in Active Directory  --..---"
$promptActiveSearchString = "  - Enter the employee username that you wish to search the Active OU's for"
$promptDisabledSearchString = "  - Enter the employee username that you wish to search the Disabled OU's for"
$emptyInput = "No entry specified, please retype request."
$cancelOnboardForm = "Exiting Onboarding form. No actions taken."

$script:TESTING = $False
function testing-message
{
Write-Host "script:TESTING is currently : " -NoNewline
if($script:TESTING){ Write-Host "TRUE" -ForegroundColor Red }
else { Write-Host "FALSE" -ForegroundColor Green }

}

Connect-QADService childdomain.domain.com


Write-Host "`n`n**********************`n**`n**  " -NoNewline -ForegroundColor Green
Write-Host "Welcome, $SDAgent ($env:UserName)"
Write-Host "**`n********`n" -ForegroundColor Green


$SelectString = "Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, @{l='DN'; e={Find-Container}}, homeDirectory"

function SelectStandard
{
#-trying to create function to standardize output for various search modes
Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, @{l='DN'; e={Find-Container}}, homeDirectory
}

function Show-Error
{
#- NOTE: add "-ErrorAction Stop" switch to force terminating error
Write-Host "  |====================="
Write-Host "  |"
Write-Host "  | " -NoNewline
Write-Host "Caught an exception:" -ForegroundColor Red
Write-Host "  | " -NoNewline
Write-Host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host "  | " -NoNewline
Write-Host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
Write-Host "  | " -NoNewline
Write-Host "Exception Error[0]: $($error[0])" -ForegroundColor Red
Write-Host "  |"
Write-Host "  |====================="

}

function Show-Prompt
{
$prompttime = Get-Date -format T
$prompttime = Get-Date -format hh:mm:ss

Write-Host " `n<" -NoNewline
Write-Host "$prompttime" -ForegroundColor Yellow -BackgroundColor Black -NoNewline
Write-Host ">" -NoNewline
Write-Host " Enter the username you would like to lookup: " -ForegroundColor Cyan -BackgroundColor Black -NoNewline

# Write-Host " `n[ $prompttime ] Enter the username you would like to lookup: " -ForegroundColor Cyan -NoNewline
}

##########################
#  main loop
while($true){
Show-Prompt
$username = Read-Host
$username = $username.Trim()
#-ignore blank
elseif (($username -Match "^\s+$") -or ($username -eq '')){
Write-Host $emptyInput
Continue
}

#-Search Active OU's
#WIP
elseif ($username -eq 'Active'){
$usra = Read-Host -prompt $promptActiveSearchString
$usra = $usra.Trim()
$activecorp = Get-QADUser $usra -Searchroot $aous | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, @{l='DN'; e={Find-Container} }

$activecorp
if (!$activecorp) { Write-Host $noADuserErrorString -ForegroundColor Red -BackgroundColor Black }

$username = $usra  #~why?
Continue
}

#-Search Terminated & Disability Leave OU's
#WIP

elseif ($username -eq 'Disabled'){
$usra = Read-Host -prompt $promptDisabledSearchString
$usra = $usra.Trim()

$validUsername = $False
try{
    Get-ADUser -Server $ADServer -Searchbase $Dous | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, @{l='DN'; e={Find-Container} }
    $validUsername = $True
}
catch{
    Write-Host "$usra $noADuserErrorString" -ForegroundColor Red -BackgroundColor Black
    $validUsername = $False
}

$username = $usra

<#
$usra = Read-Host -prompt $promptDisabledSearchString
$usra = $usra.Trim()
$discorp = Get-QADUser $usra -Searchroot $dous | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, @{l='DN'; e={Find-Container} }

if (!$discorp) { Write-Host $noADuserErrorString -ForegroundColor Red -BackgroundColor Black }


#$username = $usra  #~why?
Return $discorp
#Continue

foreach($AllADUsers in $ADous){Get-ADUser -server $ADServer `
        -SearchBase $AllADUsers `
    -Filter * -Properties * |

#>
}

#-if starts with a number, assume phone number mode
elseif ($username -Match "^\d.*"){
$phoneno = $username

# Connect-QADService childdomain.domain.com
$phonecorp = Get-QADUser -Enabled -telephonenumber "*$phoneno" | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, @{l='DN'; e={Find-Container} }

$phonecorp
if (!$phonecorp) { Write-Host $noADuserErrorString -ForegroundColor Red -BackgroundColor Black }

Continue
}
#-Get employee ID
elseif ($username -eq 'gid'){
$usra = Read-Host -prompt "  - Enter the employee username that you wish to get the Employee ID for"
$usra = $usra.Trim()

$validUsername = $False
try{
    Get-ADUser $usra -Properties EmployeeID | Select EmployeeID
    $validUsername = $True
}
catch{
    Write-Host "[$usra] is not a valid username. Username must match EXACTLY." -ForegroundColor Red -BackgroundColor Black
    $validUsername = $False
}
$username = $usra
}
#-Exit script gracefully
elseif ($username -eq 'Exit'){
Exit
}
#-perform basic search
else{
# Write-Host "`n  - basic search - "  #-for testing, to verify elseif as well as to prove Active/Disabled options are not working as intended
# Connect-QADService childdomain.domain.com
$corp = Get-QADUser $username | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, @{l='DN'; e={Find-Container}}, homeDirectory, @{n="ManagerName";e={(Get-ADUser -Identity $_.Manager -properties DisplayName).DisplayName}}

$corp
if (!$corp) { Write-Host $noADuserErrorString -ForegroundColor Red -BackgroundColor Black }
}
}
0
Matt 14 Мар 2018 в 13:17

1 ответ

Лучший ответ

Я не совсем понимаю, что вы пытаетесь сделать, но я вижу пару проблем в вашем коде.

Я не могу разговаривать с командлетами Quest, но могу поговорить с Get-ADUser.

Параметр SearchBase принимает вызов, но вы объявили $Dous как массив:

$Dous = 'OU=Terminated,DC=childdomain,DC=domain,DC=com', 'OU=Disability Leave,OU=Production,DC=childdomain,DC=domain,DC=com'

Затем передал его Get-ADUser:

Get-ADUser -Server $ADServer -Searchbase $Dous

Это не сработает. Вам нужно запустить Get-ADUser один раз для каждого OU.

Вам также необходимо установить параметр Filter, даже если вы просто установили его на *, чтобы получить каждого пользователя:

Get-ADUser -Filter * -Server $ADServer -Searchbase 'OU=Terminated,DC=childdomain,DC=domain,DC=com'

Но вы можете настроить Filter по-другому, если знаете имя учетной записи, которую ищете.

0
Gabriel Luci 14 Мар 2018 в 15:50