2013-04-08 59 views
0

任何人都可以幫助PowerShell表嗎?Powershell Data.Table

腳本

Function CheckWMI { 
Param (
    [Parameter(Mandatory=$True)] 
    $Computers 

) 
     $CheckWMIResults = New-Object system.Data.DataTable 
     $Function = $CheckWMIResults.columns.add("ComputerName", [System.Type]::GetType("System.String")) 
     $Function = $CheckWMIResults.columns.add("Attempts", [System.Type]::GetType("System.Int32")) 
     $Function = $CheckWMIResults.columns.add("Result", [System.Type]::GetType("System.String")) 

    ForEach ($Computer in $Computers) { 
     $CheckWMIResults.Rows.Add($Computer,"0","Incomplete") 
    } 

} 

CheckWMI "192.168.1.8","192.168.1.7","192.168.1.6" 

正如你可以看到它需要每一個IP地址,併爲他們創造一個獨立的行的工作部分。

現在我該如何選擇其中一行並更新它,比如第二行的count列?

回答

3

沒有必要使用像DataTable這樣龐大的數據結構。所有你需要的是一個簡單的集合,如數組和通用的PSObject。下面重寫你的腳本上面,然後設置第一臺計算機的ResultComplete

Function CheckWMI { 
Param (
    [Parameter(Mandatory=$True)] 
    [string[]]$Computers 

) 
    $CheckWMIResults = @(); 

    ForEach ($Computer in $Computers) { 
     $TempResults = New-Object PSObject; 
     $TempResults | Add-Member -MemberType NoteProperty -Name "ComputerName" -Value $Computer; 
     $TempResults | Add-Member -MemberType NoteProperty -Name "Attempts" -Value 0; 
     $TempResults | Add-Member -MemberType NoteProperty -Name "Result" -Value "Incomplete"; 
     $CheckWMIResults += $TempResults; 
    } 
    $CheckWMIResults; 
} 

$Results = CheckWMI -Computers "192.168.1.8","192.168.1.7","192.168.1.6" 
$Results[0].Result = "Complete"; 
$Results; 

如果你確實需要的類型檢查(其中DataTable給你),定義自己的類型。

add-type @" 
public class WMIResults { 
    public string ComputerName; 
    public int Attempts; 
    public string Result; 
} 
"@ 

Function CheckWMI { 
Param (
    [Parameter(Mandatory=$True)] 
    [string[]]$Computers 

) 
    $CheckWMIResults = @(); 

    ForEach ($Computer in $Computers) { 
     $TempResults = New-Object WMIResults; 
     $TempResults.ComputerName = $Computer 
     $TempResults.Attempts = 0; 
     $TempResults.Result = "Incomplete"; 
     $CheckWMIResults += $TempResults; 
    } 
    $CheckWMIResults; 
} 

$Results = CheckWMI -Computers "192.168.1.8","192.168.1.7","192.168.1.6" 
$Results[0].Result = "Complete"; 
$Results; 

http://blogs.msdn.com/b/powershell/archive/2009/03/11/how-to-create-an-object-in-powershell.aspxGet-Help Add-Type,詳細瞭解此第二個方法(你可以使用一個結構,而不是爲了微不足道的情況下,一類,但classes are generally a better idea)。

+0

最後一個問題,我將如何使用計算機名稱來選擇行 – user1451070 2013-04-08 13:07:50

+0

與搜索集合中其他任何東西的方式相同。 '$ Results | Where-object {$ _。ComputerName -eq「criteria」}' – alroc 2013-04-08 13:12:39