数据集中的表计数错误

时间:2015-12-09 08:42:20

标签: powershell dataset

我提供3个服务器来循环,但$mdtable.table.count只有1.我必须在这里错过一个简单的事情。有谁可以帮我解决这个问题?

Get-Content 'C:\test\computers.txt' | ? { $_.Trim() -ne "" } | ForEach-Object {
  $value = Invoke-Command -Computer $_ -ScriptBlock {
    Param($computer)
    # Connect to SQL and query data, extract data to SQL Adapter
    $SqlQuery = "xp_fixeddrives"
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Data Source=$computer;Initial Catalog='Secaudit';Integrated Security = True";
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($SqlQuery, $Sqlconnection)
    $mdtable = New-Object System.Data.Dataset
    $nRecs = $SqlAdapter.Fill($mdtable) | Out-Null
    $nRecs | Out-Null
    $res = $mdtable.Tables.Count
    $res
  } -ArgumentList $_ -Credential $cred
}
$value

1 个答案:

答案 0 :(得分:2)

你缺少的是那个

... | ForEach-object {
  $value = Invoke-Command -Computer $_ -ScriptBlock {
    ...
  } -ArgumentList $_ -Credential $cred 
}
当您实际想要累积值时,

会在每次迭代时替换 $value的值。

你可以这样做:

... | ForEach-object {
  $value += Invoke-Command -Computer $_ -ScriptBlock {
    ...
  } -ArgumentList $_ -Credential $cred 
}

或者像这样:

$value = ... | ForEach-object {
  Invoke-Command -Computer $_ -ScriptBlock {
    ...
  } -ArgumentList $_ -Credential $cred 
} | Measure-Object -Sum | Select-Object -Expand Sum