PowerShell中实现人机交互

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

以下是我的代码,实现一个动态交互表单:

<#
    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()
}

使用方法如下:

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

运行效果如下:

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

posted @ 2015-06-22 14:15  天外归云  阅读(1900)  评论(4编辑  收藏  举报