How to run PowerShell commands from the command prompt?

PowerShellMicrosoft TechnologiesSoftware & Coding

To run Powershell commands from the command prompt or cmd, we need to call the PowerShell process PowerShell.exe.

Example

See the sample example,

C:\> Powershell.exe -Command "Write-Output 'Hello world'"
Hello world

Similarly, you can call any command. We will use another example to get service information

C:\> Powershell.exe -Command "Get-Service Spooler"
Status   Name    DisplayName
------   ----    -----------
Running  Spooler Print Spooler

To run multiple commands,

C:\> Powershell.exe -Command "Stop-Service Spooler -verbose -passthru;
Start-Service
Spooler -verbose -passthru"

Output

VERBOSE: Performing the operation "Stop-Service" on target "Print Spooler (Spooler)".
Status Name DisplayName
------ ---- -----------
Stopped Spooler Print Spooler
VERBOSE: Performing the operation "Start-Service" on target "Print Spooler (Spooler)".
Running Spooler Print Spooler

The above command is similar to,

C:\> Powershell.exe Invoke-Command -scriptblock {
   "Stop-Service Spooler -verbose - passthru;
   Start-Service Spooler -verbose -passthru"
}
raja
Published on 30-Mar-2021 13:22:36
Advertisements