Tag: PowerShell

Analogue of Add-Computer in PowerShell 7

===========================================================

UPDATE:

Testing with PowerShell 7.3.0-preview.5 shows that Add-Computer is back!

Command

Get-Command -module Microsoft.PowerShell.Management

outputs the following:

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Add-Computer                                       1.0        Microsoft.PowerShell.Management
………………….
………………….

That is, Add-Computer is present, it is a function (not a cmdlet), the version is indicated as 1.0. The status of Add-Computer is not completely clear: is it a temporary hotfix or a gradual return of the cmdlet?

===========================================================

Add a computer to a domain or workgroup in PowerShell

The Add-Computer cmdlet joins a computer to a Windows Domain or to a Workgroup. The Add-Computer cmdlet adds the local computer or remote computers to a domain or workgroup, or moves them from one domain to another. It also creates a domain account if the computer is added to the domain without an account. You can use the parameters of this cmdlet to specify an organizational unit (OU) and domain controller or to perform an unsecure join.

An example of a command that adds the local computer to the domain and restarts the computer:

Add-Computer -DomainName Domain01 -LocalCredential Domain01\Administrator -Restart

The following command adds the local computer to the workgroup, or renames the workgroup (if the computer is already in a workgroup with a different name):

Add-Computer -WorkgroupName WORKGROUP-A

These commands work fine in PowerShell 5, which is built in by default in all versions of Windows up to Windows 11 and all server versions up to Windows Server 2022.

See also: How to check PowerShell version in Windows 11

Error “Add-Computer: The term 'Add-Computer' is not recognized as a name of a cmdlet, function, script file, or executable program.”

But in PowerShell 7, this command is missing:

Add-Computer
Add-Computer: The term 'Add-Computer' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Suggestion [4,General]: The most similar commands are: Add-Computer, Stop-Computer, Get-ADComputer, New-ADComputer, Set-ADComputer, Add-Content, Rename-Computer, Add-Member.

You can verify that the command named Add-Computer is indeed present in PowerShell 5, where it is placed in the Microsoft.PowerShell.Management module:

powershell
Get-Command -Module Microsoft.PowerShell.Management -Name *Computer* | Select Name

But Add-Computer is missing from PowerShell 7:

pwsh
Get-Command -Module Microsoft.PowerShell.Management -Name *Computer* | Select Name

You can count exactly how many commands are removed from the Management module when moving from PowerShell 5 to PowerShell 7:

powershell
Get-Command -Module Microsoft.PowerShell.Management | Measure-Object | select Count

pwsh
Get-Command -Module Microsoft.PowerShell.Management | Measure-Object | select Count

There were 89 command, 61 commands remained.

How to replace Add-Computer in PowerShell 7

One of the suggested alternatives seems to be the New-ADComputer cmdlet, but the documentation explicitly says that “This cmdlet does not join a computer to a domain”.

There is no information about where the Add-Computer cmdlet or what its alternative is in PowerShell.

One working solution, if you've already installed PowerShell 7, is to run the join Domain or Workgroup command in PowerShell 5. To do this, run the following sequence of commands:

powershell
Add-Computer -DomainName Domain01 -LocalCredential Domain01\Administrator -Restart

See also: How to install the latest PowerShell on Windows 11

Basics of launching and using command line utilities in Windows

Are the command line and command line utilities relevant today?

Windows users are accustomed to using programs (applications) with a graphical user interface, in which actions are performed using mouse clicks or keyboard input.

At the same time, even in Windows there are and can be installed many utilities, programs without a graphical interface, with very useful functionality. As a rule, programs without a graphical interface are designed to perform a highly specialized action or function and are designed for professionals.

Programs without a graphical interface are called “command line utilities”, “programs with a command line interface” (CLI).

There is no need to think that command line utilities are some kind of atavism and something outdated. This is very far from the truth! Entire layers of specialized programs in various fields are developed precisely as utilities with a command line interface.

The purpose of this note is to give a general idea to Windows users about how to deal with the command line. If you have downloaded the utility and cannot run it, then this note is for you!

When I click on the exe file, a black window flickers and then disappears

When you try to launch the command line utility by double-clicking, you will most likely encounter the console window flashing for a second, which immediately closes.

Programs with a command line interface are not designed to be launched by double-clicking. Instead, they need to be run, as you might have guessed, on the command line.

Windows has several environments for executing commands:

  • CMD
  • PowerShell (includes all the features of CMD and provides many cmdlets for administering Windows desktops and servers)

You can also remember Windows Terminal, but this is not a separate environment that has its own commands, but just an application for conveniently entering CMD and PowerShell commands.

To run the program, you need to open a Windows Terminal window (or PowerShell). To do this, press the key combination Win+x, and select “Windows Terminal” or “Windows Terminal (Admin)”:

What to choose: “Windows Terminal” or “Windows Terminal (Admin)”

Utilities can be run with normal user rights, or require running with Administrator rights.

