Шпаргалка по командам windows power shell

Morsi Masmoudi

In this article, we will explore the main differences between Azure CLI and Azure PowerShell. We’ll examine their unique features, use cases, and benefits.

Table of contents

  1. What is the difference between Azure CLI and Azure PowerShell?
  2. Why should you consider using Azure CLI, Azure PowerShell (or both)
  3. Using Azure CLI and Azure Powershell from Azure Portal
  4. Using Azure Powershell From your computer
  5. PowerShell Reference commands

5.1 Accounts and Subscriptions

5.2 Resource Groups

5.5 Deploy and Manage Virtual Machines

5.7 Azure Active Directory Commands

What is the difference between Azure CLI and Azure PowerShell?

Azure PowerShell and Azure CLI are both command-line interfaces for interacting with Microsoft Azure, each with its own characteristics.

Azure PowerShell, built on the PowerShell scripting language, is well-suited for Windows-centric environments and offers powerful scripting capabilities using a Verb-Noun syntax (e.g., Get-AzResource).

Azure Powershell supports interactive scripting, deep integration with the Windows ecosystem, and outputs objects in PowerShell format.

On the other hand, Azure CLI is a cross-platform tool that uses a shell scripting approach (bash, PowerShell) and outputs in various formats like JSON and tables.

It is known for its ease of use, quick command-line tasks, and broader ecosystem integration.

The choice between them often depends on factors such as platform preference, scripting language familiarity, and specific use cases.

Here is a summary table of the differences between Azure PowerShell and Azure CLI:

Why should you consider using Azure CLI, Azure PowerShell (or both)?

There are several reasons why you might consider using Azure CLI or Azure PowerShell for managing your Azure resources:

  1. Automation: Both Azure CLI and Azure PowerShell provide powerful scripting capabilities, allowing you to automate repetitive tasks and streamline your workflows. By writing scripts, you can save time and ensure consistency in your Azure deployments and configurations.
  2. Flexibility: Azure CLI and Azure PowerShell offer a wide range of commands and modules that enable you to interact with various Azure services and resources. They provide comprehensive coverage of Azure functionalities, giving you the flexibility to manage and customize your Azure environment to meet your specific needs.
  3. Cross-platform compatibility: Azure CLI is designed to work on multiple platforms, including Windows, macOS, and Linux. This cross-platform support allows you to use Azure CLI regardless of your operating system, providing a consistent experience across different environments. Azure PowerShell, on the other hand, is primarily targeted for Windows users.
  4. Integration with other tools and workflows: Azure CLI and Azure PowerShell integrate well with other tools and systems. They can be easily incorporated into existing DevOps pipelines, configuration management frameworks, and continuous integration/continuous deployment (CI/CD) processes. This integration enables seamless collaboration and automation within your development and deployment workflows.

Ultimately, the choice between Azure CLI and Azure PowerShell depends on factors such as your familiarity with scripting languages, your preferred operating system, and the specific requirements of your Azure environment.

Additionally, you can use a combination of Azure CLI and Azure PowerShell when necessary to leverage their respective strengths and functionalities.

Using Azure CLI and Azure Powershell from Azure Portal

Azure CLI and Azure PowerShell can be accessed within the Azure cloud environment. Additionally, you have the flexibility to use both tools remotely from your local machine.

To access the Azure Cloud Shell, simply log in to the Azure Portal and locate the Cloud Shell icon.

Clicking on this icon will provide you with access to the Azure Cloud Shell.

You can switch from Powershell to Bash (Azure CLI)

In our example, wi still in powershell envirement, so we want to list our VM on our subscription :

In response, we have the list of all the virtual machines in our subscription.

If we switch to Azure Bash, and try to execute the same command:

Using Azure Powershell From your computer

  1. Open PowerShell as an administrator. To do this, right-click on the PowerShell icon in the Start menu and select “Run as administrator.”
  2. In the PowerShell window, type the following command to install the Az PowerShell module:

Press Enter to execute the command. This will initiate the installation process of the Az PowerShell module.

Once the installation is complete, you can now run the script using the Az PowerShell module.

If you have written a script called “script.ps1” and stored it in C:, you simply need to navigate to the location of the script and then type the command :

The script will be executed, and you will be able to see the results in the PowerShell window.

PowerShell Reference commands

Now, let’s take a look at the most important commands, and we will gradually add interesting commands along the way.

Feel free to leave your comments or important commands in the comments section.

1 Accounts and Subscriptions

Login to Azure Account:

Upon entering this command, you will be redirected to
https://microsoft.com/devicelogin and presented with a popup
window to complete your login process and any MFA requirements.

Logout of the Azure account you are connected with in your session:

List all subscriptions in all tenants the account can access:

Get subscriptions in a specific tenant:

Get-AzSubscription -TenantId "xxxx-xxxx-xxxxxxxx"

2 Resource Groups

Get all resource groups:

Get resource groups where the name begins with “morsi”:

Create a new Resource Group:

New-AzResourceGroup -Name 'My-RG' -Location 'northcentral'
#Creates a new resource group in North Central called “My-RG”

Moving Resources from One Resource Group to Another :

$Resource = Get-AzResource -ResourceType "Microsoft.ClassicCompute/storageAccounts" -
ResourceName "MyStorageAccount"
# Retrieves a storage account called “MyStorageAccount”

Move-AzResource -ResourceId
$Resource.ResourceId -DestinationResourceGroupName
"My-NewRG"
# Moves the resource from Step 1 into the destination resource group “My-NewRG”

3 Governance

Azure Policies: View Policies and Assignments

See all policy definitions in your subscription:

Retrieve assignments for a specific resource group:

$rg = Get-AzResourceGroup -Name "ExampleGroup"
Get-AzPolicyAssignment -Name accessTierAssignment -Scope $rg.ResourceId

4 Storage

Lists all storage accounts in the current subscription

Create Storage Account.

Requires the resource group name, storage account name, valid Azure location, and type (SkuName).

New-AzStorageAccount -ResourceGroupName “mystoragerg” -Name “mystorage1” -Location
“eastus”-SkuName “Standard_LRS”
  • Standard_LRS: Locally-redundant storage.
  • Standard_ZRS: Zone-redundant storage.
  • Standard_GRS: Geo-redundant storage.
  • Standard_RAGRS: Read access geo-redundant storage.
  • Premium_LRS: Premium locally-redundant storage.

5 Deploy and Manage Virtual Machines

List VMs in a resource group (See Resource Groups section above)

Get -AzVM -ResourceGroupName $myResourceGroup

Create a simple VM (Typing in this simple command will create a VM and populate names for all the associated objects based on the VM name specified)

New-AzVM -Name “myvm” 

Create a VM configuration:

$vmconfig = New-AzVMConfig -VMName “systemname” -VMSize "Standard_D1_v2"

Add configuration settings This adds the operating system settings to the configuration:

$vmconfig = Set-AzVMOperatingSystem -VM $vmconfig -Windows -
ComputerName “systemname” -Credential $cred -ProvisionVMAgent
EnableAutoUpdate

Add a network interface:

$vmconfig = Add-AzVMNetworkInterface -VM $vmconfig -Id $nic.Id

Specify a platform image:

$vmconfig = Set-AzVMSourceImage -VM $vmconfig -PublisherName
"publisher_name" -Offer "publisher_offer" -Skus "product_sku" -Version "latest"

Create a VM:

New-AzVM -ResourceGroupName “slresourcegroup” -Location “eastus”
-VM $vmconfigconfig

6 Networking

List virtual networks:

Get-AzVirtualNetwork -ResourceGroupName “slresourcegroup”

Get information about a virtual network:

Get-AzVirtualNetwork -Name "myVNet" -ResourceGroupName “slresourcegroup” 

7 Azure Active Directory Commands

  1. Open PowerShell
  2. Type “Install-Module AzureAD”
  3. Press Y to accept the untrusted repository (PSGallery)

Connect to Azure Active Directory:

New-AzRoleAssignment -ResourceGroupName
“myresourcegroup” -ObjectId 11111111-1111-1111-1111-
11111111111 -RoleDefinitionName Reader

We break down what Windows PowerShell is, and provide you a definitive downloadable PowerShell Commands Cheat Sheet (PDF) as a quick reference to get you started and running your own commands.

email-icon


Updated: November 27, 2023

PowerShell Cheat Sheet

When it comes to running commands on Windows, PowerShell has become somewhat of an ace in the hole. For years enthusiasts were limited to the confines of the Windows command line but in 2006, PowerShell emerged as a powerful alternative.

What is Windows PowerShell?

PowerShell is a cross-platform task automation solution made up of a command-line shell, a scripting language, and a configuration management framework. PowerShell runs on Windows, Linux, and macOS. – Microsoft Learn

  • Command Prompt
  • PowerShell Commands
  • .NET Framework API
  • Windows Management Instrumentation
  • Windows Component Object Model

Download PowerShell – Latest Stable Release

PowerShell cheat sheet (PDF)

Get the PDF version of our PowerShell Cheat Sheet.

Comparitech-Powershell-cheatsheet

How to Use Windows PowerShell

Udemy has a number of top-rated courses on PowerShell that you might find useful.

Loading Up PowerShell

Before we delve into the basics of using PowerShell, you first need to access the main interface.

  1. Press WIN + R, type in powershell, press Ctrl+Shift+Enter. Click OK to run as Administrator.
  2. Type powershell into the Taskbar search field. Select Run as Administrator from the list of options in the right panel of the results list.
  3. Open the Command Prompt, type powershell, and press Enter. Type start-process PowerShell -verb runas and press Enter.
  4. *Also in the Command Prompt, type runas /netonly /user:RemoteDomain\Administrator powershell (substitute a URL or hostname for RemoteDomain)

*A note on option 4 in this list:

How to Run cmdlets

In a nutshell, a cmdlet is a single-function command. You input cmdlets into the command line just as you would with a traditional command or utility. Cmdlets are the main way to interact with the CLI.

:/>  Инструкция по установке принтера hp laserjet

how to run cmdlets powershell

In PowerShell, most cmdlets are written in C# and comprised of instructions designed to perform a function that returns a .NET object.

Over 200 cmdlets can be used in PowerShell. Windows PowerShell command prompt isn’t case-sensitive, so these commands can be typed in either upper or lower case. The main cmdlets are listed below:

  • Get-Location – Get the current directory
  • Set-Location – Get the current directory
  • Move-item – Move a file to a new location
  • Copy-item – Copy a file to a new location
  • Rename – item Rename an existing file
  • New-item – Create a new file
PS C:\> Get-Command
PS C:\>   Set-ExecutionPolicy
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

How to Run PowerShell Scripts

how to run scripts powershell

Script-based processes and commands are part of the foundation of PowerShell’s versatility. In PowerShell, a script is essentially a text file with a ps1 extension in its filename. To create a new script you can simply open the Windows notepad, type your commands, and save with ‘.ps1’ at the end of the name.

To run a script, enter its folder and filename into the PowerShell window:

PS c:\powershell\mynewscript.ps1

Once you’ve done this, your selected script will run.

Looking to create your own PowerShell scripts? Nearly 5k students have taken this Udemy course on Advanced Scripting with PowerShell.

Overlap with Windows Commands

Much like Command Prompt, on PowerShell the cd command still changes directories, and dir still provides a list of files within the selected folder. As such, it’s important to remember you aren’t necessarily starting from scratch. Taking this on board will help to decrease the learning curve you face when using PowerShell and decrease the number of new commands that you have to learn.

