How to run PowerShell Script from CMD

Configurare noua (How To)

Situatie

Running PowerShell scripts directly from the Command Prompt (CMD) is a common task for developers and system administrators. run a PowerShell script from CMD. Whether you’re automating tasks or integrating different scripting environments, knowing how to execute a PowerShell script in CMD can be incredibly useful.

Solutie

Pasi de urmat

Open the run dialogue box (Win + R) and type “Command Prompt” or “CMD” or you can click on the Start Menu icon (on bottom-left side) and search for “Command prompt” and click on “Run as Administrator”. Once you enter the command line, simply type “PowerShell” and hit the enter button.

Assume you have a script file, named (shell.ps1) located in C:\ so you can get the entire details using the following command:

powershell -File "C:\Scripts\example.ps1"

Execute PowerShell Scripts from CMD using PowerShell Command

If you are getting errors from the above process, the following command could be a relief. Execute the command like it is mentioned to get details without any error.

powershell.exe <Enter Full Path>

You can also pass arguments to the PowerShell script using command line. Here’s an example:

Input:

param (
    [string]$Name,
    [int]$Age
)
Write-Host "Hello, $Name! You are $Age years old."

output44

Run Inline PowerShell Commands

This method is suitable where instead of creating a script file, run inline commands from command line PowerShell. Here’s an example for better understanding:

Input:

powershell -Command "Write-Host 'Hello, World!'"

Run PowerShell Script from Command Line as Administrator

You will be required to have an administrator access to run certain scripts. Here’s an example of a script that requires elevated privileges:

Input:

powershell -File "C:\Scripts\example.ps1"

mailbox

Tip solutie

Permanent

Voteaza

(4 din 11 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?