powershell - 将 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'
它不会显示表格。
为什么它不起作用,我应该修改什么才能使它起作用?
解决方案
假设 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:
我已更改函数名称以符合动词-名词命名约定。
推荐阅读
- ip - 使用 WAN IP 连接到连接到路由器的设备
- ios - 如何让 UILabel 显示多行和自动换行?
- r - 如何修复计算两个坐标之间距离的函数
- python-3.x - 是否可以在 tkinter 中模拟 Tk 接收?
- php - 如何从 Mac OS X 上的 mysql/PHP 中删除符号链接?
- r - 如何模拟具有指定 AUC 的 ROC 曲线
- javascript - Nativescript Vue(移动应用程序) - 如何将模式列表视图中的选定项目数据传递回主应用程序?
- r - getGroupsFormula.default(correlation) 中的错误:'form' 参数必须是公式
- angular - 角度应用程序的图像未显示在浏览器中
- angular - angular5: Uncaught SyntaxError: Unexpected token { in app.service.ts:1 用于单元测试