1
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?

More than 5 years have passed since last update.

Azure CLI + PowerShell 利用時にハマったこと

Posted at

はじめに

  • Azure CLI を PowerShell ベースで利用したときにハマったことをまとめます
  • 環境情報:
    • Azure CLI(v.2.0.57)
    • PowerShell(v.5.1.17134.407)

az コマンドで取得したオブジェクトのプロパティにアクセスできない

やりたいこと

  • リソースグループ一覧を取得し、名前だけ抜き出して一覧表示したい

間違ったコマンド

az group list | % {$_.name}
  • 結果:なにも出力されない

正しいコマンド

(az group list | Convertfrom-Json) | % {$_.name}

詳細

  • az 各種コマンド・サブコマンドの実行結果は基本的に JSON 文字列が戻り値 となる
  • PowerShell 側で プロパティにアクセスできるようにするには
    • | ConvertFrom-Json と続け PowerShell で扱えるオブジェクト形式に変換してやる必要がある
    • その際には 必ず全体を () でくくる 例:(az group list | ConvertFrom-Json)

where した結果 1件はデータがあるはずなのに .Count で件数が出力されない

やりたいこと

  • リソースグループ test-rgp の総リソース数を取得したい

間違ったコマンド

((az resource list -g test-rgp | ConvertFrom-Json) | where {$_.name -like "*"} ).Count
  • 結果:
    • リソースグループ内に 1つもリソースがない場合:0 が出力される
    • リソースグループ内に 1つリソースがある場合:なにも出力されない
    • リソースグループ内に 2つ以上リソースがある場合:正しい件数が出力される
    • 1件の時だけ なにも出力されない

正しいコマンド

@((az resource list -g test-rgp | ConvertFrom-Json) | where {$_.name -like "*"} ).Count

詳細

  • 正しいコマンド では @().Count とし where で絞り込んだ件数が 1件だけであっても 配列化し 件数を計上している
  • 上記コマンドから @ を外すと、絞り込み結果が 1件の場合 whereArray 型でなく PSCustomObject 型 で結果を返却する
  • PSCustomObject 型 には Count プロパティが存在しないため $null が返却される
    • これにより実際には1件ヒットしても コンソールに何も出力されないという事象が発生してしまう
1
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
1
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?