我目前正在编写一个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
答案 0 :(得分:1)
在功能FindUsers
中,只需尝试替换:
return $n
通过
return ,$n
,$n
强制return
命令返回列表,无论$n
是单个值还是列表,没有返回命令就习惯将单值数组转换为单个值。