Как запустить новый экземпляр в powershell

powershell run executable

Running Programs with Elevated Privileges using Start-Process Command

Start-Process -FilePath "powershell.exe" -Verb RunAs
Start-Process -FilePath "C:\Temp\Log.txt" -Verb Print

Introduction to PowerShell’s Start-Process Command

The PowerShell Start-Process command is a powerful tool that is used to start a new program or script in a new process. This cmdlet lets us launch external programs directly from the command line or a PowerShell script. You can use it to start any program, including batch files, executables, and PowerShell scripts.

Running PowerShell Scripts with Start-Process Command

The PowerShell Start-Process command can also be used to start PowerShell scripts. To start a PowerShell script, you need to specify the location of the script using the FilePath parameter. Additionally, you can pass arguments to the script using the ArgumentList parameter.

Start-Process -FilePath "powershell.exe" -ArgumentList "-File C:\Scripts\MyScript.ps1"

This command would start the MyScript.ps1 script in a new PowerShell process.

Running executables as a different user with Start-Process in PowerShell

Start-Process -FilePath "powershell.exe" -Credential (Get-Credential)
powershell start-process
# Parameters
$FilePath = "C:\Scripts\RunMe.bat"
$UserName = "Crescent\salaudeen"
$Password = "Password goes here"
 
#Prepare the Credentials
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePassword

#Start a process with 
Start-Process -FilePath $FilePath -Wait -Credential $Credential

Running Executables with Start-Process Command

Running executables with Start-Process in PowerShell is a straightforward process. By simply specifying the path of the executable as an argument to the Start-Process cmdlet, PowerShell launches the program and executes it. This method is particularly useful when you want to run standalone executables without any additional parameters or customization. Let’s take a look at an example:

To start an executable, you need to specify the location of the executable using the FilePath parameter.

Start-Process -FilePath "C:\MyProgram\MyProgram.exe"

This command would start the MyProgram.exe executable.

Running Batch Files with Start-Process Command

PowerShell is not limited to running standalone executables only; it can also execute scripts and batch files effortlessly. By utilizing the Start-Process cmdlet, we can launch scripts and batch files in PowerShell and automate complex tasks. This provides us with the flexibility to integrate PowerShell with other scripting languages and leverage their capabilities. Let’s take a look at an example of running a PowerShell script using Start-Process:

To start a batch file, you need to specify the location of the batch file using the FilePath parameter.

Start-Process -FilePath "C:\MyBatchFile.bat"

Choosing The Right Method

Considering your working environment and your goals, it is probably the most reasonable thing to determine the best way to start a new PowerShell instance.

  • Start-Process:- Overall, the most flexible is the Start-Process cmdlet, which has parameters based on usage.
  • Invoke-Expression:- Offers more dynamic for scripting in scripting situations.
  • Keyboard Shortcuts: Keyboard shortcuts are sometimes easy to use, as they require one to type a letter or press a specific button to get the required result.
  • Scripting:- Scripting makes it possible to automate processes, apply templates or customize them.

Such methods will help you promptly start new instances of Powershell for your tasks, improving your scripting/automation game.

Running Programs with PowerShell’s Start-Process Command

Start-Process -FilePath "notepad.exe"

This command would start Notepad in a new process.

PowerShell Run Exe

If you want to run an executable in the background without displaying any windows or prompts, you can use the -WindowStyle Hidden parameter of the Start-Process cmdlet. Similarly, you can open any specified file (Non-executable file, such as a doc file) in a new window using:

Start-Process -FilePath "C:\Docs\AppLog.txt" -WindowStyle Maximized

This opens the file “C:\Docs\AppLog.txt” in a maximized window.

PowerShell to Open Files

To open a file in PowerShell, you can use the Start-process (or its alias: Start) command:

Start "C:\Temp\Archive.zip"

This method allows you to open files in the associated programs in PowerShell. In the above case, the zip file will be opened in WinRAR/WinZip/Windows Explorer, depending on your computer’s default program associations.

Open File Explorer from PowerShell
To open Windows File Explorer from PowerShell, Use: Start-Process Explorer

When using RS, you can use the Invoke-Command cmdlet to run commands or scripts on distant systems within the same network, which has the effect of starting new PowerShell sessions on the given machines.

