問題 ccnp-350-601-topic-1-question-456-v-bd4dc0f1・第2版

問題

Cisco ACI PowerShell moduleを使う管理スクリプトで、REST応答からtenant名をすべて表示する。次はAPICへ認証済みのCookieを送り、JSON応答を得る部分である。返されるtenantの件数は事前に分からない。空欄に入るコードはどれか。

Write-Host "Retrieving list of tenants on ACI"
$tenanturl = $baseurl + "/api/node/class/fvTenant.json?"
$webobj = new-object net.webclient
$webobj.Headers.add("Cookie",$cookies)
$result = $webobj.DownloadString($tenanturl)
$resultjson = $result | ConvertFrom-Json
$tenants = New-Object System.Collections.ArrayList
[空欄]
  1. A 
    foreach( $tenant in $resultjson.imdata )
    {
        $tenant = $tenant.fvTenant.attributes.name
        Write-Host $tenant
    }
    
  2. B 
    While true {Write-Host $tenant.attributes.name}
    
  3. C 
    While True {Write-Host $tenant.iterate}
    
  4. D 
    i = 0
    foreach( $tenant in $resultjson.imdata )
    {
    $tenant = $resultjson.imdata[i]
    i = I + 1
    }
    

正解:A

理由

ConvertFrom-Jsonで変換した応答のimdataをforeachで走査する。各要素のfvTenant.attributes.nameがtenant名である。foreachは反復のたびに次の要素を$tenantへ代入するため、ループ内で名前の文字列へ置き換えても次の要素を処理できる。

選択肢ごとの説明

A.
foreach( $tenant in $resultjson.imdata )
{
    $tenant = $tenant.fvTenant.attributes.name
    Write-Host $tenant
}

imdataの各要素をforeachで処理し、fvTenant.attributes.nameを取り出して一件ずつ表示する。取得件数を先に決める必要がない。

B.
While true {Write-Host $tenant.attributes.name}

whileの条件を丸括弧で囲んでいないため構文が成立しない。配列の各要素へ進む処理もない。

C.
While True {Write-Host $tenant.iterate}

whileの条件を丸括弧で囲んでいない。iterateというpropertyを表示しても、fvTenant.attributes.nameの列挙にはならない。

D.
i = 0
foreach( $tenant in $resultjson.imdata )
{
$tenant = $resultjson.imdata[i]
i = I + 1
}

iの代入と添字に変数を示す$がなく、コードが成立しない。foreach内にもtenant名を表示する処理がない。

参考資料

お問い合わせ

演習する →