I have script where I ask for the user ID and I use $userName in all my commands.
Now I would like to also have the option to enter the PC name and turn back to the user ID, (if the user ID cannot be found it displays a custom error message). The problem is that $userName is unique and should contain the user ID and not the PC name. Side-note: PC names are imported with a CSV file. Also all pc names are starting with BN..
Do {
# Check if a username is entered on the command prompt
Do {
Write-Host "Enter the user ID: " -ForegroundColor Cyan -NoNewline
$userName = Read-Host
} Until ($userName)
# Check if the user exists in Active Directory
$user = $(
try {
Get-ADUser -Server domainlocal -Filter "samaccountname -eq '$userName'"
}
catch {
$null
}
)
# Output the result for the check in Active Directory
If (!$user) {
Write-host "The user does not exist, please try again." -ForegroundColor Red
}
Else {
Write-host "User found in Active Directory, loading options..." -ForegroundColor Yellow -NoNewline
''
}} Until ($user)
To get the user ID with the PC name it should be like this:
write-host "enter PC Name"
$PCnaming = Read-Host
$userName = $Computernames.Where({$_. "PC name" -like $PCnaming })."User ID"
$userName
CodePudding user response:
You can ask the user to prefix PC names with something that'll allow you to distinguish it from a user ID:
Do {
Write-Host "Enter the user ID (or enter a computer name prefixed with 'PC:'): " -ForegroundColor Cyan -NoNewline
$userName = Read-Host
if($userName -like 'PC:*'){
$PCnaming = $userName -replace '^PC:'
$userName = $Computernames.Where({$_. "PC name" -like $PCnaming })."User ID"
}
} Until ($userName)
If the user enters someusername
it'll be stored in $userName
, but if the user enter pc:computername
, the loop will attempt to extract the user ID associated with computername