:/>  Как полностью и правильно удалить операционную систему Windows XP, 7, 8 с компьютера или ноутбука

Examples and use cases:

Running long-running scripts:

Start a new instance with – NoExit to keep the window open while a lengthy script executes, allowing you to monitor progress or interact with the new session if needed.

Isolating Script Execution:

Launch a new instance with specific execution policies or environment variables to ensure your script runs in a controlled environment without affecting the current session.

Automating tasks with scheduled jobs:

Use Start-Process within scheduled tasks to trigger Powershell scripts at specific times or events, running them in isolation from interactive sessions.

Remote management and script deployment:

Combine Invoke-command with Start-Process to remotely launch Powershell instances on multiple machines and execute deployment or configuration scripts.

Common Errors and Troubleshooting Tips with Start-Process Command

While the PowerShell Start-Process command is a powerful tool, there are a few common errors that you may encounter.

  1. Access is denied: One common error is the “Access is denied” error. This error occurs when you try to run a program or script with elevated privileges, but you do not have permission to do so. To fix this error, you will need to log in as an administrator or use the RunAs parameter to run the program with elevated privileges.
  2. File not found: Another common error is the “File not found” error. This error occurs when you specify an incorrect file path. To fix this error, you will need to double-check the file path and make sure that it is correct. This includes verifying file permissions and network access if the executable resides on a remote machine. Always use the full path of the executable to avoid any ambiguity or reliance on the system’s PATH environment variable.
  3. Invalid Arguments: If the executable requires specific arguments, ensure that they are passed correctly using the ArgumentList parameter of the Start-Process cmdlet.

Using Arguments with Start-Process Command

As mentioned earlier, the PowerShell Start-Process command allows you to pass arguments to the program or script you are starting. This can be useful if you need to customize the behavior of the program or script.

For example, if you are starting a program that requires command-line arguments, you can pass those arguments using the ArgumentList parameter.

Start-Process -FilePath "myprogram.exe" -ArgumentList "-arg1 value1", "-arg2 value2"

This command would start the myprogram.exe program with the arguments “-arg1 value1” and “-arg2 value2”. The parameter values depend on the application you are running. Let’s take an example: Suppose you want to open a URL in Google Chrome. Here’s how you can do it:

Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "https://www.google.com" -Wait -WindowStyle Maximized
start-process argument

In this example, the -FilePath parameter specifies the path to the executable file for Chrome and the -ArgumentList parameter provides the URL to open in Chrome. The arguments are passed as a string, where a space separates each argument. It also uses a wait switch to wait for the process to close and Windowstyle parameters. This enables us to provide multiple args to the executable and customize its behavior.

    • "C:\MY.exe" A "M=a b"
    • Therefore, after parsing its command line, MY.exe will see two arguments, with verbatim values A and M=a b, respectively.

That is, inside your C# verbatim string , use \"" to yield \", which is needed in order to pass a " through verbatim to the PowerShell command that is ultimately executed.


To spell it out the solution in full:

//  Note the `\` before `""`
string arg = @"-NoProfile Start-Process -FilePath 'C:\MY.exe' -ArgumentList 'A', '\""M=a b\""'";
psTry("powershell.exe", arg);

static void psTry(string file, string arg)
{
    Process process = new Process();
    process.StartInfo.FileName = file;
    process.StartInfo.Arguments = arg;
    process.Start();
}

Taking a step back:

If the sole intent is to launch another application with arguments, the PowerShell CLI (powershell.exe) needn’t be involved at all – you can invoke C:\MY.exe directly, as shown below.

// Note how the arguments are passed *inside a single string*,
// with embedded double-quoting.
psTry("C:\MY.exe", @"A ""M=a b""");
void psTry(string file, string args)
{
    Process process = new Process();
    process.StartInfo.FileName = file;
    process.StartInfo.Arguments = args;
    process.StartInfo.UseShellExecute = true; // execute in NEW WINDOW
    process.Start();
}

If your C# application is using .NET Core/ .NET 5+ rather than .NET Framework, argument-passing can even be simplified / made conceptually clearer via the .ArgumentList property, which – as an alternative to the single-string .Arguments property – accepts an array of literal (unquoted) arguments, with .NET taking care of any required quoting and/or escaping:

// .NET Core / .NET 5+ only:
// Pass the arguments as an *array* of *literal* tokens.
psTry("dep.exe", new [] { "A", "M=a b" });
void psTry(string file, string[] args)
{
    Process process = new Process();
    process.StartInfo.FileName = file;
    foreach (string arg in args)
    {
        process.StartInfo.ArgumentList.Add(arg);
    }
    process.StartInfo.UseShellExecute = true;
    process.Start();
}

Understanding the Start-Process Command

Run an Executable in PowerShell

The PowerShell Start-Process command has a number of different parameters that you can use to customize the way that the command runs. The most important parameter is the FilePath parameter, which specifies the location of the program or script that you want to start.

:/>  Что такое частота обновления монитора? Как поменять частоту монитора в Windows 7, 10? | - Решение проблем с ПК, советы и мнение экспертов.

Another important parameter is the ArgumentList parameter, which allows you to pass arguments to the program or script you are starting. For example, if you are starting a PowerShell script, you can pass in parameters to the script using the ArgumentList parameter.

The Start-Process command also has parameters that let you specify the working directory, window style, and priority of the process you’re starting. These parameters can be useful if you need to start a program or script in a specific way. Along with other default parameters, Here is the list of important parameters of start-process cmdlet:

ParameterDescription
-FilePathSpecify the executable, application, file, batch, or script to run
-ArgumentListSpecifies parameters to use with the process to start
-CredentialUser account to run the process
-NoNewWindowOpen a window in the current console process
-PassthruReturns the process object of the process started. You can get the process ID from it.
-RedirectStandardErrorSpecify text file to redirect error output to
-RedirectStandardInputText file with input for the process
-RedirectStandardOutputSpecify text file to redirect output to
-UseNewEnvironmentThe process will use new environment variables specified for the process instead default, under: Machine and user
-WindowStyleSpecifies the state of the window: Normal, Hidden, Minimized, or Maximized
-LoadUserProfileLoads the Windows user profile from the HKEY_USERS registry key for the current user. This does not affect the PowerShell profiles.
-WaitWait for the process to complete before continuing with the script
-WorkingDirectoryThe location where the process should start in
CommonParametersVerbose, Debug,ErrorAction, ErrorVariable, WarningAction, WarningVariable,OutBuffer, PipelineVariable, and OutVariable

Methods For Launching New Powershell Instances

cmdlet is the most versatile and customizable approach for launching new PowerShell instances. It allows you to specify various parameters to control the behaviour of the new process, including:

Path to the PowerShell executable (powershell.exe).

  • List of arguments to pass to the new instances, such as scripts or commands to execute.
  • Start-Process powershell.exe -ArgumentList “-ExecutionPolicy Bypass -File C:\MyScript.ps1”

It prevents a new window from opening, keeping the process within the current console.

  • Keep the new window open after the script finishes.
  • Start-Process powershell.exe -ArgumentList “-NoExit”, “-noprofile” “-command Get-Process”

Allows the window style for the current form or a particular form by using commands such as normal, maximized, or minimized.

Start-Process powershell.exe -WindowStyle Maximized

Launches PowerShell using the default shell execution method.

Start-Process powershell.exe -ArgumentList “-ExecutionPolicy Bypass -File C: from the cmd.exe, open PowerShell and run the script “MyScript.ps1” in the latest window with the statement: -WindowStyle Maximized

This command starts a new PowerShell instance in  a maximized window, bypassing the execution policy to run the script C:\MyScript.ps1

cmdlet directly executes a string as a PowerShell command within a new process. This method is simpler but offers less control compared to the Start-Process.

Invoke-Expression “(Start-Process powershell.exe -Argument List ‘-noprofile’, ‘-command Get-Date’)”

This command launches a new PowerShell instance and retrieves a list of running processes.

For quick access, you can use keyboard shortcuts to open new PowerShell instances:

  • Hold shift while clicking the Start menu and selecting “Windows Powershell”.
  • Press Win+R, type “powershell”, and press Enter.
  • Scripting techniques:- You can also leverage PowerShell scripts to automate the process of instances with desired configurations. Here is an example: 
function Start-NewPSInstance {
param (
[Paramater (Mandatory = $true)]
[string] $ScriptPath,
[string] $Arguments = “ “
)
Start-Process powershell.exe -ArgumentList “-noprofile”, “-ExecutionPolicy Bypass”, “-File $ScriptPath”, $Arguments
}
                       Start-NewPSInstance -ScriptPath “C:\MyLongRunningScript.ps1” -Arguments “-verbose” 

