We are performing maintenance on our clinet area https://my.hostafrica.com/ : Maintenance window from 11AM 03/07/2022

Windows PowerShell Commands

We believe in helping our clients to the best of our ability. This sometimes also means refusing to help clients as some queries fall outside our scope of support or area of expertise. Windows Powershell is one of these areas, so we’ve put together a helpful guide.

If you’re a Windows user who likes to write batch scripts and manage the OS via a shell, you have two options: Command Prompt (CMD) and PowerShell. CMD is the original command-line interface (CLI), and has been around since the Windows NT days. CMD remained the default shell for Windows until it was superseded by PowerShell in Windows 10 build 14791.

Even though Windows PowerShell is unarguably more powerful and efficient than CMD, there are still use-cases where the latter can be a better choice. In the following article, let’s take a look at how the two compare against each other, why PowerShell is better, and which are some of the most useful PowerShell commands to know of.


Contents


PowerShell vs. Command Prompt

PowerShell and Command Prompt (CMD) are fundamentally different from each other. Command Prompt is simply a CLI (command-line interface) to execute console programmes and the output is displayed as plain text.

PowerShell is a much more advanced shell that can do all that CMD does, along with so much more. PowerShell has an advanced cmdlet (pronounced “command-let”) instruction set, which is a perfect fit for modern-day automation and administration.

Cmdlets are native PowerShell commands which allow users to execute various OS-level operations. Cmdlets are implemented as instances of .NET classes, which can take various inputs, and produce objects as output, instead of just plain text.

This makes it much easier to write dynamic queries with cmdlets, and filter outputs easily; something that you can’t do with Command Prompt.

For example, both CMD and PowerShell give you the ability to view the IP address of your machine. On CMD, you can use the ipconfig /all command to get the IP address, and other information like DNS mask and network adapter etc.

However, you can’t specify any other inputs. On PowerShell, you have advanced cmdlets, like Get-NetIPAddress, which allow you to filter your output based on your needs. E.g. if you pass -AddressFamily IPv6 to the cmdlet, you’d only be shown the IPv6 address configuration.

Administrators can use various cmdlets in their scripts to automate tasks and configure system settings on-the-go.

Time-consuming tasks like registry management and Windows Management Instrumentation (WMI) can be streamlined using cmdlet-powered scripts. Such level of flexibility and convenience isn’t available with Command Prompt.

(Some) Benefits of PowerShell over Command Prompt

Automation made easy

Cmdlets make automation effortless. They’re easy to include in batch scripts, as providing them input and processing their outputs is very simple. Defining your own cmdlet class is also straightforward; as per Microsoft, you only need a dozen lines of code to write a custom cmdlet.

Object-oriented

Cmdlets follow all the principles of object-oriented programming, which contributes to their ease-of-use and interoperability.

The ability to pipe output

Much like other powerful shells (Bash in Linux), PowerShell gives you the ability to pipe/share input/output across cmdlets. This means that you can create a series of commands, with each command feeding its output to the next one.

For example, let’s suppose you want to pass the output of cmdlet X as the input to cmdlet Y. All you have to do is put a pipeline operator between the two cmdlets, and execute them at once:

Cmdlet-X | Cmdlet-Y

Aliasing

Aliasing is the process of defining nicknames for commands or cmdlets. CMD doesn’t support aliasing by default; however, there are certain workarounds available. On the other hand, PowerShell ships with the Set-Alias cmdlet, which makes it super easy for users to create as many aliases as they require.

How to use Windows Powershell commands

PowerShell commands are implemented as cmdlets, which are self-contained instances of .NET classes. To get a list of all the commands available to you, for the active session, you can use the Get-Command cmdlet.

Once you know which command/cmdlet you want to use, executing it is as simple as typing/pasting it in the shell and pressing Enter.

You can also use PowerShell commands in automation scripts to automate administrative and configuration tasks. If you want to perform some custom functionality via a cmdlet, you can also define your own cmdlet class.

More on this below.

Basic PowerShell commands

powershell commands

