Table of Contents
Windows PowerShell is a new command-line shell designed especially for system administrators. Windows PowerShell includes an interactive prompt and a scripting environment that can be used independently or in combination
Unlike most command-line shells, which accept and return text, Windows PowerShell is built on top of the .NET Framework common language runtime (CLR) and the .NET Framework, and accepts and returns .NET Framework objects. This fundamental change in the environment brings entirely new tools and methods to the management and configuration of Windows.
Like many shells, Windows PowerShell gives you access to the file system on the computer. In addition, Windows PowerShell Providers enable you to access other data stores, such as the registry and the digital signature certificate stores, as easily as you access the file system.
Windows PowerShell Cmdlets
A cmdlet (pronounced as “command-let”) is a single-feature command that manipulates objects in Windows PowerShell. You can recognize cmdlets by their name format which is verb and noun separated by a dash (-), such as Get-Help, Get-Process, and Start-Service.
In traditional shells, the commands are executable programs that range from the very simple (such as ren.exe) to the very complex (such as netsh.exe).
In Windows PowerShell, most cmdlets are very simple, and they are designed to be used in combination with other cmdlets.
For example:
- The Get- cmdlets only retrieve data.
- The Set- cmdlets only change data.
- The Format- cmdlets only format data.
- The Out- cmdlets only direct the output to a specified destination.
Each cmdlet has a help file that you can access by typing:
Get-Help Get-Mailbox -Detailed
The detailed view of the cmdlet help file includes a description of the cmdlet, the command syntax, descriptions of the parameters, and an example that demonstrate use of the cmdlet.
Windows Commands and Utilities
You can run Windows command-line programs in Windows PowerShell, and you can start Windows programs that have a graphical user interface, such as Notepad and Calculator, at the Windows Powershell prompt. You can also capture the text that Windows programs generate and use that text in Windows PowerShell.
For example, the following commands use ipconfig and net commands.
PS C:\Users\admin> ipconfig
Windows IP Configuration
Ethernet adapter Ethernet:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Wireless LAN adapter Wi-Fi:
Connection-specific DNS Suffix . :
IPv4 Address. . . . . . . . . . . : 192.168.1.163
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.1.1
PS C:\Users\admin> net localgroup administrators
Alias name administrators
Comment Administrators have complete and unrestricted access to the computer/domain
Members
-------------------------------------------------------------------------------
admin
Administrator
The command completed successfully.
You can even use Windows PowerShell cmdlets, like Select-String, to manipulate the text that Windows programs return.
For example, the following command uses a pipeline operator to send the results of an ipconfig command to the Windows PowerShell Select-String cmdlet, which searches for text in strings. In this case, you use Select-String to find the pattern IPv4 in the ipconfig output.
PS C:\> ipconfig | Select-String -pattern IPv4
IPv4 Address. . . . . . . . . . . : 192.168.56.1
IPv4 Address. . . . . . . . . . . : 192.168.1.163
When a Windows command or tool has parameters, such as the -r (restart) parameter of shutdown command shutdown -r, Windows PowerShell passes the parameters to the tool without interpreting them.
Processing Objects in PowerShell
Although you might not realize it at first, when you work in Windows PowerShell, you are working with .NET Framework objects. As you gain experience, the power of object processing becomes more evident, and you’ll find yourself using the objects and even thinking in objects.
Technically, a .NET Framework object is an instance of a .NET Framework class that consists of data and the operations associated with that data. But you can think of an object as a data entity that has properties, which are like characteristics, and methods, which are actions that you can perform on the object.
For example:
- When you get a service in Windows PowerShell, you are really getting an object that represents the service.
- When you view information about a service, you are viewing the properties of its service object.
- And, when you start a service, that is, when you change the Status property of the service to “Started,” you are using a method of the service object.
All objects of the same type have the same properties and methods, but each instance of an object can have different values for the properties. For example, every service object has a Name and Status property. However, each service can have a different name and a different status.
When you’re ready, it’s easy to learn about the objects. To find out what type of object a cmdlet is getting, use a pipeline operator (|) to send the results of a Get command to the Get-Member cmdlet. For example, the following command sends the objects retrieved by a Get-Mailbox command to Get-Member.
PS C:\> Get-Mailbox | Get-Member
TypeName: Deserialized.Microsoft.Exchange.Data.Directory.Management.Mailbox
Name MemberType Definition
---- ---------- ----------
GetType Method type GetType()
ToString Method string ToString(), string ToString(string format, System.IForma...
AcceptMessagesOnlyFrom Property Deserialized.Microsoft.Exchange.Data.Directory.ADMultiValuedPro...
AcceptMessagesOnlyFromDLMembers Property Deserialized.Microsoft.Exchange.Data.Directory.ADMultiValuedPro...
AcceptMessagesOnlyFromSendersOrMembers Property Deserialized.Microsoft.Exchange.Data.Directory.ADMultiValuedPro...
AccountDisabled Property System.Boolean {get;set;}
AddressBookPolicy Property {get;set;}
AddressListMembership Property Deserialized.Microsoft.Exchange.Data.Directory.ADMultiValuedPro...
AdminDisplayVersion Property System.String {get;set;}
AdministrativeUnits Property Deserialized.Microsoft.Exchange.Data.Directory.ADMultiValuedPro...
AggregatedMailboxGuids Property Deserialized.Microsoft.Exchange.Data.MultiValuedProperty`1[[Sys...
Alias Property System.String {get;set;}
AntispamBypassEnabled Property System.Boolean {get;set;}
ArbitrationMailbox Property {get;set;}
To find the values of all of the properties of a particular object, use a pipeline operator (|) to send the results of a Get command to a Format-List or Format-Table cmdlet. Use the Property parameter of the format cmdlets with a value of all (*). For example, to find all of the properties of a mailbox, type:
PS C:\> Get-Mailbox [email protected] | Format-List -Property *
Database : APCPR03DG415-db092
DatabaseGuid : 43928945-d7cf-4294-bae9-a987e5ebf7ce
MailboxProvisioningConstraint :
IsMonitoringMailbox : False
MailboxRegion :
MailboxRegionLastUpdateTime :
MailboxRegionSuffix : None
MessageRecallProcessingEnabled : True
MessageCopyForSentAsEnabled : False
MessageCopyForSendOnBehalfEnabled : False
...
Remember that Windows PowerShell is not case sensitive. It means cmdlet Get-Service and get-service will return same result. But you will see in many blogs that cmdlets are accented such has first letter is always uppercase. This is because Windows PowerShell uses TAB key for auto-completion and TAB key automatically changes the first letter to uppercase. If you type get-mai and press TAB key, you will see that the cmdlet name changes to Get-Mailbox.
Object Pipelines
One major advantage of using objects is that it makes much easier to pipeline commands. Pipeline means to pass the output of one cmdlet to another cmdlet as input. In a traditional command-line environment, you would have to manipulate text to convert output from one format to another and to remove titles and column headings.
Windows PowerShell provides a new architecture that is based on objects, rather than text. The cmdlet that receives an object can act directly on its properties and methods without any conversion or manipulation.
Users can refer to properties and methods of the object by name, rather than calculating the position of the data in the output.
In the following example, the result of Get-Mailbox command is passed to a findstr command. The pipeline operator (|) sends the result of the command on its left to the command on its right. In Windows PowerShell, you do not need to manipulate strings or calculate data offsets.
PS C:\> Get-Mailbox | findstr "admin"
admin admin APCPR03DG415-db092
it-admin it-admin APCPR03DG425-db066
PowerShell Execution Policy
PowerShell execution policy lets you determine the conditions under which PowerShell loads configuration files and runs scripts. You can set an execution policy for the:
- local computer
- urrent user
- or for a particular session
You can also use a Group Policy setting to set execution policy for computers and users.
Execution policies for the local computer and current user are stored in the registry. You do not need to set execution policies in your PowerShell profile.
The execution policy for a particular session is stored only in memory and is lost when the session is closed.
The execution policy is not a security system that restricts user actions. For example, users can easily circumvent a policy by typing the script contents at the command line when they cannot run a script. Instead, the execution policy helps users to set basic rules and prevents them from violating them unintentionally.
To check the current execution policy on system, use Get-ExecutionPolicy cmdlet as shown below:
PS C:\> Get-ExecutionPolicy
Restricted
Restricted is default execution policy on Windows client OSes (e.g., Windows 10/11) and RemoteSigned is the default execution policy on Windows server OSes (e.g., Server 2019/2022).
Modify execution policy
To change the PowerShell execution policy on your computer, use the Set-ExecutionPolicy cmdlet. To run this cmdlet, you must have administrator privileges on computer. The syntax of command is as shown below:
Set-ExecutionPolicy <ExecutionPolicy> [-Scope] [-Force]
<ExecutionPolicy> specifies the new execution policy. Valid values are:
- Restricted: Does not load configuration files or run scripts. “Restricted” is the default execution policy. Prevents running of all script files, including formatting and configuration files (.ps1xml), module script files (.psm1), and Windows PowerShell profiles (.ps1).
- AllSigned: Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on the local computer. Learn how to sign a PowerShell script.
- RemoteSigned: Requires that all scripts and configuration files downloaded from the Internet be signed by a trusted publisher.
- Unrestricted: Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet, you are prompted for permission before it runs.
- Bypass: Nothing is blocked and there are no warnings or prompts.
- Undefined: Removes the currently assigned execution policy from the current scope. This parameter will not remove an execution policy that is set in a Group Policy scope.
-Scope specifies the scope of the execution policy. This is an optional parameter, if omitted the ExecutionPolicy is set by default for local machine. However, you can use other valid values for scope parameter. The valid values are:
- Process: The execution policy affects only the current Windows PowerShell process or session.
- CurrentUser: The execution policy affects only the current user.
- LocalMachine: The execution policy affects all users of the computer.
-Force is also an optional parameter which suppresses all prompts or Warnings. By default, Set-ExecutionPolicy displays a warning whenever you change the execution policy.
However, there are other optional parameters which can be used with Set-ExecutionPolicy cmdlet, but they are not usually used. You can see complete list of parameters and description using Get-Help command.
PS C:\Users\admin> Get-Help Set-ExecutionPolicy -Detailed
NAME
Set-ExecutionPolicy
SYNTAX
Set-ExecutionPolicy [-ExecutionPolicy] {Unrestricted | RemoteSigned | AllSigned | Restricted | Default | Bypass |
Undefined} [[-Scope] {Process | CurrentUser | LocalMachine | UserPolicy | MachinePolicy}] [-Force] [-WhatIf]
[-Confirm] [<CommonParameters>]
PARAMETERS
-Confirm
-ExecutionPolicy <ExecutionPolicy>
-Force
-Scope <ExecutionPolicyScope>
-WhatIf
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug,
ErrorAction, ErrorVariable, WarningAction, WarningVariable,
OutBuffer, PipelineVariable, and OutVariable. For more information, see
about_CommonParameters (https:/go.microsoft.com/fwlink/?LinkID=113216).
- The change done using Set-ExecutionPolicy cmdlet is effective immediately; you do not need to restart Windows PowerShell.
- If you set the execution policy for the local computer (the default) or the current user, the change is saved in the registry and remains effective until you change it again.
- If you set the execution policy for the current process, it is not saved in the registry. It is retained until the current process and any child processes are closed.
Set execution policy for a single session
You might often need to execute an unsigned script that does not comply with your current execution policy. You can easily do this by bypassing the execution policy for a single PowerShell process. To do this, use the following command:
Set-ExecutionPolicy Bypass -Scope Process
The above command does not change your machine’s execution policy permanently but for current PowerShell process only. After running this command, you can run any unsigned script in current PowerShell session until it is closed.
Bypass execution policy for a single script
Sometimes, you might want to execute a particular unsigned PowerShell script without modifying the machine’s execution policy. To achieve this, you can launch PowerShell process with -ExecutionPolicy Bypass option as shown in the following command directly in Run dialog:
powershell.exe -ExecutionPolicy Bypass .\your_script.ps1
The above command will launch a PowerShell process with execution policy set to Bypass mode, thus allowing an unsigned script to execute without any problem. This technique is now being exploited by attackers to run malicious PowerShell scripts.
Set execution policy via group policy
If you often need to change the execution policy on computers in your Active Directory domain to allow unsigned scripts, you may want to apply this setting centrally via a Group Policy Object (GPO).
The Set-ExecutionPolicy command allows you to pass the policy values for PowerShell’s operation level. For scripts you write yourself, in most situations, administrators choose the Unrestricted policy.
The Group Policy configuration in Windows Server allows a GPO to be set to configure the PowerShell operation level centrally. Within Group Policy, navigate to:
Computer Configuration | Administrative Templates | Windows Components | Windows PowerShell
And configure the Turn on Script Execution setting as shown in Figure below:
The Disabled option will prevent PowerShell scripts from being run and enforced via a GPO. If the GPO value is set, the computer accounts do not have the ability to change their local execution policy. The below Figure shows this behavior, even run as a Domain Administrator.
There are a number of considerations for this type of configuration around script security. The best practice will depend on the security policy of the systems involved. Applying the setting that enables PowerShell scripts to a GPO that corresponds to relevant systems is a practice that would fit most situations.