如何让 Read-Host 在包含脚本分配给变量时显示提示问题?

问题描述 投票:0回答:1

我有一个脚本来调用 API 端点以从应用程序的层次结构中检索数据。

此层次结构有几个级别:Campus、Building、Floor 为了使其用户友好,我编写了一个脚本来编译一个表,该表将被查询的层次结构级别的名称获取到一个数组中,并向新数组列中的条目添加一个数字(基本上是数组索引,由人-可读)

脚本使用

Format-Table
命令将表格写入终端,然后使用
Read-Host
命令要求用户根据提供的提示提供输入。

如果我随后调用此脚本并将其分配给一个变量(以使输出操作更容易),则不会显示提示,因此您可以盲目地提供值而无法实现您想要的。

例如,如果我直接调用脚本,我会在终端窗口中得到这个:

.\My-script-here.ps1


Number name
------ ----
     1 Campus 1
     2 Campus 2

Enter number of campus:

如果我将它分配给一个变量,我得到这个:

$variable = .\My-script-here.ps1

Enter number of campus:

有没有办法在将脚本分配给变量时让编译后的表格出现? 目前脚本中的行是

$Table | Format-Table -Property Number,Name
我试过将它传送到
Write-Output
但这并没有什么不同

powershell user-interface variables scripting user-input
1个回答
0
投票

如果你想以正确的格式打印表格到仅显示,使用

Out-Host

一个简单的例子:

[PSCustomObject]@{
  Foo = 'Bar'
  Baz = 42
} | 
  Format-Table |
  Out-Host

Read-Host 'Enter number of campus'

以上将格式化的表格直接打印到主机显示器(仅),因此不会被

$variable = …
分配捕获并打印 unconditionally - 只有
Read-Host
响应将被捕获。


如果你想also输出表作为数据,以便它在

$variable
中被捕获,PowerShell(核心)7+启用一个方便的
Tee-Object
解决方案,与
CON
(在 Windows 上)/
/dev/tty
(在 Unix 上)作为
-FilePath
参数(代表控制台/终端设备):

# PowerShell 7+ only
[PSCustomObject]@{
  Foo = 'Bar'
  Baz = 42
} | Tee-Object -FilePath ($IsWindows ? '\\.\CON' : '/dev/tty')

Read-Host 'Enter number of campus'

现在表格同时打印

$variable
中捕获(连同
Read-Host
响应)。

但是,解决方案依赖于数据触发implicit

Format-Table
格式化。
例如,如果您的数据默认以 list 格式显示,您将需要一个 explicit
Format-Table
调用,这会使事情变得复杂:

  • 除非你真的想捕获Format-Table发出的

    格式化指令
    ,否则你必须避免它用于输出data -
    Format-*
    cmdlets 应该只用于产生display输出,而不是 data
    用于程序化处理 - 请参阅this answer了解背景信息。

  • 在这种情况下,即使在 PowerShell 7+ 中,您也需要使用下面针对 Windows PowerShell 描述的两步方法。

不幸的是,Windows PowerShell不支持

-FilePath CON
,因此您需要先将输出收集到一个变量中,然后在两个单独的操作中输出并将其传递给
Out-Host
,或者使用
Tee-Host
便利功能如this answer所示,它具有streaming其输出的附加优势。

Windows PowerShell /

Format-Table
解决方案(非流):

# Capture the data in an aux. variable 
# and *print* it to the display.
# Note: 
#  * $table = ... by design only captures the *data*, not the Format-Table output.
#  * Enclosing the assignment in (...) passes the value *through*.
(
  $table = 
    [PSCustomObject]@{
      Foo = 'Bar'
      Baz = 42
    } 
) | Format-Table | Out-Host

# Now also *output* the data, so it can be captured.
$table

Read-Host 'Enter number of campus'
© www.soinside.com 2019 - 2024. All rights reserved.