Powershell和SQL:从SQL查询到阵列的数据
问题在于用于查找所选用户已登录的计算机的SQL查询。我执行查询,使用适配器将结果填充到表中,然后将表对象读取到数组中。我不完全理解Powershell中数组的语法和功能,因此这部分可能做得不对。在将表读入数组的函数中,数组的内容看起来很好(只是计算机名),但当我将该数组从函数中传递出去并将其分配给变量时,数组具有以下数据:{#,compName}。它似乎是找到的计算机数,然后是名称,如果找到一台计算机,则数组为{1,ComputerName}。但是,如果找到多台计算机(2台或更多),则数组为{2,ComputerName ComputerName} 下面是SQL查询函数和用户选择计算机的函数Powershell和SQL:从SQL查询到阵列的数据,sql,data-binding,powershell,active-directory,Sql,Data Binding,Powershell,Active Directory,问题在于用于查找所选用户已登录的计算机的SQL查询。我执行查询,使用适配器将结果填充到表中,然后将表对象读取到数组中。我不完全理解Powershell中数组的语法和功能,因此这部分可能做得不对。在将表读入数组的函数中,数组的内容看起来很好(只是计算机名),但当我将该数组从函数中传递出去并将其分配给变量时,数组具有以下数据:{#,compName}。它似乎是找到的计算机数,然后是名称,如果找到一台计算机,则数组为{1,ComputerName}。但是,如果找到多台计算机(2台或更多),则数组为{2
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
}
我完全迷路了,欢迎您的任何输入。您可以简化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)
}
首先,您需要指定
$compArray
实际上是一个数组。您从不声明它,因此PowerShell将其视为字符串,因此您可以将计算机名附加到彼此的后面。在GetComputerList
中的某个位置,将$compArray
声明为数组:
$compArray = @()
其次,数组中的第一个数字实际上是添加到管道中的.NET函数的返回值。最有可能的罪魁祸首是。将其返回值指定给变量:
$numRows = $adapter.Fill($table)
我建议将管道设置为空,正如我在下面所做的那样,调用Fill方法。一切似乎都按照我的预期工作,谢谢!我已经确保声明$compArray并将其作为实际数组返回,并使用out null来删除.Fill数据。选择just Property和选择ExpandProperty有什么区别?选择属性,即“..”选择Nebios_Name0“返回一个具有单个属性的对象,而-ExpandProperty返回一个字符串数组。啊,这很方便。谢谢
$numRows = $adapter.Fill($table)