다음을 통해 공유


The PowerShell Yes-man

Every sysadmin encounters those command-line applications that require the user to enter 'y' repeatedly to accept prompts.  This is time-consuming and capitalizes all of your time until the task is finished.

The good news?  PowerShell has a way to automate those infinite y's, or whatever your prompt may require!  Here's a sample snippet that we will take apart:


$psiApp = New-Object System.Diagnostics.ProcessStartInfo
$psiApp.FileName = "YourApp.exe"
$psiApp.UseShellExecute = $false
$psiApp.RedirectStandardInput = $true

$prcApp = [System.Diagnostics.Process]::Start($psiApp)

While (!$prcApp.HasExited) {
$prcApp.StandardInput.WriteLine("y")

      Start-Sleep -Milliseconds 500
}


In this script, we start by creating a new instance of System.Diagnostics.ProcessStartInfo (MSDN).  ProcessStartInfo is a .Net object used when you want to create a new process using some custom parameters.  The properties we configure on this object are:

  • FileName: The path to the file you wish to create the process from
  • UseShellExecute: This determines whether the file is launched using shell execute (think start.exe) or not.  Using shell execute means that the FileName can specify non-executable files with file associations (for example, a .docx document would launch Microsoft Word and open the document).  With ShellExecute disabled, the file in FileName must be executable.
  • RedirectStandardInput: This property enables us to programmatically write text directly to the STDIN pipe to the process.  We will use this to send in our series of Y's.

Once the ProcessStartInfo object is configured, we call the Start method (MSDN) of System.Diagnostics.Process (MSDN).  This creates a process using our previously configured ProcessStartInfo object, thus launching your application.

The last section is a Do-While loop that watches the HasExited property (MSDN) of the Process we just created.  This property will remain False until the program closes, at which time there is no reason to continue attempting to send Y's to it.

Within this loop we have two PowerShell commands.  The first one calls the WriteLine() (MSDN) method of the StandardInput property (MSDN) our process.  According to MSDN. the StandardInput property is a System.IO.StreamWriter object (MSDN).  A StreamWriter is a .Net object that allows us to write characters to the stream, in this case the StandardInput property of our process, or STDIN.  Calling WriteLine("y") on this stream will send a "y" into the input for the process.

Last, we implement a 500 ms delay so that we don't totally inundate the application with endless Y's :).