With Administrator rights, for example, the following programs should be launched:

  • Programs that register and install themselves as system services
  • Programs that require low-level access to devices (for example, programs for partitioning or fixing disk errors)
  • Programs that change system settings that only an administrator can change.

An example of programs with a command line interface that require Administrator rights:

  • Apache (web server, it registers and starts itself as a system service)
  • MySQL (DBMS, it registers and starts itself as a system service)

An example of utilities that do not require elevated privileges:

How to run an executable on the command line

Consider running a program with a command line interface using the Apache web server (httpd) as an example.

The first option: you can simply drag and drop the executable file into the command line window. The Apache executable is httpd.exe.

The second option: on the command line, you can change the current working directory to the one where the Apache executable files are located. For example, my program is located in the C:\Apache24\bin\ folder, to change the current working folder, the “cd” command is used, after which the folder you want to go to is indicated, in my case the command looks like this:

cd C:\Apache24\bin\

As you can see from the screenshot, the C:\Users\MiAl folder has been changed to C:\Apache24\bin\.

Now, to run the program, it is enough to type the name of the executable file indicating the current folder. The current folder is indicated by a dot (.), then you need to put a backslash, it turns out like this:

.\httpd.exe

Apache is a network service, that is, a program that uses a computer network for its work. Specifically, Apache listens for incoming connections on port 80 (the service opens a port). For this reason, the Windows Firewall asks whether to allow the Apache HTTP Server program to communicate on the network, select “Allow access”.

Already at this stage, the web server is running, and you can open the address http://localhost/ in a web browser

To stop the service, press Ctrl+c.

How to get help using the utility

Typically, command-line utilities support various options that can be specified with a space after the executable file name.

Also, utilities usually have built-in help on available options, which can be displayed using the -h option or the --help option, which must be specified after the executable file name.

For example:

.\httpd.exe -h

In addition to command line options, many services are configured using configuration files, which are text files with a specific syntax. This is especially common for utilities that came to Windows from Linux, since in this operating system many programs are configured using text files.

In this case, quite often explanations of custom directives are contained in the configuration file itself in the form of notes, or in accompanying documentation.

README, ReadMe.txt, README.md files and software documentation

Utilities are usually accompanied by documentation. For example, this is an Apache archive:

As you can see, the ReadMe.txt file with documentation is attached to the archive – this is documentation from those who compiled Apache for Windows.

Inside the Apache24 folder there are even more files and folders with installation information and more.

This is a PHP archive – it also contains a README.md file that provides help information.

A MySQL archive containing a README file and a documentation folder or a link to the documentation.

Program in PATH environment variable

The above shows that in order to run the program, you need to go to the folder with this program.

Alternatively, you can specify the full path to the executable, for example:

C:\Server\bin\Apache24\bin\httpd.exe

It is this method that works when you drag and drop the utility into the console to run the utility – in this case, the full path to the file is inserted into the command line.

But some commands run from any folder, wherever you are on the command line. For example, try the following command:

find /?

The fact is that for operating systems there is such a thing as the PATH environment variable.

The essence of the PATH environment variable is as follows:

1. The PATH variable is assigned a value that consists of a list of folders, that is, paths in the system.

2. When you run a file on the command line, the operating system tries to find it both in the current folder (where you went with the “cd” command, or open by default), and in each folder specified in the PATH environment variable

3. If the file is found in the current folder, or in any PATH folder, then it is launched.

This is the reason the following command always works:

find /?

The reason is that it is placed in one of the folders listed in PATH (namely C:\Windows\System32\).

To view the current value of the PATH environment variable, run any of the following commands:

Get-ChildItem -Path Env:PATH

$env:PATH

Example PATH content in Windows 11:

C:\Program Files\PowerShell\7-preview;C:\Program Files\ImageMagick-7.1.0-Q16-HDRI;C:\Server\bin\PHP\;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\libnvvp;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\NVIDIA Corporation\Nsight Compute 2022.1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\PowerShell\7-preview\preview;C:\Users\MiAl\AppData\Local\Microsoft\WindowsApps

You can place frequently used utilities in a folder included in PATH. Either you can add a new folder to PATH with the utilities you want to run without specifying the full paths to the executable files, or without having to change to the directory with these utilities.

You can set the value of PATH (and other environment variables) both in the GUI and on the command line.

See also:

Do I need to specify the extension of the executable file

When running executable files, it is not necessary to specify the extension, because the console will understand what you mean. For example, the following two commands are identical:

hashcat.exe

hashcat

Conclusion

This note is intended to give you a general idea of how to start and use the command line utilities. For basic information on using a particular utility, see the help displayed with the -h option or the program's documentation.

If you encounter an error when starting the utility, try running the program in an elevated command prompt (with admin rights).

If you get a message that “file not found”, go to the folder with the installed program using the “cd” command, or drag and drop the executable file to the command line.

If you received an error message inside the program when starting the program, then study the utility options and examples of its launch in more detail.

How to install the Active Directory PowerShell module on Windows Server, Windows 11 and Windows 10