Now that we have established why PowerShell is the superior shell for Windows and how to use it, let’s get started by looking at some of the most basic PowerShell cmdlets/commands:

To check the PowerShell version on Windows 7, 8, 10, and 11 run:

$PSVersionTable.PSVersion
Output
Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      22000  282

To get your System information:

systeminfo
Output
Host Name:                 HOSTAFRICA
OS Name:                   Microsoft Windows 11 Home Single Language
OS Version:                10.0.22000 N/A Build 22000
OS Manufacturer:           Microsoft Corporation
OS Configuration:          Standalone Workstation
OS Build Type:             Multiprocessor Free
Registered Owner:          HOST AFRICA (PTY) LTD
Registered Organization:   N/A
Product ID:                00123-30072-24684-ABCD
Original Install Date:     2022/01/01, 08:41:34
System Boot Time:          2022/02/02, 09:25:24
System Manufacturer:       ASUSTeK COMPUTER INC.
System Model:              VivoBook_ASUSLaptop X512JA_X512JA
System Type:               x64-based PC
Processor(s):              1 Processor(s) Installed.
                           [01]: Intel64 Family 6 Model 126 Stepping 5 GenuineIntel ~1201 Mhz
BIOS Version:              American Megatrends Inc. X512JA.307, 2021/05/26
Windows Directory:         C:\WINDOWS
System Directory:          C:\WINDOWS\system32
Boot Device:               \Device\HarddiskVolume1
System Locale:             en-us;English (United States)
Input Locale:              en-us;English (United States)
Time Zone:                 (UTC+02:00) Harare, Pretoria
Total Physical Memory:     7 998 MB
Available Physical Memory: 1 019 MB
Page File Location(s):     C:\pagefile.sys
Domain:                    WORKGROUP
Logon Server:              \\HOSTAFRICA
Hotfix(s):                 3 Hotfix(s) Installed.
                           [01]: KB5010474
                           [02]: KB5011493
                           [03]: KB5009641
Network Card(s):           4 NIC(s) Installed.
                           [01]: Intel(R) Wireless-AC 9560 160MHz
                                 Connection Name: Wi-Fi
                                 Status:          Media disconnected
                           [02]: Bluetooth Device (Personal Area Network)
                                 Connection Name: Bluetooth Network Connection
                                 Status:          Media disconnected
                           [03]: TP-LINK Gigabit Ethernet USB Adapter
                                 Connection Name: Ethernet
                                 DHCP Enabled:    No
                                 IP address(es)
                                 [01]: 192.168.111.13
                                 [02]: fe80::e4a7:427e:428f:82a3
                           [04]: TAP-Windows Adapter V9 for OpenVPN Connect
                                 Connection Name: Local Area Connection
                                 DHCP Enabled:    No
                                 IP address(es)
                                 [01]: 123.456.111.11
                                 [02]: fe20::s89:8abc:10zs:egt0

To get all the processes currently running on the computer:

Get-Process

You can also use another Process command to stop an unresponsive process e.g.

Stop-Process -Name notepad

To get a list of all the commands that you can use in the current session:

Get-Command

To get a list of installed services on the system:

Get-Service

To get help with any command or know more about it, you can use the Get-Help command on the Get-Service command as follows:

Get-Help -Name Get-Service

To get a list of all commands:

Get-Help *

To parse different types of event logs:

Get-EventLog

To clear history, i.e. remove the record of all previously run commands in the current session:

Clear-History

Windows PowerShell execution policies: Get and Set scripts

Microsoft has disabled scripting by default in an effort to prevent malicious code from executing in a PowerShell environment.

To change the existing policy or to find out what it is, you can use the Get-ExecutionPolicy and the Set-ExecutionPolicy commands. Four levels of control are available:

  • Restricted — Restricted is the default execution policy and locks PowerShell down so that commands can be entered only interactively. PowerShell scripts aren’t allowed to run.
  • All Signed — If the execution policy is set to All Signed then scripts will be allowed to run, but only if they’re signed by a trusted publisher.
  • Remote Signed — If the execution policy is set to Remote Signed, any PowerShell scripts that’ve been locally created will be allowed to run. Scripts created remotely are allowed to run only if they are signed by a trusted publisher.
  • Unrestricted — As the name implies, Unrestricted removes all restrictions from the execution policy.

