1

私は現在、Active Directory からユーザーを選択するために使用される Powershell スクリプトを作成しており、(SQL クエリを介して) ログインしているコンピューターとリモート デスクトップを選択できるようにしています。ユーザーは名前の全部または一部を入力するように求められ、次にすべての一致のリストが出力され、いずれかを選択するように求められます。すべての一致のリストは、すべての一致が割り当てられている配列を反復処理したものです。名前入力からの検索で 1 人だけの配列が生成され、ユーザーがその 1 人を選択すると、次のエラーが発生します。

    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
4

1 に答える 1

1

functionFindUsersでは、次のように置き換えてみてください。

return $n

return ,$n

,$nreturn単一の値またはリストであるものは何でもリストを返すコマンドを強制$nします。その戻りコマンドがなければ、単一の値の配列を単一の値に変換する習慣があります。

于 2012-06-12T06:53:19.200 に答える