1

我正在开发一个 PS 脚本,该脚本将允许用户在命令行上粘贴一堆电子邮件,然后该脚本将解析每个电子邮件并在它们上运行另一个函数。

我已经四处寻找解决方案并在 VS Code 中玩过,但似乎没有什么能像我想要的那样工作。

用户粘贴的电子邮件格式如下,从 txt 文件中复制:

1@mail.com
2@mail.com
3@mail.com

每封电子邮件由换行符分隔。

使用 Read-Host,如果我粘贴多行,它只需要第一行,运行我拥有的任何功能,然后在下一行出错。

基本上我希望输入/输出看起来像这样:

Paste emails: 
1@mail.com
2@mail.com
3@mail.com

Operation was performed on email 1@mail.com
Operation was performed on email 2@mail.com
Operation was performed on email 3@mail.com

任何帮助将非常感激。谢谢!

4

2 回答 2

2

像这样?继续追加到一个数组,直到输入一个空行。

$list = @()
while ($a = read-host) {
  $list += $a}
a
b
c

$list
a
b
c
于 2021-07-21T20:12:29.727 回答
1

Read-Host本质上只支持一行输入,因此您有以下选择

  • 让您的用户复制并粘贴以空格分隔的电子邮件地址的单行列表(例如,1@mail.com 2@mail.com ...

    • 然后,您可以将Read-Host返回值拆分为地址数组
      $addresses = -split (Read-Host ...)
  • 使用接受多行输入的基于GUI的提示机制- 请参阅下面的示例代码。

或者:

  • 让用户指定包含电子邮件地址的文件的路径,然后您可以使用Get-Content.

  • 如果您不介意在仅输入一个地址或粘贴一个或多个地址后没有尾随换行符后必须按Enter 两次,请考虑js2010 的简单基于循环的替代方案


使用 WinForms 创建多行输入框

  • 注意:对于单行输入框,可以使用[Microsoft.VisualBasic.Interaction]::InputBox()- 查看这个答案

下面创建了一个固定大小的示例对话框,带有多行文本框以及确定和取消按钮(PSv5+,但可以适应早期版本):

# Declare implied namespaces, so that types from
# the loaded assemblies can be referred to by mere name
# (e.g., 'Form' instead of 'System.Windows.Forms')
# Requires PSv5+
using namespace System.Windows.Forms
using namespace System.Drawing

# Load the System.Windows.Forms assembly
# which implicitly loads System.Drawing too.
Add-Type -AssemblyName System.Windows.Forms

# Create the form.
($form = [Form] @{
  Text = "Enter Email Addresses"
  Size = [Size]::new(300,300)
  ControlBox = $false
  FormBorderStyle = 'FixedDialog'
  StartPosition = 'CenterScreen'
}).Controls.AddRange(@(

  ($textBox = [TextBox] @{
    MultiLine = $true
    Location = [Point]::new(10, 10)
    Size = [Size]::new(260, 200)
  })

  ($okButton = [Button] @{
    Location = [Point]::new(100, 220)
    Size = [Size]::new(80,30)
    Text = '&OK'
    DialogResult = 'OK'
    Enabled = $false
  })

  ($cancelButton = [Button] @{
    Location = [Point]::new(190, 220)
    Size = [Size]::new(80,30)
    Text = 'Cancel'
  })

))

# Make Esc click the Cancel button.
# Note: We do NOT use $form.AcceptButton = $okButton,
#       because that would prevent using Enter to enter multiple lines.
$form.CancelButton = $cancelButton

# Make sure that OK can only be clicked if the textbox is non-blank.
$textBox.add_TextChanged({
  $okButton.Enabled = $textBox.Text.Trim().Length -gt 0
})

# Display the dialog modally and evaluate the result.
if ($form.ShowDialog() -ne 'OK') {
  Throw 'Canceled by user request.'
}

# Parse the multi-line string into an array of individual addresses.
$addressesEntered = -split $textBox.Text

# Diagnostic output.
Write-Verbose -Verbose 'The following addresses were entered:'
$addressesEntered
于 2021-07-21T18:50:59.190 回答