我有一段 PowerShell 代码,它从 Azure 读取项目列表,并将它们格式化为一个表格供用户选择:
if ($SubscriptionArray.Count -eq 1) {
$SelectedSub = 1
}
# Get SubscriptionID if one isn't provided
while ($SelectedSub -gt $SubscriptionArray.Count -or $SelectedSub -lt 1) {
Write-host "Please select a subscription from the list below"
$SubscriptionArray | Select-Object "#", Id, Name | Format-Table
try {
$SelectedSub = Read-Host "Please enter a selection from 1 to $($SubscriptionArray.count)"
}
catch {
Write-Warning -Message 'Invalid option, please try again.'
}
}
Run Code Online (Sandbox Code Playgroud)
在脚本的主要区域中执行时,会输出预期的结果:
我想多次使用这个逻辑,因此将它移到一个方法中:
function Get-IndexNumberFromArray(
[Parameter(Mandatory = $True)]
[array]$selectArray,
[Parameter(Mandatory = $True)]
[string]$message
) {
[int]$SelectedIndex = 0
# use the current subscription if there is only one subscription available
if ($selectArray.Count -eq 1) {
$SelectedIndex = 1
}
# Get SubscriptionID if one isn't provided
while ($SelectedIndex -gt $selectArray.Count -or $SelectedIndex -lt 1) {
Write-Host "$message"
$selectArray | Select-Object "#", Id, Name | Format-Table
try {
$SelectedIndex = Read-Host "Please enter a selection from 1 to $($selectArray.count)"
}
catch {
Write-Warning -Message 'Invalid option, please try again.'
}
}
return $SelectedIndex
}
Run Code Online (Sandbox Code Playgroud)
这个方法中的一切都很好,除了现在我的表不再输出到窗口。相反,用户只是得到一个从 1 到 x 选择一个数字的提示,而没有每个数字代表什么的上下文。
为什么该表在脚本的主要区域中工作,但在函数中不起作用?
Joe*_*oey 10
Format-Table实际上不打印表格,它输出的对象然后打印为表格。因此,如果您使用的是函数,则Format-Table输出将获取函数返回值的一部分。
您可以添加Out-Host到管道以强制Format-Table的结果在主机上结束,即控制台:
$selectArray | Select-Object "#", Id, Name | Format-Table | Out-Host
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1357 次 |
| 最近记录: |