
當我使用:
netstat -f | out-gridview
在 PowerShell 7.3 中,我得到了視窗,但它只有一列是字串。我不知道為什么它沒有為每個標題(如 Proto、Local Address 等)正確創建一列。我該如何解決這個問題?
uj5u.com熱心網友回復:
雖然評論者Toni提出了一個很好的使用點Get-NetTCPConnection | Out-GridView,但這個答案解決了所提出的問題。
為了能夠netstat在網格視圖中顯示輸出,我們必須將其文本輸出決議為物件。
幸運的是,所有欄位至少由兩個空格字符分隔,因此在用逗號替換這些字符后,我們可以簡單地使用ConvertFrom-CSV(感謝評論者Doug Maurer的想法)。
netstat -f |
# Skip unwanted lines at the beginning
Select-Object -skip 3 |
# Replace two or more white space characters by comma, except at start of line
ForEach-Object { $_ -replace '(?<!^)\s{2,}', ',' } |
# Convert into an object and add it to grid view
ConvertFrom-Csv | Out-GridView
有關與運算子一起使用的 RegEx 模式的詳細說明-replace,請參閱此RegEx101 演示頁面。
這是我原始答案的代碼,在功能上是等效的。我將把它作為一個例子來說明如何為作業選擇正確的工具可以大大簡化代碼。
$headers = @()
# Skip first 3 lines of output which we don't need
netstat -f | Select-Object -skip 3 | ForEach-Object {
# Split each line into columns
$columns = $_.Trim() -split '\s{2,}'
if( -not $headers ) {
# First line is the header row
$headers = $columns
}
else {
# Create an ordered hashtable
$objectProperties = [ordered] @{}
$i = 0
# Loop over the columns and use the header columns as property names
foreach( $key in $headers ) {
$objectProperties[ $key ] = $columns[ $i ]
}
# Convert the hashtable into an object that can be shown by Out-GridView
[PSCustomObject] $objectProperties
}
} | Out-GridView
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528436.html
標籤:电源外壳PowerShell cmdletwindows-11PowerShell-7.2
