table 计数在数据集中是错误的

Number of table count is wrong in 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

你错过的是

... | 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