To change a policy, enter the Set-ExecutionPolicy command followed by the policy name. So, if you want all scripts to run with NO restriction, enter the following:

Set-ExecutionPolicy Unrestricted

How to run Windows PowerShell scripts

A PowerShell script is really nothing more than a text file. The file contains a series of PowerShell commands, with each command on a separate line. For the text file to be treated as a PowerShell script, its filename needs to end with the .PS1 extension.

Option 1: To execute a PowerShell script, you will usually have to type the full path, along with the filename. For example, to run a script named MyScript.ps1, you might type:

C:\Scripts\MyScript.ps1

Option 2: is to navigate to the directory which contains the script, put .\ before the name of the script, and press Enter. For example, if you are inside the C:\Scripts directory, you can type:

.\MyScript.ps1

Harnessing the power of variables

Although you can use pipelining to feed one command’s output into another, sometimes pipelining alone is not enough. When you pipeline a command’s output into another command, that output is used immediately.

Occasionally, you may need to store the output for a while so that you can use it later. This is where variables come into play.

It’s easy to think of a variable as a repository for storing a value, but in PowerShell, a variable can store a command’s full output.

For example, suppose you want to store the list of processes running on a server as a variable. To do so, you could use this line of code:

$a = Get-Process

Here, the variable is named $a. If you want to use the variable, simply call it by name. For example, typing $a prints the variable’s contents on the screen.

You can assign a variable to the final output of multiple commands that have been pipelined together. Just surround the commands with parentheses.

For example, to sort the running processes by process ID and then assign the output to a variable, you could use this command:

$a = (Get-Process | Sort-Object ID)

Other useful PowerShell commands

Find the five processes using the most memory (this will be familiar to most Linux administrators):

ps | sort –p ws | select –last 5

To restart a service such as DHCP, execute the following:

Restart-Service DHCP

To delete all the files in a directory without being prompted for confirmation:

Remove-Item C:\tobedeleted –Recurse

To restart the computer you are logged in to:

(Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(2)

The Get-Process displays all the currently running programs on the system. To figure out whether a specific program (e.g. notepad) is running or not:

Get-Process | Where-Object {$_.Name –eq "notepad"}

To show the services that are running:

Get-Service | Where-Object {$_.Status –eq “Running”}

PowerShell processes every record output that Get-Service throws, evaluates whether the Status attribute is Running, and filters accordingly.

Note: $_ refers to the current record/object in the pipe |.

curl

curl is a command-line utility to send HTTP/HTTPS/FTP/SMTP requests to a local/remote server. It comes in very handy when debugging/testing web applications, or writing automation scripts.

In the latest versions of Windows, the curl executable is installed by default, and can be accessed directly via PowerShell, albeit in a unique way.

Under the hood, the curl command on PowerShell is an alias to the Invoke-WebRequest cmdlet, which offers similar features as curl.

To access the actual curl executable, you have to use curl.exe on PowerShell.

For example, to check whether curl’s present on your machine, run:

curl.exe --version

or

Get-Command curl.exe
Ouput
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     curl.exe                                           7.79.1.0   C:\WINDOWS\system32\curl.exe

If you can see the curl version in the output, then that means it’s installed. Here are some ways to use the curl command:

View the returned HTML from a server:

curl.exe https://www.hostafrica.ng/

To display header information from the response:

curl.exe -I https://www.hostafrica.ng/

To post some data to a local server:

curl.exe http://127.0.0.1:4000/sample/8 -X PATCH -H "Content-Type: application/json" -d '{\"rating\":\"2\"}'

PowerShell’s a powerful tool for administering, configuring, and even controlling Windows servers. It’s not possible to cover the full potential of PowerShell in a single article, but we hope that this one gave you a good sense of what’s possible!


FAQs

How to check PowerShell version in Windows 7?

To check the PowerShell version on Windows 7, 8, 10, and 11 run:

$PSVersionTable.PSVersion

How to run curl command in Windows PowerShell?

In the latest versions of Windows 10 and 11, curl comes pre-installed, but the curl command on PowerShell is an alias to the Invoke-WebRequest cmdlet, which provides similar functionality to curl. If you want to use the actual curl utility, you have to use curl.exe instead of plain curl.

For example, to check whether curl’s installed on your system, run: curl.exe --version

If you get the curl version as output that means it’s installed. Here are some ways to run the curl command:

  • Display the returned HTML from a server: curl.exe https://www.hostafrica.ng/
  • To view header information from the response: curl.exe -I https://www.hostafrica.ng/
  • To post some data: curl.exe http://127.0.0.1:4000/sample/8 -X PATCH -H "Content-Type: application/json" -d '{\"rating\":\"2\"}'

Does the touch command work in Windows PowerShell?

No, the touch command is not present in PowerShell. On Linux systems, touch command can be used to create a new file. On PowerShell, you can use alternatives of the command to achieve the same. For instance, you can use the following command to create a new file in the current directory:

echo $null >> filename

Does Windows PowerShell use the same commands as Mac?

No, the Windows PowerShell doesn’t use the same commands as a Mac. Macs are shipped with UNIX shells, which are fundamentally different to Windows PowerShell. Not only are the instruction sets of both terminals different, their architectures and design are also dissimilar.

PowerShell get Windows product key

To retrieve the original Windows product key of the Windows machine you’re currently on, run the following command in PowerShell:

wmic path softwarelicensingservice get OA3xOriginalProductKey

What is Windows PowerShell vs Command Prompt?

PowerShell is a shell for Windows which has extensive administrative and automation capabilities. PowerShell is seen as the long-awaited successor of the antiquated command prompt, which remained the default shell for Windows for many a year.

PowerShell has numerous benefits that Command Prompt lacks::

  • It is object-oriented, which means that cmdlets take objects as inputs, and produce objects as outputs. This simplifies the process of automation and script writing.
  • It allows aliasing by default. Conversely, Command Prompt doesn’t support aliasing out-of-the-box; however, it can be achieved via some workarounds.
  • It allows you to pipe | outputs, i.e. feed the output of one command as input to another.

How to use Windows PowerShell commands?

PowerShell commands are implemented as cmdlets, which are self-contained instances of .NET classes. To get a list of all the commands available to you, for the active session, you can use the Get-Command cmdlet.

Once you know which command/cmdlet you want to use, executing it is as simple as entering it on the shell and pressing Enter.

You can also use PowerShell commands in automation scripts to automate administrative and configuration tasks. If you want to perform some custom functionality via a cmdlet, you can also define your own cmdlet class.

Is Windows PowerShell the same as Command Prompt?

No. PowerShell and Command Prompt (CMD) are both shells for use on Windows machines, but they’re two different applications that work very differently. Both are sometimes used to perform the same administrative and configurative operations, e.g. execute batch scripts, change path variables, tweak system settings etc. However, there are many differences between the two:

  • Command prompt is a command-line interface (CLI) that uses plain commands and returns outputs in plain text, which are executables; PowerShell is more advanced and uses cmdlets, which are standalone instances of .NET classes.
  • Automation with PowerShell is much easier and faster than with CMD.
  • PowerShell uses an object-oriented architecture, whereas Command Prompt doesn’t.
  • PowerShell supports aliasing by default. On CMD, aliasing can only be achieved via workarounds.

What is the difference between Windows PowerShell and Command Prompt?

Command Prompt (CMD) used to be the default shell for Windows till 2016, when it was succeeded by PowerShell. Both shells have many differences:

  • PowerShell introduces the concept of cmdlets, which are self-contained classes that take objects as inputs, and produce objects as outputs. CMD executes plain commands.
  • PowerShell allows for easy piping of inputs and outputs. Similar functionality is not found in Command Prompt.
  • With PowerShell, you can write your own custom cmdlet. Such a functionality is not present in CMD.
  • PowerShell has an object-oriented architecture, whereas Command Prompt doesn’t deal with objects.

Latest posts

Share this article: