Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

Count the number of columns in an array with PowerShell

I have the following code:

$array = Get-Process

Now, I want to count the number of columns. I have tried:

$array.Columns.Count
$array.Columns

And all without luck.

What should I do to get the correct number of columns? That should be 8.

<<Added on January, 27th, 2021: >>

I have modified the code to:

$Processes = @(Get-Process | Select-Object -Property Name, Description, ProductVersion, @{Name="Application";Expression={$_.Description + " " + $_.ProductVersion}},@{Name="Executable";Expression={(($_."Path").split(""))[-1]}} |Where {$_.Executable})
$Array     = @()
$Record    = [ordered] @{"Name"         = "";
                         "Application"  = ""}

ForEach ($ProcesName in $Processes)
{
 $Record."Name"        = $ProcesName.Name
 $Record."Application" = $ProcesName.Application
 $objRecord            = New-Object PSObject -Property $Record
 $Array               += $objRecord
}
Clear-Host
Write-Host "Number of columns: $($Array.Column.Count)"
Write-Host "Number rows:       $($Array.Count)"

The result is the same: both the column and row are the same. And that is not correct. I want to use the technique in a new script with much more columns.

<<End part that has been added on January, 27th, 2021 >>

Feedback is appreciated.

With kind regards, TheStingPilot

question from:https://stackoverflow.com/questions/65909807/count-the-number-of-columns-in-an-array-with-powershell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$array is an array of objects of type System.Diagnostics.Process. There aren't columns as such. The objects have properties which you may choose to display in columns using $array | ft or as a list $array | fl *. You can count the properties like this:

$array | Get-Member -MemberType Property | measure

If you'd like the answer to be 8 then you can do this:

$array | select Handles, NPM, PM, WS, CPU, Id, SI, Name | Get-Member -MemberType NoteProperty | measure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...