Here are some commands that are common to PowerShell and Windows:

  • cd: Change Directory. This command is used to change the current working directory. In PowerShell, Set-Location can be used as well.
  • cls: Clear Screen. This command clears the screen of the console. In PowerShell, Clear-Host or its alias cls can be used.
  • dir: Directory. This command lists the files and subdirectories in the directory. In PowerShell, Get-ChildItem can be used as well.
  • echo: This command prints text to the console. In PowerShell, Write-Output can be used as well.
  • copy: This command copies files. In PowerShell, Copy-Item can be used as well.
  • del: Delete. This command deletes one or more files. In PowerShell, Remove-Item can be used as well.
  • move: This command moves files from one location to another. In PowerShell, Move-Item can be used as well.
  • type: This command displays the contents of a text file. In PowerShell, Get-Content can be used as well.
  • find: This command searches for a text string in a file. In PowerShell, Select-String can be used as well.
  • exit: This command closes the command prompt or terminal window. It works the same in both Command Prompt and PowerShell.

Backing Up an SQL Database with PowerShell

powershell SQL

Many people use PowerShell to back up SQL databases. The command-line interface can conduct full database backups, file backups, and transaction log backups. There are many ways to backup a database in PowerShell, but one of the simplest is to use the Backup-SqlDatabase command. For example:

PS C:\> Backup-SqlDatabase -ServerINstance “Computer\Instance” -Database “Databasecentral”

