2017-05-30 62 views
2

我有2個PowerShell腳本,我在下面提到。我正在尋找一種合併這兩種腳本的方法。但是,我無法這麼做,因爲其中一個腳本正在使用CIM方法,另一個正在使用WMI方法。如何合併Get-CimInstance和Get-WMIObject函數的輸出

我試圖完成的是提供最後一次重啓時間和同一服務器的可用空間(用戶必須輸入服務器名稱,按Enter它顯示最後一次重啓時間和可用空間)。

腳本1(CIM法):

$Server = Read-Host -Prompt 'Input your server name' 
Get-CimInstance -ClassName win32_operatingsystem -ComputerName $Server | select csname, lastbootuptime 
Read-Host -Prompt "Press Enter to exit" 

腳本2(WMI方法):

$Server = Read-Host -Prompt 'Input your server name' 
Get-WMIObject Win32_Logicaldisk -ComputerName $Server | Select PSComputername,DeviceID, @{Name="Total_Size_GB";Expression={$_.Size/1GB -as [int]}}, @{Name="Free_Space_GB";Expression={[math]::Round($_.Freespace/1GB,2)}} 
Read-Host -Prompt "Press Enter to exit" 

回答

1

Store中的查詢的一個變量的結果。然後用你感興趣的值從每個函數創建一個psobjectYou can find out more about New-Object psobject here.

$Server = Read-Host -Prompt 'Input your server name' 

$myCimResp = Get-CimInstance -ClassName win32_operatingsystem -ComputerName $Server | select csname, lastbootuptime 
$myWmiResp = Get-WMIObject Win32_Logicaldisk -ComputerName $Server | Select PSComputername,DeviceID, @{Name="Total_Size_GB";Expression={$_.Size/1GB -as [int]}}, @{Name="Free_Space_GB";Expression={[math]::Round($_.Freespace/1GB,2)}} 

$theThingIActuallyWant = New-Object psobject -Property @{ 
    LastRebootTime = $myCimResp.lastbootuptime 
    FreeSpace  = $myWmiResp.Free_Space_GB 
} 

# A couple of ways to print; delete 1, keep 1 
Write-Output $theThingIActuallyWant  # Print to screen with implicit rules 
$theThingIActuallyWant | Format-Table # Print to screen with explicit table formatting 


Read-Host -Prompt "Press Enter to exit" 
+0

@Clijsters謝謝,編輯 – gms0ulman

+0

@ gms0ulman不知道如果我做錯什麼,但我得到這個錯誤: + $ theThingIActuallyWant =新物體psobject =房產@ { + ~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo:InvalidArgument: ,Microsoft.PowerShell.Commands.NewObjectCommand New-Object:無法找到接受參數'System.Collections.Hashtable'的位置參數 –

+0

....... 在C:\用戶\ XXXXXXX \ XXXXXX \ script.ps1:6字符:26 + $ theThingIActuallyWant =新物體psobject =屬性@ { + ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidArgument:(:) [New-Object],ParameterBindingException + FullyQualifiedErrorId:PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand –