我目前正在编写一个 Powershell 脚本,用于从 Active Directory 中选择用户,然后允许您选择他们已登录的计算机(通过 SQL 查询)和远程桌面。提示用户输入全名或部分名称,然后打印所有匹配项的列表,并提示他们选择一个。所有匹配项的列表来自遍历一个数组,所有匹配项都已分配给该数组。如果从名称输入中搜索产生一个只有一个人的数组,然后用户选择那个人,我会收到以下错误:
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
}
并被称为:
$usersArray = FindUsers -n $name
PrintUsers -array $usersArray
$selectedUser = SelectUser