Tag: PowerShell

ImageMagick error on Windows: “magick: unable to open image ”test’: No such file or directory @ error/blob.c/OpenBlob/3565. magick: no decode delegate for this image format `’ @ error/constitute.c/ReadImage/741.” (SOLVED)

If in Windows 11 open CMD:

cmd

And then run the command:

magick '.\Для теста.jpg' test.png

An error will be received that there is no such file or directory:

magick: unable to open image ''.\╨Ф╨╗╤П': No such file or directory @ error/blob.c/OpenBlob/3565.
magick: no decode delegate for this image format `' @ error/constitute.c/ReadImage/741.

You can see that non-Latin characters are used in the file name, so you might think that this is the problem – that is, the “magick” program does not support alphabets other than English.

But if you try to rename the file and run the following command:

magick 'test file.jpg' new.png

Then the same error will be received again:

magick: unable to open image ''test': No such file or directory @ error/blob.c/OpenBlob/3565.
magick: no decode delegate for this image format `' @ error/constitute.c/ReadImage/741.

How to fix “magick: unable to open image ''test': No such file or directory @ error/blob.c/OpenBlob/3565. magick: no decode delegate for this image format `' @ error/constitute.c/ReadImage/741.”

1. Use double quotes instead of single quotes

If the filename is enclosed in double quotes instead of single quotes, then the command works correctly:

magick ".\Для теста.jpg" test.png

That is, try putting the filename in double quotes. If the problem persists, then it is related to the encoding of the file name.

2. Use PowerShell instead of CMD

In Windows 11 and Windows 10, the default command prompt is PowerShell, not CMD.

If your Windows uses CMD by default, then either set it to use PowerShell in the settings, or run one of the following commands at the command prompt:

powershell
pwsh

In Windows 11 + Windows Terminal Preview + PowerShell 7 command

magick '.\Для теста.jpg' test.png

works without errors.

See also: ImageMagick guide: installing, using, and troubleshooting

Error “The ‘<‘ operator is reserved for future use.” (SOLVED)

Analog “<” for PowerShell

On Linux, you can use the following construct:

COMMAND1 < FILE1

In this case, COMMAND1 will be executed with FILE1 as the input source instead of the keyboard, which is the normal standard input source.

The “<” operator corresponds to the use of “|” to be passed to standard input. For example, the following commands are identical:

COMMAND1 < FILE1
cat FILE1 | COMMAND1

Trying to use this construct in PowerShell throws an error.

For example command

mysql -uroot < C:\Users\MiAl\Downloads\all-databases.sql

ends with the following message:

ParserError:
Line |
   1 |  mysql -uroot < C:\Users\MiAl\Downloads\all-databases.sql
     |               ~
     | The '<' operator is reserved for future use.

Similar error in PowerShell 5:

string:1 character:14
+ mysql -uroot < C:\Users\MiAl\Downloads\all-databases.sql
+              ~
The '<' operator is reserved for future use.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : RedirectionNotSupported

Instead of syntax

COMMAND1 < FILE1

you need to use the following structure:

Get-Content FILE1 | COMMAND1

The Get-Content cmdlet will read the contents of FILE1. Symbol “|” (pipe, conveyor) means to pass the content to COMMAND1.

Thus, instead of

mysql -uroot < C:\Users\MiAl\Downloads\all-databases.sql

you need to use the following command:

Get-Content C:\Users\MiAl\Downloads\all-databases.sql | .\mysql -uroot

“./program < input.txt > output.txt” alternative for PowerShell

Consider the construction

./program < input.txt > output.txt

It means that the contents of the input.txt file are passed to the standard input of the “program” command, and the result of program execution is redirected to the output.txt file. But the above command will not work.

An analogue of the considered construction, which will work in PowerShell, is the following command:

Get-Content INPUT.txt | ./program > output.txt

Or you can use the PowerShell style variant:

Get-Content INPUT.txt | ./program | Out-File output.txt

mysqldump in PowerShell corrupts non-Latin characters when exporting database (SOLVED)

mysqldump is a MySQL utility for creating database and table backups. Unlike phpMyAdmin, which, although it offers a web interface, is a slower tool due to the limitations of intermediates such as PHP and Apache, mysqldump is a much more efficient tool without limitations for backing up very large data.

But on Windows, mysqldump has some nuances. Due to the peculiarities of PowerShell for working with encodings, all non-Latin characters can be corrupted in exported databases. This issue is not seen in CMD, but recent versions of Windows use PowerShell by default, so the issue in question affects all users who run mysqldump to back up databases in Windows.

The following command, executed in PowerShell 7:

.\mysqldump.exe -u root --all-databases > all-databases_ps7.sql

Creates a UTF-8 encoded all-databases_ps7.sql file into which all MySQL databases will be exported using mysqldump (for backup purposes). But in these databases all non-Latin characters will be irretrievably corrupted!

That is, instead of Cyrillic, it will be something like this:

'╨Р╤А╨▒╨╕╤В╤А╨░╨╢╨╜╤Л╨╣ ╨┐╤А╨╛╤Ж╨╡╤Б╤Б: ╤Г╤З╨╡╨▒╨╜╨╕╨║ / ╨Ъ.╨Ь. ╨Р╤А╤Б╨╗╨░╨╜╨╛╨▓, ╨Ф.╨е. ╨Т╨░╨╗╨╡╨╡╨▓, ╨а.╨Э. ╨У╨╕╨╝╨░╨╖╨

To avoid this problem, use mysqldump with the --result-file option. The following command will save the database in the correct encoding:

.\mysqldump.exe -u root --all-databases --result-file=all-databases.sql

You can also use the following two-command construct to fix the encoding problem:

[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding("UTF-8")
.\mysqldump.exe -u root --all-databases > all-databases.sql

Output encoding issues in PowerShell and third-party utilities running in PowerShell (SOLVED)

What encoding is used in PowerShell by default. How to change the default output encoding to UTF-8 in PowerShell

If you run the following command in PowerShell 5:

"Testing" > test.file

And check the encoding in the newly created test.file, it turns out that it is UTF-16LE.

If you run the following command in PowerShell 7:

"Testing" > test.file

And check the encoding in the newly created test.file, it turns out that it is UTF-8.

The following command, executed in PowerShell 5:

.\mysqldump.exe -u root --all-databases > all-databases_ps5.sql

Creates a UTF-16LE encoded all-databases_ps5.sql file into which all MySQL databases will be exported using mysqldump (for backup purposes). In these databases, ALL non-Latin characters will be irretrievably corrupted!

That is, instead of Cyrillic, it will be something like this:

'╨Р╤А╨▒╨╕╤В╤А╨░╨╢╨╜╤Л╨╣ ╨┐╤А╨╛╤Ж╨╡╤Б╤Б: ╤Г╤З╨╡╨▒╨╜╨╕╨║ / ╨Ъ.╨Ь. ╨Р╤А╤Б╨╗╨░╨╜╨╛╨▓, ╨Ф.╨е. ╨Т╨░╨╗╨╡╨╡╨▓, ╨а.╨Э. ╨У╨╕╨╝╨░╨╖╨

The following command, executed in PowerShell 7:

.\mysqldump.exe -u root --all-databases > all-databases_ps7.sql

Creates a UTF-8 encoded all-databases_ps7.sql file into which all MySQL databases will be exported using mysqldump (for backup purposes). But in these databases, ALL non-Latin characters will be irretrievably corrupted AGAIN!

That is, it would seem that the default encoding has changed to UTF-8, but the problem with completely corrupted database backups has not gone away.

How to save output from third-party programs in UTF-8 encoding in PowerShell

The above behavior, which corrupts the output of commands in PowerShell, is not acceptable. Let's look at how to ensure that output in PowerShell is saved in UTF-8 encoding.

How to save PowerShell output in UTF-8 encoding, use the Out-File cmdlet

Consider the following command:

.\mysqldump.exe -u root --all-databases > all-databases.sql

As already shown above, it corrupts non-Latin characters due to incorrect encoding.

In some sources, as a solution to the problem, it is recommended to replace the “>” character with “Out-File”, and also specify the encoding using the “-Encoding UTF8” option. That is, use the following command:

.\mysqldump.exe -u root --all-databases | Out-File -Encoding UTF8 all-databases_fixed.sql

In fact, both in PowerShell 7 and in PowerShell 5, this command changes little. First, the command is analogous to the output redirection symbol “>”. Secondly, by default, the Out-File cmdlet uses UTF-8 encoding, that is, it is not necessary to specify it specifically.

But the most important thing is that despite the fact that the data is saved to a file with UTF-8 encoding (in the previous command, this is the all-databases_fixed.sql file), non-Latin characters in this file are still corrupted! The thing is that the Out-File cmdlet initially processes the received data in the wrong encoding. Therefore, it no longer matters how exactly Out-File saves the data – the data is corrupted already at the time of receipt in this cmdlet.

The problem was solved by explicitly specifying the encoding for the received data:

[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding("UTF-8")

The subsequent run of the command saved all the data in the correct encoding:

.\mysqldump.exe -u root --all-databases | Out-File -Encoding UTF8 all-databases_fixed.sql

This method works equally well in PowerShell 7 and PowerShell 5.

By the way, the original command using this method also saves the data in the correct encoding:

[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding("UTF-8")
.\mysqldump.exe -u root --all-databases > all-databases.sql

Saving output by third-party utilities

In all previous commands, we redirected the output of the mysqldump utility to a file, or to the Out-File cmdlet. But the mysqldump utility has a --result-file option after which you can specify a filename to output. That is, as a result of using this option, you do not need to use output redirection or PowerShell cmdlets.

The following command will save the database in the correct encoding:

.\mysqldump.exe -u root --all-databases --result-file=all-databases.sql

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.

Loading...
X