0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PowerShellでCSVファイルの列数を数えるのは面倒くさい

Last updated at Posted at 2025-06-26

概要

PowerShellでCSVファイルの行数と列数を数えるだけのしょ~もない記事です。

以下、PowerShellのバージョンは PowerShell Core 7.5.1 です。

正解

$data = Import-Csv -Path $csvFileName  # CSVファイルをインポートします

# 行数を数えるのはシンプルです。

$rowCount = $data.Count # ヘッダも数える場合は1を足しましょう

# しかし列数を数えるのは大変です

$firstRow = $data | Select-Object -First 1 # とりあえず1行目をサンプルにします
$rowProps = $firstRow.PSObject.Properties # 1行分のプロパティを取ります
$rowMeasure = $rowProps | Measure-Object # 1行分のMeasureオブジェクトを取得します
$colCount = $rowMeasure.Count # そのうちCountプロパティが列数です

もちろん1行にまとめることができます。

$colCount = (($data | Select-Object -First 1).PSObject.Properties | Measure-Object).Count

また、1つひとつ数えてしまうという方法もあります。

$colCount = 0
foreach ($prop in $firstRow.PSObject.Properties) { $colCount++ }

背景

ネットで調べると下記のようにすれば列数を取れるとありますが、取れません。

$rowCount = $firstRow.PSObject.Properties.Count

PSObject.Properties の Count プロパティは Properties の個々の値の個数を返すので「1 1 1 1 (...)」となってしまいます。

なので Properties をいったん Measure-Object で数える必要があります。その結果は以下のようになります。

Count             : 29
Average           : 
Sum               :
Maximum           :
Minimum           :
StandardDeviation :
Property          :

このCountの値でやっと列数にたどり着きます。

ちなみにこの問題については本家MicrosoftのPowerShell実装チームの中でも議論になっていたようです。

Type [System.Management.Automation.PSMemberInfoIntegratingCollection`1] returned by .psobject.properties should have a .Count property #9155

PSObject.Properties は IEnumerable なので「一つひとつ数えて初めて全部の個数が分かる」という挙動は正しいようです。

まとめ

神は細部に宿る。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?