Simple InputBox function

前端 未结 3 1271
逝去的感伤
逝去的感伤 2020-12-08 10:53

I\'m aware of a simple pop-up function for PowerShell, e.g.:

function popUp($text,$title) {
    $a = new-object -co         


        
相关标签:
3条回答
  • 2020-12-08 11:31

    Probably the simplest way is to use the InputBox method of the Microsoft.VisualBasic.Interaction class:

    [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
    
    $title = 'Demographics'
    $msg   = 'Enter your demographics:'
    
    $text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
    
    0 讨论(0)
  • 2020-12-08 11:51

    The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.

    $us = Read-Host 'Enter Your User Name:' -AsSecureString
    $pw = Read-Host 'Enter Your Password:' -AsSecureString
    

    This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:

    [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
    [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))
    

    If the info does not need to be secure at all you can convert it to plain text:

    $user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
    

    Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0

    0 讨论(0)
  • 2020-12-08 11:51

    It would be something like this

    function CustomInputBox([string] $title, [string] $message, [string] $defaultText) 
    {
    $inputObject = new-object -comobject MSScriptControl.ScriptControl
    $inputObject.language = "vbscript" 
    $inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" ) 
    $_userInput = $inputObject.eval("getInput") 
    
    return $_userInput
    }
    

    Then you can call the function similar to this.

    $userInput = CustomInputBox "User Name" "Please enter your name." ""
    if ( $userInput -ne $null ) 
    {
     echo "Input was [$userInput]"
    }
    else
    {
     echo "User cancelled the form!"
    }
    

    This is the most simple way to do this that I can think of.

    0 讨论(0)
提交回复
热议问题