I'm currently writing a Powershell script that's used to select a user from Active Directory, then allow you to select a computer they've logged into (via an SQL query) and remote desktop into it. The user is prompted to enter a full or partial name, then a list of all matches are printed and they are prompted to select one. The list of all matches is from iterating through an array, which all matches have been assigned to. If the search from the name input produces an array with only one person, and then the user selects that one person I get the following error:
Get-ADUser : Variable: 'u' found in expression: $u is not defined.
At C:\Users\styanc\Desktop\test.ps1:67 char:12
+ Get-ADUser <<<< -f{DisplayName -eq $u} -Properties TelephoneNumber, OtherTelephone, Mobile | Select TelephoneNumber, OtherTelephone, Moblie #| Format
-List
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : Variable: 'u' found in expression: $u is not defined.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
The functions are as follows.
Function FindUsers{
param ($n)
#creates an array of users with names LIKE the script users input
$n = @(Get-ADUser -f {DisplayName -like $n} -Properties DisplayName)
return $n
}
Function PrintUsers{
param ($array)
$i = 1
#for each user in the array, print their name
foreach($object in $array){
Write-Host "$i. $($object.name)"
$i++
}
}
Function SelectUser{
#there's probably a better way to do newlines?
Write-Host ""
#user selects a user from the list by number, input needs validation
$userNum = Read-Host "Please select a user. (by number)"
$length = $usersArray.Length
Write-Host $length
Write-Host $usersArray.length
if($usersArray.Length -eq $null){
$user = ($usersArray.Name)
}
else{
$user = ($usersArray[$userNum-1].Name)
}
#$user = ($usersArray[$userNum-1].Name)
return $user
}
And are called like this:
$usersArray = FindUsers -n $name
PrintUsers -array $usersArray
$selectedUser = SelectUser