Running commands in the shell - PowerShell (2024)

  • Article

PowerShell is a command-line shell and a scripting language used for automation. Similar to othershells, like bash on Linux or the Windows Command Shell (cmd.exe), PowerShell lets you to runany command available on your system, not just PowerShell commands.

Types of commands

For any shell in any operating system there are three types of commands:

  • Shell language keywords are part of the shell's scripting language.

    • Examples of bash keywords include: if, then, else, elif, and fi.
    • Examples of cmd.exe keywords include: dir, copy, move, if, and echo.
    • Examples of PowerShell keywords include: for, foreach, try, catch, and trap.

    Shell language keywords can only be used within the runtime environment of the shell. There is noexecutable file, external to the shell, that provides the keyword's functionality.

  • OS-native commands are executable files installed in the operating system. The executables canbe run from any command-line shell, like PowerShell. This includes script files that may requireother shells to work properly. For example, if you run a Windows batch script (.cmd file) inPowerShell, PowerShell runs cmd.exe and passes in the batch file for execution.

  • Shell environment-specific commands are commands defined in external files that can only beused within the runtime environment of the shell. These include scripts and functions, or they canbe specially compiled modules that add commands to the shell runtime. In PowerShell, thesecommands are known as cmdlets (pronounced "command-lets").

Running native commands

Any native command can be run from the PowerShell command line. Usually you run the command exactlyas you would in bash or cmd.exe. The following example shows running the grep command inbash on Ubuntu Linux.

sdwheeler@circumflex:~$ grep sdwheeler /etc/passwdsdwheeler:x:1000:1000:,,,:/home/sdwheeler:/bin/bashsdwheeler@circumflex:~$ pwshPowerShell 7.2.6Copyright (c) Microsoft Corporation.https://aka.ms/powershellType 'help' to get help.

After starting PowerShell on Ubuntu, you can run the same command from the PowerShell command line:

PS /home/sdwheeler> grep sdwheeler /etc/passwdsdwheeler:x:1000:1000:,,,:/home/sdwheeler:/bin/bash

Passing arguments to native commands

Most shells include features for using variables, evaluating expressions, and handling strings. Buteach shell does these things differently. In PowerShell, all parameters start with a hyphen (-)character. In cmd.exe, most parameters use a slash (/) character. Other command-line tools maynot have a special character for parameters.

Each shell has its own way of handling and evaluating strings on the command line. When runningnative commands in PowerShell that expect strings to be quoted in a specific way, you may needadjust how you pass those strings.

For more information, see the following articles:

  • about_Parsing
  • about_Quoting_Rules

PowerShell 7.2 introduced a new experimental feature PSnativeCommandArgumentPassing that improvednative command handling. For more information, see PSnativeCommandArgumentPassing.

Handling output and errors

PowerShell also has several more output streams than other shells. The bash and cmd.exe shellshave stdout and stderr. PowerShell has six output streams. For more information, seeabout_Redirection and about_Output_Streams.

In general, the output sent to stdout by a native command is sent to the Success stream inPowerShell. Output sent to stderr by a native command is sent to the Error stream inPowerShell.

When a native command has a non-zero exit code, $? is set to $false. If the exit code is zero,$? is set to $true.

However, this changed in PowerShell 7.2. Error records redirected from native commands, like whenusing redirection operators (2>&1), aren't written to PowerShell's $Error variable and thepreference variable $ErrorActionPreference doesn't affect the redirected output.

Many native commands write to stderr as an alternative stream for additional information. Thisbehavior can cause confusion in PowerShell when looking through errors and the additional outputinformation can be lost if $ErrorActionPreference is set to a state that mutes the output.

PowerShell 7.3 added a new experimental feature PSnativeCommandErrorActionPreference that allowsyou to control whether output to stderr is treated as an error. For more information, seePSnativeCommandErrorActionPreference.

Running PowerShell commands

