This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
This chapter focuses on finding and launching PowerShell and solving the initial pain points thatnew users experience with PowerShell. Follow along and walk through the examples in this chapter onyour lab environment computer.
Windows PowerShell is an easy-to-use command-line shell and scripting environment for automatingadministrative tasks of Windows-based systems. Windows PowerShell is preinstalled on all modernversions of the Windows operating system.
The easiest way to find PowerShell on Windows 11 is to typePowerShell
into the search bar, asshown in Figure 1-1. Notice that there are four different shortcuts for Windows PowerShell.
Windows PowerShell shortcuts on a 64-bit version of Windows:
On a 64-bit version of Windows, you have a 64-bit version of the Windows PowerShell console and theWindows PowerShell Integrated Scripting Environment (ISE) and a 32-bit version of each one, asindicated by the (x86) suffix on the shortcuts.
Note
Windows 11 only ships as a 64-bit operating system. There is no 32-bit version of Windows 11.However, Windows 11 includes 32-bit versions of Windows PowerShell and the Windows PowerShell ISE.
You only have two shortcuts if you're running an older 32-bit version of Windows. Those shortcutsdon't have the (x86) suffix but are 32-bit versions.
I recommend using the 64-bit version of Windows PowerShell if you're running a 64-bit operatingsystem unless you have a specific reason for using the 32-bit version.
Depending on what version of Windows 11 you're running, Windows PowerShell might open inWindows Terminal.
Microsoft no longer updates the PowerShell ISE. The ISE only works with Windows PowerShell 5.1.Visual Studio Code (VS Code) with thePowerShell extension works with bothversions of PowerShell. VS Code and the PowerShell extension don't ship in Windows. Install VS Codeand the extension on the computer where you create PowerShell scripts. You don't need to installthem on all the computers where you run PowerShell.
I use three different Active Directory user accounts in the production environments I support. Imirrored those accounts in the lab environment used in this book. I sign into my Windows 11 computeras a domain user without domain or local administrator rights.
Launch the PowerShell console by clicking theWindows PowerShell shortcut, as shown in Figure1-1. Notice that the title bar of the console saysWindows PowerShell, as shown in Figure 1-2.
Some commands run fine when you run PowerShell as an ordinary user. However, PowerShell doesn'tparticipate inUser Access Control (UAC). That means it's unable to prompt for elevation fortasks that require the approval of an administrator.
Note
UAC is a Windows security feature that helps prevent malicious code from running with elevatedprivileges.
When signed on as an ordinary user, PowerShell returns an error when you run a command that requireselevation. For example, stopping a Windows service:
Stop-Service -Name W32Time
Stop-Service : Service 'Windows Time (W32Time)' cannot be stopped due tothe following error: Cannot open W32Time service on computer '.'.At line:1 char:1+ Stop-Service -Name W32Time+ ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (System.ServiceProcess.ServiceCon troller:ServiceController) [Stop-Service], ServiceCommandException + FullyQualifiedErrorId : CouldNotStopService,Microsoft.PowerShell.Comm ands.StopServiceCommand
The solution is to run PowerShell elevated as a user who is a local administrator. That's how Iconfigured my second domain user account. Following the principle of least privilege, this accountshouldn't be a domain administrator or have any elevated privileges in the domain.
To start PowerShell with elevated rights, right-click theWindows PowerShell shortcut and selectRun as administrator, as shown in Figure 1-3.
Windows prompts you for credentials because you logged into Windows as an ordinary user. Enter thecredentials of your domain user who is a local administrator, as shown in Figure 1-4.
Notice that the title bar of the elevated console windows saysAdministrator: WindowsPowerShell, as shown in Figure 1-5.
Now that you're running PowerShell elevated as an administrator, UAC is no longer a problem when yourun a command that requires elevation.
Important
You should only run PowerShell elevated as an administrator when absolutely necessary.
When you target remote computers, there's no need to run PowerShell elevated. Running PowerShellelevated only affects commands that run against your local computer.
You can simplify finding and launching PowerShell. Pin the PowerShell or Windows Terminal shortcutto your taskbar. Search for PowerShell again, except this time right-click on it and selectPin totaskbar as shown in Figure 1-6.
Important
The original version of this book, published in 2017, recommended pinning a shortcut to thetaskbar to launch an elevated instance automatically every time you start PowerShell. However, dueto potential security concerns, I no longer recommend it. Any applications you launch from anelevated instance of PowerShell also bypass UAC and run elevated. For example, if you launch a webbrowser from an elevated instance of PowerShell, any website you visit containing malicious codealso runs elevated.
When you need to run PowerShell with elevated permissions, right-click the PowerShell shortcutpinned to your taskbar while pressingShift. SelectRun as administrator, as shown inFigure 1-7.
There are automatic variables in PowerShell that store state information. One of these variables is$PSVersionTable
, which contains version information about your PowerShell session.
$PSVersionTable
Name Value---- -----PSVersion 5.1.22621.2428PSEdition DesktopPSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}BuildVersion 10.0.22621.2428CLRVersion 4.0.30319.42000WSManStackVersion 3.0PSRemotingProtocolVersion 2.3SerializationVersion 1.1.0.1
If you're running a version of Windows PowerShell older than 5.1, you should update your version ofWindows. Windows PowerShell 5.1 is preinstalled on the currently supported versions of Windows.
PowerShell version 7 isn't a replacement for Windows PowerShell 5.1; it installs side-by-side withWindows PowerShell. Windows PowerShell version 5.1 and PowerShell version 7 are two differentproducts. For more information about the differences between Windows PowerShell version 5.1 andPowerShell version 7, seeMigrating from Windows PowerShell 5.1 to PowerShell 7.
Tip
PowerShell version 6, formerly known as PowerShell Core, is no longer supported.
PowerShell execution policy controls the conditions under which you can run PowerShell scripts. Theexecution policy in PowerShell is a safety feature designed to help prevent the unintentionalexecution of malicious scripts. However, it's not a security boundary because it can't stopdetermined users from deliberately running scripts. A determined user can bypass the executionpolicy in PowerShell.
You can set an execution policy for the local computer, current user, or a PowerShell session. Youcan also set execution policies for users and computers with Group Policy.
The following table shows the default execution policy for current Windows operating systems.
Windows Operating System Version | Default Execution Policy |
---|---|
Windows Server 2022 | Remote Signed |
Windows Server 2019 | Remote Signed |
Windows Server 2016 | Remote Signed |
Windows 11 | Restricted |
Windows 10 | Restricted |
Regardless of the execution policy setting, you can run any PowerShell command interactively. Theexecution policy only affects commands running in a script. Use theGet-ExecutionPolicy
cmdlet todetermine the current execution policy setting.
Check the execution policy setting on your computer.
Get-ExecutionPolicy
Restricted
List the execution policy settings for all scopes.
Get-ExecutionPolicy -List
Scope ExecutionPolicy ----- ---------------MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser Undefined LocalMachine Undefined
All Windows client operating systems have the default execution policy setting ofRestricted
. Youcan't run PowerShell scripts using theRestricted
execution policy setting. To test the executionpolicy, save the following code as a.ps1
file namedGet-TimeService.ps1
.
Tip
A PowerShell script is a plaintext file that contains the commands you want to run. PowerShellscript files use the.ps1
file extension. To create a PowerShell script, use a code editor likeVisual Studio Code (VS Code) or any text editor such as Notepad.
When you run the following command interactively, it completes without error.
Get-Service -Name W32Time
However, PowerShell returns an error when you run the same command from a script.
.\Get-TimeService.ps1
.\Get-TimeService.ps1 : File C:\tmp\Get-TimeService.ps1 cannot be loadedbecause running scripts is disabled on this system. For more information,see about_Execution_Policies athttps:/go.microsoft.com/fwlink/?LinkID=135170.At line:1 char:1+ .\Get-TimeService.ps1+ ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess
When you run a command in PowerShell that generates an error, read the error message before retryingthe command. Notice the error message tells you why the command failed:
... running scripts is disabled on this system.
To enable the execution of scripts, change the execution policy with theSet-ExecutionPolicy
cmdlet.LocalMachine
is the default scope when you don't specify theScope parameter. You mustrun PowerShell elevated as an administrator to change the execution policy for the local machine.Unless you're signing your scripts, I recommend using theRemoteSigned
execution policy.RemoteSigned
prevents you from running downloaded scripts that aren't signed by a trustedpublisher.
Before you change the execution policy, read theabout_Execution_Policies helparticle to understand the security implications.
Change the execution policy setting on your computer toRemoteSigned
.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
If you have successfully changed the execution policy, PowerShell displays the following warning:
Execution Policy ChangeThe execution policy helps protect you from scripts that you do not trust.Changing the execution policy might expose you to the security risksdescribed in the about_Execution_Policies help topic athttps:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change theexecution policy?[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help(default is "N"):y
If you're not running PowerShell elevated as an administrator, PowerShell returns the followingerror message:
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. Tochange the execution policy for the default (LocalMachine) scope, startWindows PowerShell with the "Run as administrator" option. To change theexecution policy for the current user, run "Set-ExecutionPolicy -ScopeCurrentUser".At line:1 char:1+ Set-ExecutionPolicy -ExecutionPolicy RemoteSigned+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft. PowerShell.Commands.SetExecutionPolicyCommand
It's also possible to change the execution policy for the current user without requiring you to runPowerShell elevated as an administrator. This step is unnecessary if you successfully set theexecution policy for the local machine toRemoteSigned
.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
With the execution policy set toRemoteSigned
, theGet-TimeService.ps1
script runs successfully.
.\Get-TimeService.ps1
Status Name DisplayName------ ---- -----------Running W32Time Windows Time
In this chapter, you learned where to find and how to launch PowerShell. You also learned how todetermine the version of PowerShell and the purpose of execution policies.
To learn more about the concepts covered in this chapter, read the following PowerShell helparticles.
In the next chapter, you'll learn about the discoverability of commands in PowerShell. You'll alsolearn how to download PowerShell's help files so you can view the help in your PowerShell session.
Was this page helpful?
Was this page helpful?