This will create a database backup of a database with the name ‘Databasecentral’ (or the name of your chosen database’.

To back up a transaction log, you would input:

PS C:\> Backup-SqlDatabase -ServerInstance “Computer\Instance”  -Database “Databasecentral” -BackupAction Log

This will create a transaction log of the selected database.

The Essential PowerShell Commands

Using aliases will only get you so far on PowerShell, so it’s important to commit to learning everything you can about PowerShell’s native commands. We touched on some of these above, but we’re going to break down the main ones in much more detail below.

Get-Help

For example, if you wanted to see how Get-Process works, you would type:

PS C:\> Get-Help -Name Get-Process
PS C:\> Set-ExecutionPolicy

As touched on earlier in this guide, Microsoft has a restricted execution policy that prevents scripting on PowerShell unless you change it. When setting the execution policy, you have four options to choose from:

  • Restricted – The default execution policy that stops scripts from running.
  • All Signed – Will run scripts if they are signed by a trusted publisher
  • Remote Signed – Allows scripts to run which have been created locally
  • Unrestricted – A policy with no restrictions on running scripts
PS C:\> Get-ExecutionPolicy

If you’re using PowerShell, you may not always work on a server that you’re familiar with. Running the command Get-Execution Policy will allow you to see which policy is active on the server before running a new script. If you then see the server in question operating under a restricted policy, you can then implement the Set-ExecutionPolicy command to change it.

Get-Service

For example, if you were to type PS C:\> Get-Service, you would be shown a list of all services on your computer, their statuses, and display names.

To use this command to retrieve specific services, type:   PS C:\ Get-Service “WMI*” to retrieve all services that begin with WMI.

PS C:\ Get-Service | Where-Object {$_.Status -eq “Running”}

ConvertTo-HTML

When using PowerShell, you might want to generate a report about the information you’ve seen. One of the best ways to do this is by using the ConvertTo-HTML command. This cmdlet allows you to build reports with tables and color, which can help to visualize complex data. Simply choose an object and add it to the command.

For example, you could type:

Get-PSDrive | ConvertTo-Html

This returns a mass of information, so it’s a good idea to limit it to a file with the Out-File command. A better alternative command is:

Get-PSD Drive | ConvertTo-Html | Out-File -FilePath PSDrives.html

This will then generate an HTML file in table form. For example:

powershell html table

You can then add your own colors and borders to refine its presentation.

Export-CSV (and Get-Service)

To use this command, you would type:

PS C:\> Get-Service | Export-CSV c:\service.csv

It’s important to remember not to format objects before running the Export-CSV command. This is because formatting objects results in only the formatted properties being placed into the CSV file rather than the original objects themselves. In the event that you want to send specific properties of an object to a CSV file, you would use the Select-Object cmdlet.

To use the Select-Object cmdlet, type:

PS C:\> Get-Service | Select-Object Name, Status | Export-CSV c:\Service.csv

Get-Process

If you want to view all processes currently running on your system, the Get-Process command is very important. To get a list of all active processes on your computer, type:

PS C:\ Get-Process

Notice that if you don’t specify any parameters, you’ll get a breakdown of every active process on your computer. To pick a specific process, narrow the results down by process name or process ID and combine that with the Format-List cmdlet, which displays all available properties. For example:

PS C:\ Get-Process windowrd, explorer | Format-List *

This provides you with comprehensive oversight of all active processes.

Get-EventLog

get eventlog security cmdlet

If you ever want to access your computer’s event logs (or logs on remote computers) while using PowerShell, then you’re going to need the Get-EventLog command. This cmdlet only works on classic event logs, so you’ll need the Get-WinEvent command for logs later than Windows Vista.

To run the event log command, type:

PS C:\> Get-EventLog -List

This will show all event logs on your computer.

PS C:\> Get-EventLog -LogName System -EntryType Error

If you want to get event logs from multiple computers, specify which devices you want to view (listed below as “Server1” and “Server2”). For example:

PS C:\> Get-EventLog - LogName “Windows PowerShell” -ComputerName “local computer”, “Server1”, “Server2”.
Parameters you can use to search event logs include:
AfterUser specifies a date and time and the cmdlet will locate events that occurred after
AsBaseObjectProvides a System.Diagnostics.EventLogEntry for each event
AsStringReturns the output as strings
BeforeUser specifies a date and time and the cmdlet will locate events that occurred before
ComputerNameUsed to refer to a remote computer
EntryTypeSpecifies the entry type of events (Error, Failure Audit, Success Audit, Information, Warning)
IndexSpecifies index values the cmdlet finds events from
ListProvides a list of event logs
UserNameSpecifies usernames associated with a given event

 Stop-Process

powershell stop-process

When using PowerShell, it’s not uncommon to experience a process freezing up. Whenever this happens, you can use Get-Process to retrieve the name of the process experiencing difficulties and then stop it with the Stop-Process command.

Generally, you terminate a process by its name. For example:

PS C:\> Stop-Process -Name “notepad”

PowerShell Commands List

Here are 25 basic PowerShell commands:

Command nameAliasDescription
Set-Locationcd, chdir, slSets the current working location to a specified location.
Get-Contentcat, gc, typeGets the content of the item at the specified location.
Add-ContentacAdds content to the specified items, such as adding words to a file.
Set-ContentscWrites or replaces the content in an item with new content.
Copy-Itemcopy, cp, cpiCopies an item from one location to another.
Remove-Itemdel, erase, rd, ri, rm, rmdirDeletes the specified items.
Move-Itemmi, move, mvMoves an item from one location to another.
Set-ItemsiChanges the value of an item to the value specified in the command.
New-ItemniCreates a new item.
Start-JobsajbStarts a Windows PowerShell background job.
Compare-Objectcompare, difCompares two sets of objects.
Group-ObjectgroupGroups objects that contain the same value for specified properties.
Invoke-WebRequestcurl, iwr, wgetGets content from a web page on the Internet.
Measure-ObjectmeasureCalculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files …
Resolve-PathrvpaResolves the wildcard characters in a path, and displays the path contents.
Resume-JobrujbRestarts a suspended job
Set-Variableset, svSets the value of a variable. Creates the variable if one with the requested name does not exist.
Show-CommandshcmCreates Windows PowerShell commands in a graphical command window.
Sort-ObjectsortSorts objects by property values.
Start-ServicesasvStarts one or more stopped services.
Start-Processsaps, startStarts one or more processes on the local computer.
Suspend-JobsujbTemporarily stops workflow jobs.
Wait-JobwjbSuppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are …
Where-Object?, whereSelects objects from a collection based on their property values.
Write-Outputecho, writeSends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline,…
:/>  Как перенести Windows 7 на другой компьютер

Is Windows PowerShell the same as Command Prompt?

PowerShell is an advancement on Command Prompt because its shell scripting capabilities include better programming constructs than those available for batch jobs in Command Prompt. All of the Command Prompt commands are available in PowerShell but then PowerShell has extra commands and utilities, called cmdlets. Think of PowerShell as Command Prompt +.

How do I learn bash scripting?

Bash scripting is a Unix shell script. As Linux is an adaptation of Unix, a shell script written for Linux is often called a Bash script. There are a lot of online tutorials on how to create a Bash script. In order to avoid confusion, try not to refer to a PowerShell script as a Bash script.

How can I make Command Prompt default instead of PowerShell?

When you press WIN + X, you now get a PowerShell window instead of the old Command Prompt. To stick with Command Prompt, go to the Start menu and click on Settings. In the Settings menu, select Personalization. Select Taskbar in the left-hand menu of the Personalization Settings Window. In the main panel of that window, look for Replace Command Prompt with Windows PowerShell in the menu when I right-click the Start button or press Windows key+X. Set that to Off.

  1. Press WIN + R, type in powershell, press Ctrl+Shift+Enter. Click OK to run as Administrator.
  2. Type powershell into the Taskbar search field. Select Run as Administrator from the list of options in the right panel of the results list.
  3. Open the Command Prompt, type powershell, and press Enter. Type start-process PowerShell -verb runas and press Enter.

How do I run PowerShell commands?

You can run PowerShell commands from a Command Prompt window by using the format: powershell -command ” <PowerShellCode> “ but put your PowerShell command inside the quotes instead of <PowerShellCode>. If your PowerShell command requires a value in quotes, use single quotes in there instead of double-quotes. The surrounding quotes in the execution example here should remain as double-quotes.

We also included a PowerShell commands cheat sheet for quick reference so you can easily find and apply the commands discussed.

  • PowerShell is a cross-platform system administration and automation tool compatible with Windows, Linux, and macOS.
  • We highlight 30 basic PowerShell commands covering file system navigation, file manipulation, system administration, user and permissions management, networking, process management, and working with objects, along with a cheat sheet for quick reference.
  • You can automate complex operations through PowerShell scripting and extend its functionality with modules, which provide advanced commands and functions for specialized tasks.
  • Best practices include using clear naming conventions, simplifying commands, modularizing code, consistent formatting, avoiding hard-coded values, implementing error handling, and the importance of commenting and documenting your scripts.


Table of Contents

Table of Contents


Table of Contents

Basic Concepts of PowerShell

Cmdlets

Cmdlets are small commands in PowerShell designed to perform a single operation. For example, Get-Content reads content from a file, while Set-Content writes content to a file. Cmdlets can be combined, and their output can be manipulated to handle complex tasks. They form the foundation of PowerShell’s functionality.

Scripts

PowerShell scripts are text files that contain cmdlets and other PowerShell commands saved with a .ps1 extension. They automate longer sequences of tasks and can be simple or complex.

Pipeline

PowerShell Pipeline connects multiple cmdlets, passing the output of one as the input to the next. This chaining of commands enables you to perform complex operations with minimal code. For example, you can list all files in a directory and filter them by size or type in a single line of code.

PowerShell Integrated Scripting Environment (ISE)

Essential PowerShell Commands You Should Know

There are so many Windows PowerShell commands available that it can easily become a bit overwhelming to figure out where to start.

Navigating the File System

Image showing file system navigation with powershell

  • Get-ChildItem: Lists items in a directory.
  • Set-Location: Changes the current directory.
  • Push-Location: Saves the current directory on a stack so you can return to it.
  • Pop-Location: Returns to the directory saved by Push-Location.

File Manipulation

Image showing file manipulation with powershell

  • New-Item: Creates a new file or directory.
  • Remove-Item: Deletes a file or directory.
  • Copy-Item: Copies a file or directory to another location.
  • Move-Item: Moves a file or directory to a new location.
  • Rename-Item: Renames a file or directory.

System Administration

Image showing system administration with powershell

  • Get-Service: Lists all services on a computer.
  • Start-Service: Starts a stopped service.
  • Stop-Service: Stops a running service.
  • Restart-Service: Restarts a service.

User & Permissions Management

  • Get-LocalUser: Retrieves local user accounts.
  • New-LocalUser: Creates a new local user account.
  • Remove-LocalUser: Deletes a local user account.
  • Get-Acl: Gets access control list (ACL) for a file or resource.
  • Set-Acl: Sets the ACL for a file or resource.

Networking Commands

Image showing networking commands for powershell

  • Test-Connection: Sends ICMP echo requests to a target host to test connectivity.
  • Get-NetIPAddress: Retrieves IP address configuration.
  • Get-NetAdapter: Lists network adapters.
  • Resolve-DnsName: Resolves a DNS name to an IP address.

Process Management

Image showing process management with powershell

  • Get-Process: Lists currently running processes.
  • Start-Process: Starts a new process.
  • Stop-Process: Stops a running process.
  • Wait-Process: Waits for a process to exit.

Working With Objects

Image shows working with objects on Powershell

  • Select-Object: Selects specific properties of an object.
  • Where-Object: Filters objects based on property values.
  • Sort-Object: Sorts objects by property values.
  • Group-Object: Groups objects by property values.

We’ve listed the most common PowerShell Commands you should know, but what about an alias for a given command? How about its syntax?

With this cheat sheet, you can get everything you need to know about those essential commands, along with an example, for quick reference.

AliasCommandSyntaxExampleDescription
Navigating the File System
Gci, ls, dirGet-ChildItemGet-ChildItem -Path <Path>Get-ChildItem -Path C:\UsersLists items in a specified directory
Cd, chdirSet-LocationSet-Location -Path <Path>Set-Location -Path C:\WindowsChanges the current directory
pushdPush-LocationPush-Location -Path <Path>Push-Location -Path C:\WindowsSaves the current directory on a stack
popdPop-LocationPop-LocationPop-LocationReturns to the directory saved by Push-Location
File Manipulation
niNew-ItemNew-Item -Path <Path> -ItemType FileNew-Item -Path .\file.txt -ItemType FileCreates a new file
del, erase, rd, ri, rm, rmdir, rpRemove-ItemRemove-Item -Path <Path>Remove-Item -Path .\file.txtDeletes a file or directory
copy, cp, cpi, cppCopy-ItemCopy-Item -Path <Path> -Destination <Destination>Copy-Item -Path .\file.txt -Destination .\backup\file.txtCopies a file to a new location
mi, move, mp, mvMove-ItemMove-Item -Path <Path> -Destination <Destination>Move-Item -Path .\file.txt -Destination .\new\file.txtMoves a file to a new location
ren, rni,Rename-ItemRename-Item -Path <Path> -NewName <NewName>Rename-Item -Path .\file.txt -NewName new_file.txtRenames a file
System Administration
gsvGet-ServiceGet-ServiceGet-ServiceWhere-Object {$_.Status -eq “Running”}`
sasvStart-ServiceStart-Service -Name <Name>Start-Service -Name “bits”Starts a stopped service
spsvStop-ServiceStop-Service -Name <Name>Stop-Service -Name “bits”Stops a running service
Restart-ServiceRestart-Service -Name <Name>Restart-Service -Name “bits”Restarts a service
User & Permissions Management
gluGet-LocalUserGet-LocalUserGet-LocalUserSelect-Object Name`
nluNew-LocalUserNew-LocalUser -Name <Name>New-LocalUser -Name “User1”Creates a new local user account
rluRemove-LocalUserRemove-LocalUser -Name <Name>Remove-LocalUser -Name “User1”Deletes a local user account
Get-AclGet-Acl -Path <Path>Get-Acl -Path .\file.txtGets ACL for a file or resource
Set-AclSet-Acl -Path <Path> -AclObject <AclObject>Set-Acl -Path .\file.txt -AclObject $aclSets the ACL for a file or resource
Networking Commands
Test-ConnectionTest-Connection -ComputerName <Name>Test-Connection -ComputerName google.comTests network connectivity
Get-NetIPAddressGet-NetIPAddressGet-NetIPAddress -InterfaceAlias “Ethernet”Retrieves IP address configuration
Get-NetAdapterGet-NetAdapterGet-NetAdapter -Name “Ethernet”Lists network adapters
Resolve-DnsNameResolve-DnsName -Name <Name>Resolve-DnsName -Name google.comResolves a DNS name to an IP address
Process Management
gps, psGet-ProcessGet-ProcessGet-ProcessWhere-Object {$_.CPU -gt 100}`
start, sapsStart-ProcessStart-Process -FilePath <FilePath>Start-Process -FilePath “notepad.exe”Starts a new process
spps, killStop-ProcessStop-Process -Name <Name>Stop-Process -Name “notepad”Stops a running process
Wait-ProcessWait-Process -Name <Name>Wait-Process -Name “notepad”Waits for a process to exit
Working With Objects
selectSelect-ObjectSelect-Object -Property <Property>Get-Process | Select-Object Name, CPUSelects specific properties of an object
Where-ObjectWhere-Object {$_.Property -Condition <Value>}Get-Process | Where-Object {$_.CPU -gt 100}Filters objects based on property values
sortSort-ObjectSort-Object -Property <Property>Get-Process | Sort-Object CPUSorts objects by property values
groupGroup-ObjectGroup-Object -Property <Property>Get-Process | Group-Object ProcessNameGroups objects by property values
:/>  Программы для блокировки клавиатуры и мыши в Windows

Advanced PowerShell Commands & Techniques

  • Control Structures: These are the if, else, and switch statements for decision-making and loops (for, for each, while, do-while) for repetitive tasks.
  • Functions: Functions are reusable blocks of code that you can call with a name. They help organize scripts into manageable sections and can accept parameters for dynamic operation.
  • Error Handling: PowerShell uses try, catch, and finally blocks for error handling. This allows scripts to gracefully handle errors and continue executing or properly terminate.

Scripts can automate almost any task that can be performed in the PowerShell command line. Complex scripts can manage system updates, deploy software across networks, automate file management, and a whole lot more.

The key is combining cmdlets, control structures, and custom functions to create a sequence of operations that run without manual intervention.

Modules expand PowerShell’s capabilities by adding new commands, including cmdlets and functions. After importing a module with Import-Module, you can access additional functionalities for specific tasks, like AzureRM for Azure resources, ActiveDirectory for directory services, and PSDsc for configuration management.

Modules can be either built-in, downloaded from the PowerShell Gallery, or custom-made.

PowerShell Scripting Best Practices

  • Use Clear Naming Conventions: Choose descriptive names for functions and variables. This makes your script self-documenting and easier to understand.
  • Keep It Simple: Write simple and straightforward commands. Complex one-liners can be impressive but difficult to read and maintain.
  • Modularize Your Code: Break your script into functions. This approach makes your code reusable and easier to test.
  • Use Consistent Formatting: Use consistent indentation, spacing, and bracket placement. This consistency improves readability and maintenance.
  • Avoid Hard-Coding Values: Use parameters and configuration files instead of hard-coded values. This makes your scripts more flexible and easier to update.
  • Implement Error Handling: Use try, catch, and finally, blocks to handle errors. Proper error handling prevents your script from failing silently and makes debugging easier.
  • Comment Your Code: Comments are very important for explaining the purpose of your code, how it works, and why specific decisions were made. Comments are valuable for anyone who may work on your script in the future, including your future self.
  • Document Your Script: Alongside in-line comments, document at the beginning of your script its purpose, usage, parameters, and any dependencies. It is important for others to understand and use your script.

The Bottom Line

The PowerShell commands cheat sheet provided is a good starting point, but it’s important to practice these commands and explore beyond the basics.

Advanced scripting, using modules, and learning new commands will unlock PowerShell’s full capabilities.

What are commands for PowerShell?

How do I script a PowerShell command?

How do I use PowerShell from the command prompt?

Did you find this summary helpful?

Thank you for your feedback

(See also WMI Class Reference for additional information about WMI classes used by Netreo.)

DHCP Server

See DHCP Server (Device Subtype)

  • gwmi -Namespace "" -Query "SELECT Name, DiscoversPersec, OffersPersec, RequestsPersec, InformsPersec, AcksPersec, NacksPersec, ReleasesPersec, Timestamp_Sys100NS, Frequency_Sys100NS FROM Win32_PerfRawData_DHCPServer_DHCPServer" | Select *

Hyper-V Host

Hyper-V Host (Device Type)

  • gwmi -Namespace "" -Query "SELECT Name, PercentTotalRunTime, PercentTotalRunTime_Base, Frequency_Sys100NS, Timestamp_Sys100NS FROM Win32_PerfRawData_HvStats_HyperVHypervisorVirtualProcessor" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, PercentTotalRunTime, PercentTotalRunTime_Base, Frequency_Sys100NS, Timestamp_Sys100NS FROM Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, AvailableBytes, Timestamp_Sys100NS FROM Win32_PerfRawData_PerfOS_Memory" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, CurrentBandwidth, BytesReceivedPersec, BytesSentPersec, PacketsOutboundErrors, PacketsOutboundDiscarded, PacketsReceivedErrors, PacketsReceivedDiscarded, Timestamp_Sys100NS, Frequency_Sys100NS FROM Win32_PerfRawData_Tcpip_NetworkInterface" | Select *
  • gwmi -Namespace "" -Query "SELECT DeviceID, DriveType, FreeSpace, Size FROM Win32_LogicalDisk" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, DiskReadBytesPersec, DiskWriteBytesPersec, Timestamp_Sys100NS, Timestamp_PerfTime, Frequency_PerfTime, Frequency_Sys100NS FROM Win32_PerfRawData_PerfDisk_LogicalDisk" | Select *

Microsoft IIS Server

See Microsoft IIS Server (Device Subtype)

  • gwmi -Namespace "" -Query "SELECT Name, AvailableBytes, CommittedBytes, PagesPersec, PoolNonpagedBytes, Timestamp_Sys100NS, Timestamp_PerfTime, Frequency_PerfTime, Frequency_Sys100NS FROM Win32_PerfRawData_PerfOS_Memory" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, RequestWaitTime, RequestsQueued FROM Win32_PerfRawData_ASPNET_ASPNET" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, BytesReceivedPersec, BytesSentPersec, BytesTotalPersec, ConnectionAttemptsPersec, ConnectionAttemptsPersec, Timestamp_Sys100NS, Timestamp_PerfTime, Frequency_PerfTime, Frequency_Sys100NS FROM Win32_PerfRawData_W3SVC_WebService" | Select *

Windows Mounted Volume

See Windows Mounted Volume (Device Subtype)

  • gwmi -Namespace "" -Query "SELECT Capacity, FreeSpace FROM Win32_Volume" | Select *

Windows Server

See Windows Server – Detailed (Device Type) and Windows Server – Standard (Device Type)

  • gwmi -Namespace "" -Query "SELECT Name, LastBootUpTime FROM Win32_OperatingSystem" | Select *
  • gwmi -Namespace "" -Query "SELECT DeviceID, DriveType, FreeSpace, Size FROM Win32_LogicalDisk" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, DiskReadBytesPersec, DiskWriteBytesPersec, Timestamp_Sys100NS, Timestamp_PerfTime, Frequency_PerfTime, Frequency_Sys100NS FROM Win32_PerfRawData_PerfDisk_PhysicalDisk" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, AvgDiskReadQueueLength, AvgDiskWriteQueueLength, DiskReadsPersec, DiskWritesPersec, Timestamp_Sys100NS, Timestamp_PerfTime, Frequency_PerfTime, Frequency_Sys100NS  FROM Win32_PerfRawData_PerfDisk_LogicalDisk" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, AvailableBytes, PageFaultsPersec, Timestamp_Sys100NS, Timestamp_PerfTime, Frequency_PerfTime, Frequency_Sys100NS FROM Win32_PerfRawData_PerfOS_Memory" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, PercentProcessorTime, Timestamp_Sys100NS FROM Win32_PerfRawData_PerfOS_Processor" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, WorkingSet, PercentProcessorTime, Timestamp_Sys100NS FROM Win32_PerfRawData_PerfProc_Process" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, ContextSwitchesPersec, Timestamp_Sys100NS, Frequency_Sys100NS FROM Win32_PerfRawData_PerfOS_System" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, CurrentBandwidth, BytesReceivedPersec, BytesSentPersec, PacketsOutboundErrors, PacketsOutboundDiscarded, PacketsReceivedErrors, PacketsReceivedDiscarded, Timestamp_Sys100NS, Frequency_Sys100NS FROM Win32_PerfRawData_Tcpip_NetworkInterface" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, CurrentUsage FROM Win32_PageFileUsage" | Select *
  • gwmi -Namespace "" -Query "SELECT Name, NumberOfProcessors, NumberOfLogicalProcessors, TotalPhysicalMemory FROM Win32_ComputerSystem" | Select *
  • gwmi -Namespace "" -Query "SELECT SELECT Name, NumberOfProcessors, TotalPhysicalMemory FROM Win32_ComputerSystem" | Select *

Was this article helpful?

https://www.example.com

We’ll cover key topics such as objects, regular expressions, operators, and tips and best practices for working with this powerful task automation tool. So, rather than spending more time than you need in the official documentation or in remembering complex commands, keep our Windows PowerShell cheat sheet within reach and get to work.

Download this cheat sheet here. When you’re ready, let’s get started.

Search our PowerShell cheat sheet to find the right cheat for the term you’re looking for. Simply enter the term in the search bar and you’ll receive the matching cheats available.

What Is PowerShell?

The PowerShell Integrated Scripting Environment (ISE) is a terminal console for running PowerShell commands known as cmdlets (pronounced “command-let”) and writing/executing PowerShell scripts with the file extension “.ps1”.

Table Of Contents

How to Use PowerShell

PowerShell comes pre-installed on Windows and Azure, but you can install it on certain Linux distributions through their respective package managers and on the latest macOS version via Homebrew, direct download, or binary archives.

How to start a PowerShell instance:

Operating systemAction
WindowsRight-click Start > select “Windows PowerShell”
If you want elevated privileges, select ”Windows PowerShell (Admin)”
Run Command Prompt (click Start > type cmd) > input “PowerShell” and select your preferred option—with or without “(Admin)”
LinuxRaspberry Pi: In Terminal, type ~/powershell/pwsh > press Enter.
Other distributions: In Terminal, input pwsh > press Enter.
macOSIn Terminal, input pwsh > press Enter.

Useful PowerShell Commands

The table below lists the most important PowerShell commands. Although PowerShell aliases resemble Command Prompt (cmd.exe) or Bash commands, they’re not functions native to PowerShell but are shortcuts to the corresponding PowerShell commands.

Command nameAliasDescription
Get-Help Get-Command(None)Display help information about PowerShell command Get-Command (which lists all PowerShell commands).
You may replace Get-Command with any PowerShell command of your choice.
Get-ChildItemdir, ls, gci Lists all files and folders in the current working directory
Get-Locationpwd, glGet the current working directory
Set-Locationcd, chdir, slSets the current working location to a specified location
Get-Contentcat, gc, typeGets the content of the item at the specified location
Copy-Itemcopy, cp, cpiCopies an item from one location to another
Remove-Itemdel, erase, rd, ri, rm, rmdirDeletes the specified items
Move-Itemmi, move, mvMoves an item from one location to another
New-ItemniCreates a new item
Out-File>, >>Send output to a file.
When you wish to specify parameters, stick to Out-File.
Invoke-WebRequestcurl, iwr, wgetGet content from a web page on the Internet
Write-Outputecho, writeSends the specified objects to the next command in the pipeline.
If Write-Output is the last command in the pipeline, the console displays the objects.
Clear-Hostcls, clearClear console

PowerShell syntax

PowerShell is so complex and contains so many commands that you need to understand its syntax to use it well.

Parameters

Parameters are command arguments that enable developers to build reusable PowerShell scripts. For a command with two parameters (here, Parameter1 takes a value, but Parameter2 doesn’t), the syntax is:

Do-Something -Parameter1 value1 -Parameter2

To find all commands with, say, the “ComputerName” parameter, use:

Get-Help * -Parameter ComputerName

Risk mitigation parameterDescriptionExample
-ConfirmPrompt whether to take action.Creating a new item called test.txt:
ni test.txt -Confirm
-WhatIfDisplays what a certain command would do.Removal of an item called test.txt:
del test.txt -WhatIf

Here’s more information about common parameters in PowerShell.

Pipes

Here is an example involving four commands:

In this example, Get-Service sends a list of all the Windows services to Where-Object, which filters out the services having Running as their Status. The filtered results pass through Select-Object, which picks out the columns Name, DisplayName, and StartType, and finally, Sort-Object sorts these columns by StartType and Name.

Шпаргалка по командам windows power shell

Other examples of pipes:

CommandDescription
"plan_A.txt" | Rename-Item -NewName "plan_B.md" Rename the file “plan_A.txt” to a new name “plan_B.md
Get-ChildItem | Select-Object basename | Sort-Object *Lists the names of all the files in the current working directory, sorted in alphabetical order.

Objects

In the example below, we explore a Fax application .NET Framework object:

Шпаргалка по командам windows power shell

Fax has one or more properties. Let’s check out the Status property. It turns out that it’s not in use:

(Get-Service -Name Fax).Status

Output of "(Get-Service -Name Fax).Status" reveals that the Fax application status is Stopped

One of the methods listed is “GetType” and we can try it out:

(Get-Service -Name Fax).GetType()

Output of "(Get-Service -Name Fax).GetType()" reveals the type of object Fax is

This method shows that the .NET object Fax is a ServiceController.

Variables

These are the basic commands for defining and calling PowerShell variables.

CommandDescription
New-Variable var1Create a new variable var1 without defining its value
Get-Variable my*Lists all variables in use beginning with “my*”
Remove-Variable bad_variableDelete the variable called “bad_variable” 
$var = "string"Assign the value “string” to a variable $var
$a,$b = 0Assign the value 0 to the variables $a, $b
$a,$b,$c = 'a','b','c'Assign the characters 'a', 'b', 'c' to respectively-named variables
$a,$b = $b,$aSwap the values of the variables $a and $b
$var = [int]5Force the variable $var to be strongly typed and only admit integer values
VariableDescription
$HOMEPath to user’s home directory
$NULLEmpty/null value
$TRUEBoolean value TRUE
$FALSEBoolean value FALSE
$PIDProcess identifier (PID) of the process hosting the current session of PowerShell

Regular Expressions

A regular expression (regex) is a character-matching pattern. It can comprise literal characters, operators, and other constructs.

Here are the rules for constructing regexes:

Regex syntaxDescription
[ ]Allowable characters, e.g., [abcd] means 'a'/'b'/'c'/'d'
[aeiou]Single vowel character in English
^1. Use it with square brackets [ ] to denote exclusion
2. For matching the beginning of a string
[^aeiou]Single consonant character in English
$For matching the end of a string
-Use with square brackets [ ] to denote character ranges
[A-Z]Uppercase alphabetic characters
[a-z]Lowercase alphabetic characters
[0-9]Numeric characters
[ -~]All ASCII-based (hence printable) characters
\tTab
\nNewline
\rCarriage return
.Any character except a newline (\n) character; wildcard
*Match the regex prefixed to it zero or more times.
+Match the regex prefixed to it one or more times.
?Match the regex prefixed to it zero or one time.
{n}A regex symbol must match exactly n times. 
{n,}A regex symbol must match at least n times. 
{n,m}A regex symbol must match between n and m times inclusive.
\Escape; interpret the following regex-reserved characters as the corresponding literal characters: []().\^$|?*+{}
\dDecimal digit
\DNon-decimal digit, such as hexadecimal
\wAlphanumeric character and underscore (“word character”)
\WNon-word character
\sSpace character
\SNon-space character
Check for -MatchCheck for -NotMatch
<string> -Match <regex><string> -NotMatch <regex>
RegexStrings that -Match Strings that do -NotMatch
'Hello world''Hello world''Hello World'
'^Windows$''Windows''windows'
'[aeiou][^aeiou]''ah''lo'
'[a-z]''x''X'
'[a-z]+-?\d\D''server0F','x-8B''--AF'
'\w{1,3}\W''Hey!''Fast'
'.{8}''Break up''No'
'..\s\S{2,}''oh no''\n\nYes'
'\d\.\d{3}''1.618''3.14'

Operators

PowerShell has many operators. Here we present the most commonly used ones.

OperatorDescriptionExample
+Addition. Adds values on either side of the operator.$a + $b → 30
-Subtraction. Subtracts right-hand operand from the left-hand operand.$a - $b → -10
*Multiplication. Multiplies values on either side of the operator.$a * $b → 200
/Division. Divides left-hand operand by right-hand operand.$b / $a → 2
%Modulus. Divides left-hand operand by right-hand operand and returns the remainder.$b % $a → 0
OperatorMath symbol (not PowerShell)DescriptionExample
eq=Equal$a -eq $b → $false
neUnequal$a -ne $b → $true
gt>Greater than$b -gt $a → $true
geGreater than or equal to$b -ge $a → $true
lt<Less than$b -lt $a → $false
leLess than or equal to$b -le $a → $false
OperatorDescriptionExample
=Assign values from the right-side operands to the left-hand operand.Assign the sum of variables $a and $b to a new variable $c:
$c = $a + $b
+=Add the right side operand to the left operand and assign the result to the left-hand operand.$c += $a ⇔ $c = $c + $a
-=Subtract the right side operand from the left operand and assign the result to the left-hand operand.$c -= $a ⇔ $c = $c - $a
OperatorDescriptionExample
-andLogical AND. If both operands are true/non-zero, then the condition becomes true.($a -and $b) → $true
-orLogical OR. If any of the two operands are true/non-zero, then the condition becomes true.($a -or 0) → $true
-not, !Logical NOT. Negation of a given Boolean expression.!($b -eq 20) → $false
-xorLogical exclusive OR. If only one of the two operands is true/non-zero, then the condition becomes true.($a -xor $b) → $false
OperatorDescription
>Send output to the specified file or output device.
>>Append output to the specified file or output device.
>&1Redirects the specified stream to the standard output stream.