In scripts, you can leverage various methods to launch new PowerShell instances depending on your specific needs:

:/>  Чем открыть пдф? Топ бесплатных программ для чтения PDF

Calling Start-Process within a script:

This allows programmatic control over launching new instances with desired parameters.

Using the dot (.) operator:

The dot operator (.) executes a command in a child process, essentially creating a new instance for that specific command.

Start-Process powershell.exe-ArgumentList “-noprofile -command Get-Date”

 # Using the dot operator

Get-ChildItem. -Filter “*.txt”

The first line launches a new instance to display the current date. The second line uses the dot operator to list text files within the current directory in a separate process.

Understanding PowerShell Instances

PowerShell can be opened in two ways: affiliated or new. When opened, an instance is created for you. It has its own memory space, flags, execution context, environment variables, and other things. You will find that when you type in commands or scripts to execute in this instance, they will not impact any other instances or the main system environment.   

Table of contents

  • Introduction to PowerShell’s Start-Process Command
  • Understanding the Start-Process Command
  • Running Programs with PowerShell’s Start-Process Command
  • Running Programs with Elevated Privileges using Start-Process Command
  • Running executables as a different user with Start-Process in PowerShell
  • Running PowerShell Scripts with Start-Process Command
  • Using Arguments with Start-Process Command
  • Running Executables with Start-Process Command
  • Running Batch Files with Start-Process Command
  • Common Errors and Troubleshooting Tips with Start-Process Command
  • Conclusion and Best Practices

Mastering PowerShell Instances

Understanding how to launch new PowerShell instances empowers you to manage tasks efficiently and execute specific commands or scripts in isolated environments. Combining the different methods and advanced considerations discussed in this post, you can tailor your approach to various automation and scripting scenarios with your PowerShell workflows.

Conclusion and Best Practices

When using the Start-Process command, it is important to double-check your file paths and arguments to avoid common errors. Additionally, it is a good practice to test your commands in a test environment before running them in a production environment.

Now that you have a better understanding of the PowerShell Start-Process command, you can start using it to automate your tasks and streamline your workflow!

How do I run a PowerShell script like an EXE?

How do I run an EXE file in PowerShell?

To run an EXE file in PowerShell, you can use the “Start-Process” cmdlet. Here’s an example of the command you can use: “Start-Process -FilePath 'C:\Path\to\file.exe'“. Replace ‘C:\Path\to\file.exe‘ with the actual path to your EXE file.

How do I install an EXE file in PowerShell silently?

To install an EXE file silently using PowerShell, you can use the Start-Process cmdlet with the -ArgumentList parameter. Here’s an example of the command you can use: Start-Process -FilePath "path\to\file.exe" -ArgumentList "/silent"

How do I open an application in PowerShell?

How to run an exe file from the command line?

To run an EXE file from the command line, you need to navigate to the directory where the file is located using the “cd” command. Once you are in the current directory, you can simply type the name of an executable file and press enter to run it.

How do I run PS from the command prompt?

How can I wait for a process to finish before proceeding?

To make PowerShell wait for a process to finish before continuing, you can use the -Wait parameter with Start-Process. This parameter ensures that PowerShell waits for the process and all its descendants to exit before returning control.

Can I pass arguments to the executable with Start-Process?

Yes, you can pass arguments to the executable using the -ArgumentList parameter. Start-Process -FilePath "notepad.exe" -ArgumentList "C:\Temp\Logs.txt"

Can I capture the output of a process started with Start-Process?

Yes, you can capture the output of a process by using the -RedirectStandardOutput parameter and specifying a file path to store the output. For example:
Start-Process -FilePath "ping.exe" -ArgumentList "google.com" -RedirectStandardOutput "output.txt"
This command will start the ping command, ping google.com, and redirect the output to the “output.txt” file.

Can I start a process in a minimized or maximized window?

Yes, you can control the window state of the process using the -WindowStyle parameter. The available options are “Normal”, “Hidden”, “Minimized”, and “Maximized”. For example: Start-Process -FilePath "notepad.exe" -WindowStyle Minimized

Оставьте комментарий