首页 > 解决方案 > 将 json 数组传递给 powershell 中的函数

问题描述

我有这个简短的脚本,它显示一个带有行号的表格,并询问用户想要使用哪个 Azure 订阅。它工作得很好。

$subscriptions = $(& az account list --query '[].{name:name}' --output json) | ConvertFrom-Json
$subscriptions | ForEach-Object {$index=0} {$_; $index++} | Format-Table -Property @{ Label="index";Expression={$index}; Width=5 },Name
$subChoice = Read-Host 'Choose subscription'

现在我想编写一个小函数来显示表格并从中选择一个项目,以便将其重用于其他选择。

function GetChoice {
    param (
        [Parameter(Mandatory = $true)][psobject] $list,
        [Parameter(Mandatory = $true)][string] $prompt
    )    
    $list | ForEach-Object {$index=0} {$_; $index++} | Format-Table -Property @{ Label="index";Expression={$index}; Width=5 },Name
    $choice = Read-Host $prompt
}

当我用它调用它时,$subChoice = GetChoice $subscriptions 'Choose subscription'它不会显示表格。

为什么它不起作用,我应该修改什么才能使它起作用?

标签: powershellpowershell-6.0

解决方案


假设 line 的结果$subscriptions = $(& az account list --query '[].{name:name}' --output json) | ConvertFrom-Json看起来像这样:

$subscriptions = [PsCustomObject] @{ 'Name' = 'Subscription one' },
                 [PsCustomObject] @{ 'Name' = 'Subscription two' },
                 [PsCustomObject] @{ 'Name' = 'Subscription three' }

然后将您的GetChoice功能更改为:

function Get-Choice {
    param (
        [Parameter(Mandatory = $true, Position = 0)][psobject[]] $list,
        [Parameter(Mandatory = $true, Position = 1)][string] $prompt
    ) 
    $index = 0
    $msg = $list | ForEach-Object { [PsCustomObject] @{'Index' = $index++; 'Name' = $_.Name }} | Format-Table -AutoSize | Out-String
    Write-Host $msg
    Read-Host $prompt
}

并这样称呼它

$choice = Get-Choice $subscriptions 'Choose subscription'
# show whatever the user typed in
$choice

结果:

Index Name              
----- ----              
    0 Subscription one  
    1 Subscription two  
    2 Subscription three



Choose subscription:

我已更改函数名称以符合动词-名词命名约定。


推荐阅读