The Active Directory Module for Windows PowerShell is one of the main tools for domain administration, managing objects in Active Directory, and getting various information about AD computers, users, groups, etc. Any Windows administrator should know how to use AD as a graphical snap-in (usually These are ADUC – Active Directory Users & Computers) and RSAT-AD-PowerShell cmdlets for performing day-to-day Active Directory administration tasks. In this article, we'll take a look at how to install the Active Directory PowerShell module on Windows.

How to install Powershell Active Directory Module on Windows Server

On Windows Server 2016, 2019 and 2022, you can install AD Module for PowerShell from Server Manager: Add Roles and Features → Features → Remote Server Administration Tools → Role Administration Tools → AD DS and AD LDS Tools → Active Directory module for Windows PowerShell.

If you have already installed the Active Directory Domain Services role, this means that the Active Directory Powershell module is already activated and no additional action is required.

See also: Active Directory comprehensive guide, from installation and configuration to security auditing. Part 4: Install Active Directory Domain Services in Windows Server 2022

You can also install the module from the PowerShell console using the command:

Install-WindowsFeature -Name "RSAT-AD-PowerShell" -IncludeAllSubFeature

How to Install Active Directory PowerShell Module on Windows 11 and Windows 10 in command line

You can install the RSAT-AD-PowerShell module not only on Windows Server, but also on your workstations.

On Windows 11 or Windows 10, run this PowerShell command to install the Active Directory module:

Add-WindowsCapability -online -Name "Rsat.ActiveDirectory.DS-LDS.Tools"

The previous command must be executed in the command line with administrator rights.

Related article: PowerShell with administrator rights: how to run and verify

How to install Active Directory PowerShell module in Windows 11 in a GUI

To install the Active Directory PowerShell module in Windows 11 using a GUI, open “Settings” by pressing Win+i and select the “Apps” tab, then go to “Optional Features”.

Now select “View features” under “Add an optional feature”.

To install the Active Directory Remote Administration Tools, search for “RSAT: Active Directory Domain Services and Lightweight Directory Services Tools”, check the box and click “Next”,

then click “Install”.

Note: if, when searching for a particular component, you cannot find it, then, probably, this component is already installed.

To verify this, in the search bar under “Installed features” enter the name of the component you are looking for.

Also, remember that English and localized versions of Windows have different names for these components!

How to Install Active Directory PowerShell Module on Windows 10 in using a GUI

To install the Active Directory PowerShell module in the GUI, press Win+x, then select “Apps and Features” from the menu that opens.

Next, select “Optional Features”.

Now select “Add a feature”.

To install the Active Directory Remote Administration Tools, select “RSAT: Active Directory Domain Services and Lightweight Directory Services Tools” and click the “Install” button.

PowerShell with administrator rights: how to run and verify

How to run PowerShell as an administrator

Some commands and cmdlets require elevated privileges. Examples of actions that require administrator rights are service management (install, start, stop, uninstall) and package management (add and remove package providers, install and remove packages).

For example, the following cmdlet tries to add a new package provider:

Install-PackageProvider chocolatey

It will throw the following error:

Install-PackageProvider: Administrator rights are required to install packages in ''. Log on to the computer with an account that has Administrator rights, and then try again, or install in 'C:\Users\MiAl\AppData\Local\PackageManagement\ProviderAssemblies' by adding "-Scope CurrentUser" to your command. You can also try running the Windows PowerShell session with elevated rights (Run as Administrator).

To fix this error, you need to run PowerShell as an administrator.

How to run PowerShell as an administrator on Windows

Let's consider several ways.

1. Launch PowerShell with administrator rights via the Power user menu

Press Win+x and in the menu that opens, select “Windows Terminal (Admin)”:

If you have two versions of PowerShell installed on your OS (PowerShell 5 preinstalled with Windows, and PowerShell 7 installed manually), this will open PowerShell 5.

2. Run PowerShell as an administrator from the Start menu

To open PowerShell 7 as an administrator, click the Start menu and search for “PowerShell” or “PowerShell 7”, select “Run as Administrator”:

3. How to run Windows Terminal with administrator rights in Windows

By default, Windows Terminal uses PowerShell, so if you run Terminal with administrator rights, then Terminal will also be with elevated rights.

Remember that the terminal is not included in the standard set of Windows 10 programs and must be installed from the Microsoft Store. In Windows 11, this program is installed by default.

Go to the start menu and start typing “Terminal”:

If you do not see the “Run as administrator” item, then click the arrow to expand the entire list:

Click on “Run as administrator”.

4. How to run PowerShell as an administrator in the command line

If you already have a PowerShell console open with standard user rights, then directly from it you can start a new elevated PowerShell process:

Start-Process PowerShell -Verb RunAs

This command will launch PowerShell 5 or PowerShell 6, whichever is the default on your system. To run the latest version that you manually installed, i.e. PowerShell 7, run the command:

Start-Process pwsh -Verb RunAs

5. How to run PowerShell as an administrator on Linux

To run PowerShell as administrator on Linux, run the command with sudo:

sudo pwsh

How do I check if a PowerShell script or PowerShell terminal is running as administrator

If you need to run a PowerShell script as an administrator, you can check if the current process has powershell.exe or pwsh.exe elevated permissions right in your PS code.

In addition, sometimes you need to determine whether the terminal is running with elevated privileges or with the rights of a regular user.

How to determine if PowerShell terminal is running with administrator rights

First of all, pay attention to the command line prompt:

A PowerShell window opens with the current working directory in C:\windows\system32 and, accordingly, there is the following command line prompt:

PS C:\windows\system32>

If the PowerShell process has normal rights, then the user's folder is opened as the current working directory:

PS C:\Users\MiAl>

Things get more complicated if PowerShell is used through the Windows Terminal. Take a look at this screenshot, one of these terminals is open as an administrator, and the other as a regular user – they are no different.

It was a test of attentiveness – the name of the window with administrator rights contains the word “Administrator”.

When you need to find out if a given shell has administrator rights, run the following two commands in sequence:

$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

PowerShell console with administrator privileges will print True, console with normal privileges will print False:

By the way, the same method can be used in scripts as well.

How to check in a PowerShell script that it is running as administrator

The following PowerShell code can be used to test if the current script is running in “Run as Administrator” mode:

Write-Host "Checking elevated rights..."
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator")) {
	Write-Warning "Insufficient permissions for the script. Open PowerShell console as administrator and rerun this script."
	Break
}
else {
	Write-Host "The code is run as administrator - script can continue..." -ForegroundColor Green
}

Save the PowerShell code in check_process_elevation.ps1 and run it in the console without admin rights:

C:\PS\check_process_elevation.ps1

As you can see, a message appeared that you do not have administrator rights, so the PowerShell script was stopped.

Now run the script in an elevated PowerShell session. As you can see, the script detected that this PowerShell session is running as administrator.

Alternatively, you can request administrator rights directly from a PowerShell script. To do this, instead of the line:

	Write-Warning "Insufficient permissions for the script. Open PowerShell console as administrator and rerun this script."
	Break

use the following code:

Start-Process Powershell -ArgumentList $PSCommandPath -Verb RunAs

When you run the script without administrator rights, it will rerun in a new elevated PowerShell session and you will see a UAC elevation prompt. If you accept it, your PS1 script will run as administrator. (The path to the current PowerShell script file is passed using the $PSCommandPath environment variable.)

In PowerShell 4.0 or newer, it's even easier to check if your script is running as an administrator. To do this, use the -RunAsAdministrator directive.

#requires -version 4.0
#requires -RunAsAdministrator
Write-Host "PowerShell is running as administrator" -ForegroundColor Green

If the script does not run under administrator, the following error will appear:

C:\PS\check_process_elevation.ps1: The script 'check_process_elevation.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current PowerShell session is not running as Administrator. Start PowerShell by using the Run as Administrator option, and then try running the script again.

If you run the script on a PowerShell v2 machine, you receive the following error message:

Cannot process the “#requires” statement at line 2 because it is not in the correct format.
The “#requires” statement must be in one of the following formats:
“#requires -shellid <shellID>”
“#requires -version <major.minor>”
“#requires -pssnapin <psSnapInName> [-version ]”

To manage Active Directory, you may need a different task: check if the current user has domain administrator rights from a PowerShell script. Use the following code:

If(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole("Domain Admins"))
{
	# the user who ran this script has Domain Admins rights
}
Else
{
	# no Domain Admins rights
}

Demote Domain Controllers in Windows Server in PowerShell and GUI

This article shows you how to demote a domain controller in Windows Server. This method is applicable for Windows Server 2012 and later, up to Windows Server 2019 and Windows Server 2022.

You can undo a promotion to a domain controller in PowerShell as well as using the GUI configuration tools.

This article explains step by step how to uninstall AD DS using Server Manager or Windows PowerShell.

Error “The Active Directory domain controller needs to be demoted before the AD DS role can be removed”

You may need to cancel the addition of the Domain Controller role if you want to remove Active Directory components.

For example, when deleting Active Directory, you may encounter the following error:

Error
A prerequisite check for the AD-Domain-Services feature failed. 1. The Active Directory domain controller needs to be demoted before the AD DS role can be removed

To fix it, you need to start by turning off the domain controller on the server, below is shown how to do it.

Downgrading and Removing an Active Directory domain controller role Using PowerShell

To disable the Domain Controller role, use the Uninstall-ADDSDomainController cmdlet. And you can remove Active Directory and DNS server using the Uninstall-WindowsFeature (Remove-WindowsFeature) cmdlet. Let's consider their options:

ADDSDeployment and ServerManager Cmdlets Arguments (Arguments in bold are required. Arguments in italics can be specified using Windows PowerShell or the AD DS Configuration Wizard.)
Uninstall-ADDSDomainController

-SkipPreChecks

-LocalAdministratorPassword

-Confirm

-Credential

-DemoteOperationMasterRole

-DNSDelegationRemovalCredential

-Force

-ForceRemoval

-IgnoreLastDCInDomainMismatch

-IgnoreLastDNSServerForZone

-LastDomainControllerInDomain

-Norebootoncompletion

-RemoveApplicationPartitions

-RemoveDNSDelegation

-RetainDCMetadata

Uninstall-WindowsFeature/Remove-WindowsFeature

-Name

-IncludeManagementTools

-Restart

-Remove

-Force

-ComputerName

-Credential

-LogPath

-Vhd

Note: The -credential argument is only required if you are not already logged in as a member of the Enterprise Admins group (whose DC you are downgrading) or the Domain Admins group (whose DC you are downgrading). The -includemanagementtools argument is required only if you want to remove all AD DS management utilities.

The following command will downgrade the server from a domain controller to a regular server:

Uninstall-ADDSDomainController -DemoteOperationMasterRole:$true -IgnoreLastDnsServerForZone:$true -LastDomainControllerInDomain:$true -RemoveDnsDelegation:$true -RemoveApplicationPartitions:$true -IgnoreLastDCInDomainMismatch:$true -Force:$true

At runtime, you will be prompted for a password for the local administrator, which, after removing the Domain Controller, will become the primary account and replace the domain administrator.

You can specify the password directly in the command using the following option:

  • -localadministratorpassword (convertto-securestring "Password1" -asplaintext -force)

After executing the command, the computer will automatically reboot.

Use the following commands to remove Active Directory and DNS server:

Uninstall-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
Uninstall-WindowsFeature -Name DNS -IncludeManagementTools

The components (roles) were successfully removed, but a server restart is required for the changes to take effect:

Success Restart Needed Exit Code      Feature Result
------- -------------- ---------      --------------
True    Yes            SuccessRest... {Active Directory Domain Services, Group P...
WARNING: You must restart this server to finish the removal process.

Now let's look at removing roles and features through Server Manager.

Removing a Domain Controller in Server Manager

Press the “Windows” key on your keyboard and type “Server Manager” to search for the application, open it.

Click “Manage” → “Remove Roles and Features”.

Click “Next”.

Select a server and click “Next”.

Find the item “Active Directory Domain Services” and uncheck the checkbox, then click “Next”.

In the window that opens, click “Remove Feature”.

Since this server is a Domain Controller, it is not possible to uninstall Active Directory Domain Services until the promotion to Domain Controller is canceled. Therefore, an error occurs:

Validation Results
The validation process found problems on the server from which you want to remove features. The selected features cannot be removed from the selected server. Click OK to select different features.

Validation Results, Server
The Active Directory domain controller needs to be demoted before the AD DS role can be removed.

To start the process of removing the Domain Controller, click on “Demote this domain controller”.

Check the “Proceed with removal” checkbox and click “Next”.

Check the “Last domain controller in the domain” checkbox and click “Next”.

Check the boxes “Remove this DNS zone (this is the last DNS server that hosts the zone”, “Remove application partitions”, “Remove DNS delegation” and click “Next”.

Enter the password of the local administrator, under whose account you will be logged in after removing the domain controller and click “Next”.

Check the summarized information and click the “Demote” button.

Wait for the domain controller demotion process to complete.

The computer will then automatically restart.

After rebooting the server, go to Server Manager again. In it, click “Manage” → “Remove Roles and Features”.

Click “Next”.

Select a server and click “Next”.

Find the item “Active Directory Domain Services” and uncheck the checkbox, then click “Next”. In the window that opens, click “Remove Feature”.

Then find the item “DNS Server” and uncheck the checkbox, then click “Next”. In the window that opens, click “Remove Feature”.

After removing all more unnecessary features and roles, click “Next”.

On the next window, the check-boxes corresponding to the auxiliary functions and snap-in to be removed will already be cleared, click “Next”.

On the confirmation page, click “Remove”.

Now you can close the wizard window.

How to check PowerShell version in Windows 11

Finding your version of PowerShell will help you find out which PowerShell features you have access to. The PowerShell command lets you specify a version number, and we'll show you how.

How to find out the installed version of PowerShell

There is a PowerShell utility to find the version number, which is what we are going to use.

First, press Win+x and select “Windows Terminal”:

In the Windows Terminal window that opens, enter the following command and press Enter:

$PSVersionTable

PowerShell displays various numbers. Here, the first value "PSVersion" is your version of PowerShell.

You can now close the PowerShell window.

How to install the latest version of PowerShell

By default, all versions of Windows, even the latest Windows 11, provided with PowerShell 5, although the current version is PowerShell 7. To install it, see “How to install the latest PowerShell on Windows 11”.

How to check the built-in PowerShell version

If you installed PowerShell 6 or 7, you now have two versions at the same time on your system: PowerShell 5 and the latest. Windows Terminal can use any of these versions by default.

To find out your built-in PowerShell version, open the Start menu, search for “Windows PowerShell”, and click it in the search results.

In the PowerShell window that opens, enter the following command and press Enter:

$PSVersionTable

Or, no matter how you opened the command line, you can find out the versions with the following command sequences.

To check the built-in PowerShell version:

powershell
$PSVersionTable

To find out the version of PowerShell installed:

pwsh
$PSVersionTable

If the “pwsh” command is not found, then try “pwsh-preview”.

How to update the built-in version of PowerShell

Windows 10 updates the built-in PowerShell tool when installing system updates. This means that you should regularly update your computer to always use the latest version of PowerShell.

How to install the latest PowerShell on Windows 11

What's new in PowerShell 7

PowerShell 5.1 is installed by default in Windows 10 and Windows 11. In recent years, there has been an active development of new versions of PowerShell 7.*: 7.0, 7.1. PowerShell 7.2 beta is currently in development

You can view the PowerShell 6.* and PowerShell 7.* changelog on this page: https://github.com/PowerShell/PowerShell/tree/master/CHANGELOG

Despite the rapid development of the seventh version of PowerShell, the fifth version of PowerShell is still installed by default in the Windows operating system. Even the latest Windows 11 has PowerShell 5 installed.

PowerShell 7 is available for Windows, macOS, and Linux. We will show you how to install it on Windows 11.

Please note that PowerShell 7 is not currently a replacement for PowerShell 5, which means that when PowerShell 7 is installed, the fifth version will still be available on the system.

There are frequent updates for PowerShell 7, you can update to the latest versions of PowerShell 7 in the same ways that are shown in this article.

The latest version of PowerShell 7 can be downloaded in two ways - go to the releases page and find the PowerShell 7 installer; or use the script to download PowerShell 7 right in the command line.

Where to download PowerShell 7 (official site)

The first method we'll look at uses an .msi file to install PowerShell. MSI packages work almost identically to an EXE file and allow you to install a program using a graphical user interface. This is an installation method that only uses the required and key files. All you need to do is double click on the file to launch the installation wizard.

To download the package, launch your browser and go to the PowerShell Github Releases page. Scroll down to the Assets section and find the MSI file (PowerShell-*-win-x64.msi) there to download it.

Be sure to select the correct package for your version of Windows, x64 for 64-bit or x86 for 32-bit systems.

When prompted, select a download location and click Save to start downloading.

Once the download is complete, navigate to the folder where the file is located and double-click it to start the installation.

How to download PowerShell 7 from the command line

The PowerShell developers have also created a script that can be called directly from PowerShell. It is a one-line cmdlet that automatically downloads and runs the installation wizard. All you need to do is paste in the code snippet and hit the Enter key.

Start PowerShell and copy/paste the following cmdlet into the window:

iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"

Press Enter and PowerShell will run the command and start downloading.

If you are curious about what exactly the above command does, then the following notation may help you figure it out:

Invoke-Expression "& { $(Invoke-RestMethod https://aka.ms/install-powershell.ps1) } -UseMSI"

That is, at the first stage, the command downloads the file https://aka.ms/install-powershell.ps1 and then runs it.

PowerShell 7 Installer

When the installation wizard opens, click Next to install PowerShell 7.

On the next screen, select the folder where the PowerShell 7 files will be located and click Next:

Then you decide which additional features to include during installation. You can enable or disable the following five options:

  • Add PowerShell to Path Environment Variable: Adds PowerShell to the Windows Path environment variable and allows PowerShell to be invoked from any other shell or terminal.
  • Register Windows Event Logging Manifest: Adds PowerShell to the Windows Event Registration manifest and allows events to be logged from a PowerShell instance.
  • Enable PowerShell remoting: Enables the ability to remotely run commands on this system.
  • Add ‘Open here’ context menus to Explorer: Adds an option to the right-click context menu that opens a PowerShell instance in the folder you clicked.
  • Add ‘Run with PowerShell 7-preview’ context menus for PowerShell files: Adds an option to the right-click context menu that prompts PowerShell files to run a script using PowerShell 7.

Click “Next” after selecting all the additional features you want.

On this window, you can choose if you want PowerShell to be updated using Windows Update. You can still update PowerShell either manually or along with Windows updates.

Click “Next” after choosing the update options.

Click “Intall” to start installation. A UAC prompt will appear asking for administrator rights to install the package. Click “Yes” to continue.

When the installation wizard completes, click Finish to exit.

How to open PowerShell 7

Once the installation is complete, you can open PowerShell 7 in several ways.

If you selected the Add PowerShell to Path Environment Variable and Add ‘Open here’ Context Menus to Explorer options, you can enter

pwsh

or right-click any folder and select PowerShell 7 → Open here.

However, one of the easiest ways is to search for “pwsh”. Then press Enter or click on the PowerShell icon with the mouse. Here you can also run PowerShell 7 with Administrator rights.

To make sure you are using PowerShell 7, take a look at the window title:

To update the help, run the command:

Update-Help

If the previous command failed, then try updating the help like this:

Update-Help -UICulture en-US

How to make Terminal use PowerShell 7 by default

The default command line in Windows 11 is Terminal.

Terminal is a pretty and functional program, but even after installing PowerShell 7, it uses PowerShell 5 by default. This can be easily changed.

To do this, press Win+x and select “Windows Terminal”:

Click on the down arrow button to the right of the window names and select “Settings” from the menu:

In the drop-down menu “Default profile” select “PowerShell”, then click “Save”:

Terminal will now use the most recently installed version of Terminal by default.

If you want to switch to PowerShell 5, then enter at the command line:

powershell

Alternatively, select the appropriate option when opening a new tab:

How to shut down computers in PowerShell

Stop-Computer cmdlet

The Stop-Computer cmdlet shuts down the local or remote computer.

You can run Stop-Computer with additional options to specify authentication types and alternate credentials, and to force an immediate shutdown.

This cmdlet uses the Win32Shutdown method of the Win32_OperatingSystem WMI class.

The following two commands are identical and shutdown the local computer:

Stop-Computer
Stop-Computer -ComputerName localhost

The following example will shutdown a computer named Win-Server-Core that has an Administrator user with sufficient rights to shutdown the computer:

Stop-Computer -ComputerName Win-Server-Core -Credential Administrator

This command shuts down remote computers and the local computer.

Stop-Computer -ComputerName "Server01", "Server02", "localhost"

In the previous command, Stop-Computer uses the -ComputerName option to specify two remote computers and a local computer. Each of the listed computers will be turned off.

The following code shuts down remote computers as a background job:

$j = Stop-Computer -ComputerName "Server01", "Server02" &
$results = $j | Receive-Job
$results

In the previous example, Stop-Computer uses the -ComputerName option to specify two remote computers. The background operator “&” translates the command as a background job. The job objects are stored in the $j variable.

The job objects in the $j variable are piped to Receive-Job, which receives the job results. The objects are stored in the $results variable. The $results variable displays information about the job in the PowerShell console.

Shutting down the remote computer:

Stop-Computer -ComputerName "Server01" -WsmanAuthentication Kerberos

In the previous example, Stop-Computer uses the -ComputerName option to specify the remote computer. The -WsmanAuthentication option specifies using Kerberos to establish a remote connection.

Shutting down a computer in the domain:

$s = Get-Content -Path ./Domain01.txt
$c = Get-Credential -Credential Domain01\Admin01
Stop-Computer -ComputerName $s -Force -Credential $c

In the previous example, Get-Content uses the -Path option to read the contents of the Domain01.txt file in the current directory with a list of domain computers. The objects are stored in the $s variable.

Then Get-Credential uses the -Credential option to specify the credentials of the domain administrator. The credentials are stored in the $c variable.

Finally, Stop-Computer shuts down the computers specified in the list of computers in the -ComputerName option in the $s variable. The -Force option causes immediate shutdown. The -Credential option passes your credentials stored in the $c variable.

Error “Unable to initiate a system shutdown because the computer is being used by other users”

Running command

Stop-Computer -ComputerName Win-Server-Core -Credential Administrator

may fail with the error message:

Stop-Computer: Failed to stop the computer Win-Server-Core with the following error message: Unable to initiate a system shutdown because the computer is being used by other users

Its reason is that users are logged in to the computer and are using it.

To force shutdown, specify the -Force option:

Stop-Computer -ComputerName Win-Server-Core -Credential Administrator -Force

Shutting down the computer without PowerShell

Without PowerShell, you can shutdown your computer with the following command:

shutdown /s

You will be shown a warning and the computer will shut down after 30 seconds.

To shut down the computer immediately, run the command:

shutdown /s /t 0

You can add the /f option to the command, which means forcibly closing running applications without warning users. The /f parameter is implied if the /t parameter is set to a value greater than 0.

How to restart computers in PowerShell

Restart-Computer Cmdlet

The Restart-Computer cmdlet restarts the operating system on a local or remote computer.

The following command will reboot the local computer:

Restart-Computer

You can use Restart-Computer with various parameters to trigger restart operations, to specify authentication levels and alternate credentials, to restrict operations to be performed simultaneously, and to restart immediately.

Starting with Windows PowerShell 3.0, you can wait until the reboot is complete before running the next command. Specify the timeout and request interval and wait for certain services to be available on the rebooted computer. This feature makes it practical to use Restart-Computer in scripts and functions.

Restart-Computer only works on Windows computers and requires WinRM and WMI to shut down the system, including the local one.

Example of restarting multiple computers:

Restart-Computer -ComputerName Server01, Server02, localhost

The -ComputerName <String[]> option specifies a single computer name or an array of computer names separated by commas. Restart-Computer accepts ComputerName objects from a pipeline or variables.

Enter the NetBIOS name, IP address, or fully qualified domain name of the remote computer. To specify the local computer, enter the computer name, period “.” or “localhost”.

This parameter is independent of PowerShell remoting. You can use the -ComputerName parameter even if your computer is not configured to run remote commands.

If the -ComputerName parameter is not specified, Restart-Computer restarts the local computer.

If you are restarting a remote computer, you will most likely need the -Credential <PSCredential> option, which specifies a user account that has permission to perform this action. By default, this is the current user.

Enter a username, such as User01 or Domain01\User01, or enter the PSCredential object generated by the Get-Credential cmdlet. If you enter a username, you will be prompted for a password.

The credentials are stored in the PSCredential object (/dotnet/api/system.management.automation.pscredential) and the password is stored as SecureString (/dotnet/api/system.security.securestring).

The following example reboots computers whose names are obtained from a text file:

Get-Content -Path C:\Domain01.txt | Restart-Computer

Get-Content uses the -Path parameter to get a list of computer names from the Domain01.txt text file. Computer names are sent down the pipeline. Restart-Computer restarts every computer.

Forced restart of computers listed in the text file:

$Names = Get-Content -Path C:\Domain01.txt
$Creds = Get-Credential
Restart-Computer -ComputerName $Names -Credential $Creds -Force

Get-Content uses the -Path parameter to get a list of computer names from the Domain01.txt text file. Computer names are stored in the $Names variable. Get-Credential prompts you for a username and password and stores the values in the $Creds variable. Restart-Computer uses the -ComputerName and -Credential parameters with their variables. The -Force option causes each computer to restart immediately.

Restarting the remote computer and waiting for it to turn on to execute PowerShell:

Restart-Computer -ComputerName Server01 -Wait -For PowerShell -Timeout 300 -Delay 2

Restart-Computer uses the -ComputerName parameter to restart Server01. The -Wait parameter makes the command wait for the restart to complete. -For sets PowerShell to run commands on the remote computer. The -Timeout parameter sets a five minute wait. The -Delay parameter polls the remote computer every two seconds to determine if it has restarted.

Restarting your computer using WsmanAuthentication:

Restart-Computer -ComputerName Server01 -WsmanAuthentication Kerberos

Restart-Computer uses the -ComputerName parameter to restart the Server01 remote computer. The -WsmanAuthentication parameter specifies the Kerberos authentication method.

Error “Unable to initiate a system shutdown because the computer is being used by other users”

When restarting a remote computer, for example:

Restart-Computer -ComputerName Win-Server-Core -Credential Administrator

an error may occur

Restart-Computer: Failed to restart the computer Win-Server-Core with the following error message: System shutdown cannot be initiated because the computer is in use by other users.

This error occurs if any user is logged in to the remote computer, use the -Force option to force reboot:

Restart-Computer -ComputerName Win-Server-Core -Credential Administrator -Force

Restarting the computer without PowerShell

Without PowerShell, you can restart your computer with the following command:

shutdown /r

You will be shown a warning and the computer will restart after 30 seconds.

To restart your computer immediately, run the command:

shutdown /r /t 0

You can add the /f option to the command, which means forcibly closing running applications without warning users. The /f parameter is implied if the /t parameter is set to a value greater than 0.

How to configure the network interface to use a dynamic IP address (DHCP) in PowerShell

Note: all settings in this article must be done with administrator rights.

Dynamic Host Configuration Protocol (DHCP) allows the network adapter to obtain the correct network settings without manually configuring network interfaces.

To manage a network interface, you need to know its index. The list of interfaces and their indices can be obtained with the following command:

Get-NetIPAddress | Format-Table

Before activating DHCP on the network interface, you need to delete the IP address settings (if any).

Remove the static IP address:

Remove-NetIPAddress -InterfaceIndex INTERFACE_INDEX

Remove the default gateway:

Remove-NetRoute -InterfaceIndex INTERFACE_INDEX

For example:

Remove-NetIPAddress -InterfaceIndex 18
Remove-NetRoute -InterfaceIndex 18

Remove an IP address using a pipeline:

Get-NetIPAddress -IPAddress 192.168.0.1 | Remove-NetIPAddress

This command removes all of the IP addresses with the address 192.168.0.1.

To enable DHCP on the network interface, use a command of the form:

Set-NetIPInterface -InterfaceIndex INTERFACE_INDEX -Dhcp Enabled

For example:

Set-NetIPInterface -InterfaceIndex 18 -Dhcp Enabled

If you want to delete records about DNS servers so that DNS settings are also obtained automatically, then run the following command:

Set-DnsClientServerAddress -InterfaceIndex INTERFACE_INDEX -ResetServerAddresses

Please note that you can use DHCP and DNS server settings at the same time (specify the desired DNS servers for the network interface, which automatically receive an IP address and other network settings). To set the DNS server settings on the network interface with the specified index, use a command of the form:

Set-DnsClientServerAddress -InterfaceIndex INTERFACE_INDEX -ServerAddresses ("8.8.8.8","8.8.4.4")
Loading...
X