我想列印出核心數。
$N_cores = Get-WmiObject –class Win32_processor | ft NumberOfCores
Write-Host $N_cores | Select-Object -Property NumberOfCores
這給了我以下資訊:
Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Mi
crosoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Micros
oft.PowerShell.Commands.Internal.Format.FormatEndData
如何顯示 NumberOfCores?
uj5u.com熱心網友回復:
你只需要提取核心的價值,試試這個
$N_cores = Get-WmiObject –class Win32_processor | Select-Object -ExpandProperty NumberOfCores
Write-Host "Number of cores is: $N_cores"
uj5u.com熱心網友回復:
您看到的令人困惑的輸出來自ft(別名Format-Table)。
要從 中修剪您想要的屬性數量,請Get-WmiObject改用Select-Object。
例如,要將NumberOfCores屬性存盤在 中$N_cores,然后僅顯示其原始值,您可以這樣做:
# This will create an object with a `NumberOfCores` property
$N_cores = Get-WmiObject –class Win32_processor |Select-Object NumberOfCores
# print just the value of the property
Write-Host $N_cores.NumberOfCores
uj5u.com熱心網友回復:
這里有幾個問題
- 您在其他地方使用內容之前呼叫 Format-Table,Format-Table 回傳格式物件的輸出
- 您正在將您的寫入輸出傳遞給 Select-Object,這通常不是您想要的方式......
我建議您遵循Filter Left, Format Right的最佳實踐
當您通過管道將物件傳遞給另一個函式時,該函式會嘗試將這些物件的屬性解釋為引數。如果您檢查 Format-Table 輸出,它不再具有 NumberOfCores 屬性。該屬性是 Win32_processor 物件型別的成員。
您無法從 Write-Host 管道輸出,因為它不會向管道回傳任何內容
最終你想要的代碼是
$N_cores = Get-WmiObject –class Win32_processor | Select-Object -Property NumberOfCores
Format-Table $N_cores |Write-Host
還應該提到的是,如果您打算使用此腳本執行除列印到控制臺之外的任何操作,則不應使用 Format-Table 或 Write-Host,而應使用 `Write-Output $N_cores 作為第二行。這不僅會將結果寫入控制臺,還會將 $N_cores 變數中的物件傳遞給管道 Write-Host vs Write-Output
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/420894.html
標籤:
