Powershell和SQL:从SQL查询到数组的数据

Cal*_*yan 4 sql data-binding powershell active-directory

问题在于用于查找所选用户已登录的计算机的SQL查询.我执行查询,使用适配器将结果填充到表中,然后将表对象读入数组.我不完全理解Powershell中数组的语法和功能,所以我可能会错误地做这个部分.在将表读入数组的函数内部,数组的内容看起来很好(只是计算机名)但是当我将该数组传递出函数并将其分配给变量时,该数组具有以下数据:{ #,compName}.它似乎是找到的计算机数量,然后是名称,如果找到一台计算机,则阵列为{1,ComputerName}.但是,如果找到多台计算机,则为2台或更多台,则阵列为{2,ComputerNameComputerName}.

这是带有SQL查询的函数以及用户选择计算机的函数.

Function GetComputerList{
    param ($u)
    #use the display name of the user to get their login name
    $queryUser = Get-ADUser -f{DisplayName -eq $u} #-Properties sAMAccountname | Select sAMAccountname
    $queryName = "'"
    $queryName += $queryUser.SamAccountName
    $queryName += "'"
    $query = "SELECT SYS.Netbios_Name0 FROM v_R_System SYS WHERE User_Name0 = $queryName ORDER BY SYS.User_Name0, SYS.Netbios_Name0"

    $connection = new-object system.data.sqlclient.sqlconnection( "Data Source=SERVER;Initial Catalog=DATABASE;Integrated Security=SSPI;”) 

    $adapter = new-object system.data.sqlclient.sqldataadapter ($query, $connection)

    $table = new-object system.data.datatable

    $adapter.Fill($table)

    $i = 1
    foreach($object in $table){
        <#Write-Host "$i. $($object.Netbios_Name0)"
        $i++#>
        $compArray += $object.Netbios_Name0
    }
    foreach($object in $compArray){
        Write-Host "$i. $($object)"
    }

    return @($compArray)
}


Function SelectComputer{
    param ($a)
    $computerNum = Read-Host "Please select a computer. (by number)"
    $computer = ($a[$computerNum])
    return $computer
}
Run Code Online (Sandbox Code Playgroud)

它们被称为这样:

$computerArray = GetComputerList -u $selectedUser
$selectedComputer = SelectComputer -a $computerArray
Run Code Online (Sandbox Code Playgroud)

我完全迷失了,任何意见都表示赞赏.

Cha*_*ler 11

您可以简化您的GetComputerList函数,在我的测试中产生所需的结果:

Function GetComputerList{
    param ($u)
    #use the display name of the user to get their login name
    $queryUser = Get-ADUser -f{DisplayName -eq $u} #-Properties sAMAccountname | Select sAMAccountname

    $query = @"
SELECT SYS.Netbios_Name0 
FROM v_R_System SYS 
WHERE User_Name0 = '$($queryUser.SamAccountName)'
ORDER BY SYS.User_Name0, SYS.Netbios_Name0
"@
    $connection = new-object system.data.sqlclient.sqlconnection( "Data Source=SERVER;Initial Catalog=DATABASE;Integrated Security=SSPI;”) 
    $adapter = new-object system.data.sqlclient.sqldataadapter ($query, $connection)
    $table = new-object system.data.datatable
    $adapter.Fill($table) | out-null
    $compArray = @($table | select -ExpandProperty Netbios_Name0)

    return @($compArray)
}
Run Code Online (Sandbox Code Playgroud)