2012-06-11 42 views
1

我目前正在编写一个Powershell脚本,用于从Active Directory中选择一个用户,然后允许您选择他们已经登录到的计算机(通过SQL查询)和远程桌面。 提示用户输入完整或部分名称,然后打印所有匹配的列表,并提示他们选择一个。所有匹配的列表来自迭代所有匹配已分配给的数组。如果从名称上输入的搜索产生的阵列,只有一个人,然后用户选择一个人,我得到以下错误:PowerShell:数据表到阵列

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 

回答

1

在功能FindUsers,只是尝试更换:

return $n 

通过

return ,$n 

,$n强制return命令返回列表无论$n是单个值还是列表,没有该返回命令习惯将单个值数组转换为单个值。

+0

你说得对,那修正了第一个错误!谢谢。 – CallumStyan

+0

奇怪的修复方法,添加逗号究竟做了什么? – CallumStyan

+0

首先,这不是一个错误,而是一个功能; o)我将解释添加到答案 – JPBlanc