PowerShell中实现人机交互

编写脚本的过程当中有不少时候须要进行人机交互,好比我写一个脚本,须要动态的输入一些内容,好比用户名和密码之类的东西,这些是没办法事先写进代码里的。而经过外部文件进行信息读取,友好性又差了点。因此当咱们须要动态的用户输入信息时,一个这样的表单真是必不可少。虽然这并非PowerShell做为一个脚本语言的强项,可是任何具备特点的语言确定都不是完美的,因此咱们为了充分发挥脚本语言的灵活性,有时候也不得不为他的弱项买单。(其实也没有太弱,若是VS中WinForm用的熟,这个原理也是同样的,PowerShell作为一种脚本语言,和C#同样是基于.NET框架的,因此类库相通,不少特性均可以互联。)框架

如下是个人代码,实现一个动态交互表单:ide

<#
    Intro: This function will display a form to communicate with the user.
    Input: -FormText -ButtonText
    Example: MakeForm -FormText "ForInput" -ButtonText "Submit"
    Use: To make the PowerShell program's interactivity better.
#>
function MakeForm{
    param($FormText,$ButtonText)
    $null = [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    $form = New-Object Windows.Forms.Form
    $form.size = New-Object Drawing.Size -Arg 400,80
    $form.StartPosition = "CenterScreen"
    $form.Text = $FormText.toString()
    $textBox = New-Object Windows.Forms.TextBox
    $textBox.Dock = "fill"
    $form.Controls.Add($textBox)
    $button = New-Object Windows.Forms.Button
    $button.Text = $ButtonText
    $button.Dock = "Bottom"
    $button.add_Click(
    {$global:resultText = $textBox.Text;$form.Close()})
    $form.Controls.Add($button)
    [Void]$form.ShowDialog()
}

使用方法以下:spa

 MakeForm -FormText "What's your name" -ButtonText "Submit" 3d

运行效果以下:orm

PS:用户输入的内容将存储到变量$global:resultText中。(本质就是建立了一个WinForm窗体对象,并动态的赋予窗体标题和按钮名称。)对象