As previously noted, PowerShell commands are known as cmdlets. Cmdlets are collected into PowerShellmodules that can be loaded on demand. Cmdlets can be written in any compiled .NET language or usingthe PowerShell scripting language itself.

PowerShell commands that run other commands

The PowerShell call operator (&) lets you run commands that are stored in variables andrepresented by strings or script blocks. You can use this to run any native command or PowerShellcommand. This is useful in a script when you need to dynamically construct the command-lineparameters for a native command. For more information, see the call operator.

The Start-Process cmdlet can be used to run native commands, but should only be used when you needto control how the command is executed. The cmdlet has parameters to support the followingscenarios:

  • Run a command using different credentials
  • Hide the console window created by the new process
  • Redirect stdin, stdout, and stderr streams
  • Use a different working directory for the command

The following example runs the native command sort.exe with redirected input and output streams.

$processOptions = @{ FilePath = "sort.exe" RedirectStandardInput = "TestSort.txt" RedirectStandardOutput = "Sorted.txt" RedirectStandardError = "SortError.txt" UseNewEnvironment = $true}Start-Process @processOptions

For more information, see Start-Process.

On Windows, the Invoke-Item cmdlet performs the default action for the specified item. Forexample, it runs an executable file or opens a document file using the application associated withthe document file type. The default action depends on the type of item and is resolved by thePowerShell provider that provides access to the item.

The following example opens the PowerShell source code repository in your default web browser.

Invoke-Item https://github.com/PowerShell/PowerShell

For more information, see Invoke-Item.

Running commands in the shell - PowerShell (2024)
Top Articles
Does it appear shipment address in sent transaction?
Recommendations for shipping jewelry | The Hanover Insurance Group
Cappacuolo Pronunciation
Napa Autocare Locator
27 Places With The Absolute Best Pizza In NYC
Which aspects are important in sales |#1 Prospection
Best Private Elementary Schools In Virginia
Cape Cod | P Town beach
Crusader Kings 3 Workshop
Theycallmemissblue
Evil Dead Rise Showtimes Near Regal Columbiana Grande
House Party 2023 Showtimes Near Marcus North Shore Cinema
Belly Dump Trailers For Sale On Craigslist
Moonshiner Tyler Wood Net Worth
Minecraft Jar Google Drive
Wal-Mart 140 Supercenter Products
Ms Rabbit 305
Bing Chilling Words Romanized
Amih Stocktwits
Self-Service ATMs: Accessibility, Limits, & Features
Holiday Gift Bearer In Egypt
About My Father Showtimes Near Copper Creek 9
Greenville Sc Greyhound
Elbert County Swap Shop
1773x / >
Club Keno Drawings
Missing 2023 Showtimes Near Grand Theatres - Bismarck
South Florida residents must earn more than $100,000 to avoid being 'rent burdened'
JD Power's top airlines in 2024, ranked - The Points Guy
Moxfield Deck Builder
Http://N14.Ultipro.com
Devotion Showtimes Near Mjr Universal Grand Cinema 16
2024 Ford Bronco Sport for sale - McDonough, GA - craigslist
Grapes And Hops Festival Jamestown Ny
Bay Focus
Jewish Federation Of Greater Rochester
Hindilinks4U Bollywood Action Movies
One Main Branch Locator
Craigslist Tulsa Ok Farm And Garden
10 Rarest and Most Valuable Milk Glass Pieces: Value Guide
Live Delta Flight Status - FlightAware
Jetblue 1919
888-822-3743
Rush Copley Swim Lessons
Noh Buddy
Haunted Mansion (2023) | Rotten Tomatoes
Gear Bicycle Sales Butler Pa
Ark Silica Pearls Gfi
28 Mm Zwart Spaanplaat Gemelamineerd (U999 ST9 Matte | RAL9005) Op Maat | Zagen Op Mm + ABS Kantenband
Service Changes and Self-Service Options
Subdomain Finer
The Ultimate Guide To 5 Movierulz. Com: Exploring The World Of Online Movies
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 6372

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.