【问题标题】:Powershell: Data table to arrayPowershell:数据表到数组
【发布时间】:2012-06-14 01:38:02
【问题描述】:

我目前正在编写一个 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

【问题讨论】:

    标签: powershell active-directory


    【解决方案1】:

    在函数FindUsers中,尝试替换:

    return $n
    

    return ,$n
    

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

    【讨论】:

    • 多么奇怪的修复,添加逗号到底有什么作用?
    • 首先这不是一个错误,而是一个特性;o)我在答案中添加了解释
    • 啊,好的,谢谢!现在有道理了。我不完全确定 Powershell 的所有工作原理,我用 C 和 Java 编程。这是我第一次编写脚本。
    • 您对待问题的方式不公平。你最好把它分成两个问题。第一个没有斜体并标记为已回答我的答案,并将第二个问题报告给添加 SQL 或数据绑定标志的新问题。您将有更好的机会解决两者的问题。
    • 好主意,我现在就这样做。再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    相关资源
    最近更新 更多