Converting the Windows Script Host Run Method
Definition: Runs a program in a new process.
It’s pretty easy to start an external program from within Windows PowerShell (after all, PowerShell is a command shell). Want to start an instance of Notepad? This command should do the trick:
Note. If that command doesn’t do the trick that usually means that Notepad isn’t in your Windows path. In that case try using the complete path to the file: C:\Windows\Notepad.exe.
That’s nice, but with Windows Script Host’s Run method you can go a step beyond that; for one thing, you can specify the window state (minimized, maximize, hidden) when the process starts. We’d like to see you do that with Windows PowerShell!
$objStartInfo = New-Object System.Diagnostics.ProcessStartInfo $objStartInfo.FileName = "Notepad.exe" $objStartInfo.windowStyle ="Minimized" [void][System.Diagnostics.Process]::Start($objStartInfo)
What we’re doing with the preceding block of code is delving into the .NET Framework in order to specify startup options for our process. In the first line we use the New-Object cmdlet to create an instance of the System.Diagnostics.ProcessStartInfo class. In the next two lines we assign values to two properties of the ProcessStartInfo class: the FileName property gets the path to the executable file we want to start; and the windowStyle property gets the startup style for the process window. In this case we chose to start Notepad with the window minimized; alternatively, we could have set the windowStyle to Maximized, Normal, or Hidden.
And then, the piece de resistance: in line 4 we use the Start method to start our new instance of Notepad, passing the method the ProcessStartInfo object we just created and configured.
Here’s another example, one which starts a new instance of Windows PowerShell, and runs the script C:\Scripts\Test.ps1 in that instance. In this script we added two items to the arguments property: -noexit, which will keep the PowerShell window open after the script finishes running; and the path to the script we want to run.
Here’s the code:
$objStartInfo = New-Object System.Diagnostics.ProcessStartInfo $objStartInfo.FileName = "PowerShell.exe" $objStartInfo.windowStyle ="Normal" $objStartInfo.arguments = "-noexit C:\Scripts\Test.ps1" [System.Diagnostics.Process]::Start($objStartInfo)