If statements are conditional logic statements that you can add to your PowerShell scripts. If statements mimic the decision-making process people use every day. If a condition is met, then something happens. For example, if it’s raining outside, I’ll grab an umbrella before heading outside.
If statements in PowerShell function similarly to If statements in other programming languages.
In this diagram, if the condition is true, then it runs a specific command or statement. If the condition is false, it moves onto the next command or statement. Here’s a simple PowerShell example.
In this example, we created a variable called $eggs and gave it a value of 10. Next, we set a conditional statement that says if $eggs is less than 12, display a message. Since $eggs has a value of 10, the message “You have less than a dozen eggs” is displayed.
Now that we have a basic understanding of If statements, let’s dive a little deeper and go over the syntax and some more advanced examples.
PowerShell If statement syntax
The syntax of If statements in PowerShell is pretty basic and resembles other coding languages.
The condition statement itself can be structured in various different ways. Many condition statements use comparison operators. In my earlier eggcelent example, I used the -lt comparison operation in my conditional statement, which stands for less than. Here is a list of some of the comparison operators you can use in PowerShell.
Keep in mind that condition statements don’t require comparison operators. You can use regular PowerShell cmdlets in the condition statement. For example:
In this example, we are calling the Test-Path cmdlet to see if a file exists or not. If the file exists, we use the Get-Content and Measure-Object cmdlets to return a word count of the file. If the file does not exist, then the script will just end. As you can see from the screenshot, my MacGyver biography is only 8 words long so far. One of these days, I’ll finish it.
PowerShell If-Else statements
Up to this point, we’ve only talked about If statements. However, you’ll often find If statements accompanied by an Else statement. Else statements allow you to perform an additional action if the condition is not met or returns false.
In this diagram, you can see that we now have two statements that can be executed. One statement if the condition returns true, and one statement if the condition returns false. Here’s a simple PowerShell If-Else statement example.
In this example, we’ve set the variable $x to a value of 4. We then set our If statement with the condition that if $x is greater than or equal to 3, display the message “$x is greater than or equal to 3.” Lastly, we set our Else statement that if the condition is false, display the message “$x is less than 3.”
You can see from the screenshot that since $x equaled 4, the condition returned true. Now let’s change the value of $x to 1, making the condition return false.
Now that the condition returns false, you can see that PowerShell is returning our Else statement, “$x is less than 3.”
Nesting conditional statements
The second and preferred way to nest conditional statements is to use the elseif statement. Here’s an example that builds on the egg example we covered earlier.
In this example, we have three possible outcomes. One if we have exactly 12 eggs. One if we have less than 12 eggs. And one if we have more than 12 eggs. In the screenshot above, we have our $egg variable set to 14, which returned the Else statement, displaying the message “You have more than a dozen eggs.”
Negating PowerShell statements
Sometimes with operators, we need to negate the statement. Using the previous MacGyver example, what if instead of searching for the MacGyver biography, we want to make sure it isn’t there? Here’s an example of how to do that:
Now that we know all about If statements, Else statements, and nested conditional statements, let’s bring it all together by creating a script that will give us our dinner plans depending on what day of the week it is.
First, we’ll get the day of the week using the Get-Date cmdlet, returning the DayOfWeek property and assigning it to the $day variable.
$day = (Get-Date).DayOfWeek
Next, we’ll build our nested conditional statement for the different days of the week and assign a different meal for each day.
Wrapping up
If you’re interested in other powerful tools, make sure you download a free trial of PDQ Deploy and PDQ Inventory. PDQ Deploy will help you keep your network environment up to date, making deployments and updates a breeze. PDQ Inventory will ensure you have all the information you need to properly manage all of your Windows devices. PDQ Inventory also gives you access to the PowerShell scanner, letting you take advantage of all the cool PowerShell knowledge you just learned in this article.
Born in the ’80s and raised by his NES, Brock quickly fell in love with everything tech. With over 15 years of IT experience, Brock now enjoys the life of luxury as a renowned tech blogger and receiver of many Dundie Awards. In his free time, Brock enjoys adventuring with his wife, kids, and dogs, while dreaming of retirement.

Conditional statements are an essential part of programming, and PowerShell provides several ways to implement them. The cornerstone of conditional logic in PowerShell is the if else
statement. It allows you to control the flow of your code based on Boolean conditions. Using these conditional statements can add powerful logic to your scripts. This article dives into the depths of if else statements in PowerShell scripts, explaining the basics of If-Else statements, elucidating their syntax, usage, and best practices for writing them to help you become a master of If-Else statements.
Whether you are a beginner or an experienced scripter, mastering the If, Else, and Else If statements will add a versatile tool to your toolkit. By the end of this article, you will have a solid foundation for implementing conditional logic to control the flow of your PowerShell code. So, let’s get started exploring conditional logic statements If, ElseIf, and Else in PowerShell!
Table of contents
- Introduction to PowerShell If-Else Statements
- Understanding the If Else Statement in PowerShell
- How to use ElseIf statements in PowerShell?
- Nested If-Else statements in PowerShell
- Using If-Else statements with comparison operators
- Display Menu in PowerShell using If-ElseIf-Else statement
- Combining Multiple Conditions with Logical and Comparison Operators
- Best Practices and Tips for PowerShell If Statement
- Troubleshooting common issues with If-Else statements in PowerShell
Introduction to PowerShell If-Else Statements
If-Else statements allow you to make decisions in your scripts based on conditions, which can help automate processes and reduce manual intervention. The If statement evaluates a condition and executes code if the condition is true. The Else statement executes code if the condition (or the Boolean expression) is false.
The basic Syntax of If statements in PowerShell
The most commonly used conditional statement in PowerShell is the “if” statement. At its core, an if statement syntax is relatively straightforward. It consists of three components: the term “if”, a condition evaluates a given statement, and an action inside curly brackets will be executed if the condition is met.
if (condition) { # Statement lists - Commands or actions to execute if condition is true }
PowerShell If Statement Examples
Let’s look at some examples of the PowerShell “if” statement in action:
$num = 5 if ($num -gt 0) { Write-Host "The number is positive." }
In this example, we are checking if the value of the variable $num is greater than zero. If it is, we execute the code to display the message “The number is positive.”. To illustrate the IF condition better, let’s consider a simple example. Suppose we want to check if a file exists in a particular directory. We can use the if statement in PowerShell to do this.
$file = "C:\Temp\SQL-backup.bak" If (Test-Path $file) { Echo "The file exists" }
This checks if the $Var is not $Null, an empty string, $False, 0, or an empty array.
The same thing works for string comparisons or arrays and returns True or False. E.g.
# Compare string $fruit = "Orange" $fruit -eq "orange" #Returns : True #Check if an array contains an element $fruits = @( 'apple', 'banana', 'mango', 'orange' ) If ("orange" -in $fruits) {"We found an orange fruit!"}
Please note that by default, the string comparison is case-insensitive.
Understanding the If Else Statement in PowerShell
If (condition) { # code to execute if the condition is true } Else { # code to execute if the condition is false }

Examples: How do you use the If-else statements in PowerShell?
Here is a basic example of how to use PowerShell If-Else statement:
$Age = 25 if ($Age -lt 18) { Write-Host "You are not old enough to vote." } else { Write-Host "You are old enough to vote." }
Here, we are checking if the value of the variable $age is less than 18. If it is, we display the message, “You are not old enough to vote.” Otherwise, we display the message, “You are old enough to vote”. So, the if and else statements can be used to handle both true and false conditions.

Here is another example of PowerShell If Else:
$computerName = "Server01" if (Test-Connection $computerName -Quiet) { Write-Host "The computer is online." } else { Write-Host "The computer is offline." }
In this example, we are checking if the computer with the name “Server01” is online. If it is, we display the message “The computer is online.” Otherwise, we display the message, “The computer is offline.”
To illustrate the practical use of if else statements in Windows PowerShell, let’s consider a real-world example. Suppose you have a script that checks the status of a specific service on a server. If the service is running, the script restarts the service. If the service is not running, the script starts the service.
$serviceName = "YourServiceName" $ServiceStatus = Get-Service $serviceName | Select-Object -ExpandProperty Status If ($serviceStatus -eq 'Running') { Restart-Service $ServiceName } Else { Start-Service $ServiceName }
In this script, we first use the Get-Service
cmdlet to retrieve the status of the service and store it in the $serviceStatus
variable. Then, we use an if else
statement to check if the service is running or not. If the service is running ($serviceStatus -eq 'Running'
), we restart the service using the Restart-Service
cmdlet. If the service is not running, we start the service using the Start-Service
cmdlet.
How to use ElseIf statements in PowerShell?
Here is a syntax of using the keyword ElseIf condition in an If-Else statement:
if ($condition1 -eq $true) { # code to execute if condition1 is true } elseif ($condition2 -eq $true) { # code to execute if condition1 is false and condition2 is true } else { # code to execute if condition1 and condition2 are false }
PowerShell ElseIf Statement Examples
Let’s look at some more examples of the PowerShell “ElseIf” statement in action:
$Value = 10 if ($value -lt 10) { Write-Host -f Yellow "The value is less than 10" } elseif ($value -gt 10) { Write-Host -f Cyan "The value is greater than 10" } else { Write-Host -f Green "The value is equal to 10" }

Here is another example:
#Get the Print Spooler service status $Status = Get-Service -Name Spooler if ($status -eq "Running") { Stop-Process -Name "ProcessName" } elseif ($status -eq "Stopped") { Start-Process -FilePath "C:\ProcessPath" } else { Restart-Service -Name "ServiceName" }
Nested If-Else statements in PowerShell
Nesting allows you to place a if
statement within another if
Statement. This enables the testing of multiple conditions in a hierarchical manner, further enhancing the decision-making capability of your scripts. Nested If-Else statements are used when you need to handle multiple conditions. You can nest If-Else statements inside each other to create an additional condition. Here is an example of a nested If-Else statement:
if ($condition1 -eq $true) { if ($condition2 -eq $true) { # code to execute if condition1 and condition2 are true } else { # code to execute if condition1 is true and condition2 is false } } else { # code to execute if condition1 is false }
$role = "admin" $permissions = "write" if (($role -eq "admin") -or ($role -eq "manager")) { if ($permissions -eq "write") { Write-Host "The user is allowed to perform the action." } else { Write-Host "The user does not have the required permissions." } } else { Write-Host "The user does not have the required role." }
Using If-Else statements with comparison operators
Comparison operators are used in If-Else statements to compare values. The most common comparison operators used in PowerShell are:
-eq
(equals)-ne
(not equals)-gt
(greater than)-lt
(less than)-ge
(greater than or equal to)-le
(less than or equal to)like
: Match a string using a wildcard-notlike
: Does not match a string using a wildcard-match
: Matches a specified regular expression (RegEx pattern)-notmatch
: Does not match a specified regular expression
You can use multiple comparison operators in a single If-Else statement by using logical operators such as -and
and -or
.
Here is an example:
$grade = 80 if ($grade -ge 90) { Write-Host "You got an A." } elseif ($grade -ge 80 -and $grade -lt 90) { Write-Host "You got a B." } else { Write-Host "You got a C or lower." }
In this example, we are using the “-ge” and “-lt” comparison operators to compare the value of the variable $grade. The first condition checks if the value is greater than or equal to 90, the second condition checks if the value is greater than or equal to 80 and less than 90, and the third condition executes if neither of the first two conditions is true.
Logical Operators AND-OR-NOT in IF statements
In addition to comparison operators, PowerShell offers logical statements that allow you to combine multiple conditions in your If Else statements. The most common logical operators include:
-and
: Logical AND, returns true if both conditions are true-or
: Logical OR, returns true if at least one condition is true-not
: Logical NOT, returns true if the condition is false
Here is an example:
$age = 25 $isCitizen = $true if ($age -ge 18 -and $isCitizen) { Write-Host "You are eligible to vote." } else { Write-Host "You are not eligible to vote." }
In this example, we are using the “and” logical operator to combine two conditions. The first condition checks if the value of the variable $age is greater than or equal to 18, and the second condition checks if the value of the variable $isCitizen is true. If both conditions are true, we display the message “You are eligible to vote.” Otherwise, we display the message, “You are not eligible to vote.” More on How to use Logical Operators in PowerShell?
Here is a simple menu example using If statements in PowerShell:
# Display menu to the user Do { Write-Host "-------------" Write-Host " Main Menu " Write-Host "-------------" Write-Host "1. Option 1" Write-Host "2. Option 2" Write-Host "3. Option 3" Write-Host "4. Exit" #Clear-Host $selection = Read-Host "Enter selection" if ($selection -eq 1) { Write-Host "You chose option 1" } elseif ($selection -eq 2) { Write-Host "You chose option 2" } elseif ($selection -eq 3) { Write-Host "You chose option 3" } elseif ($selection -eq 4) { Write-Host "Exiting" break } else { Write-Host "Invalid selection" } } while ($true)
Combining Multiple Conditions with Logical and Comparison Operators
In some cases, you may need to test multiple conditions simultaneously. This can be achieved using logical operators such as -and
, -or
, and -not
. Let’s look at an example that checks if a number is within a specific range.
$num = 15 if (($num -ge 10) -and ($num -le 20)) { Write-Host "$num is between 10 and 20" } else { Write-Host "$num is not between 10 and 20" }
Let’s see other examples:
# Check if num is equal to 5 OR 10 if ($num -eq 5 -or $num -eq 10) # Check if string is NOT equal to "Hello" if ($str -ne "Hello")
Best Practices and Tips for PowerShell If Statement
While if else statements are incredibly versatile and powerful, there are a few best practices to remember when using them in PowerShell.
- Use Functions for Multiple Lines of Code: If the action associated with your
if
orelse
statement includes multiple lines of code. Consider encapsulating that code in a function and calling the function from theif else
statement. This enhances the readability and maintainability of your scripts. - Choose Switch Over Multiple ElseIf: If you nest multiple
elseif
statements, consider using the PowerShell switch statement instead. Theswitch
statement is more efficient and provides cleaner code when dealing with multiple conditions. - Use Parentheses for Complex Conditions: If your condition involves multiple operators, use parentheses to group the operations. This makes your script more readable and ensures proper precedence of operations.
- Use descriptive variable names: Use variable names that describe the value being compared, rather than generic names like y.
- Usage of comparison operators where appropriate: Use comparison operators to compare values, rather than using the -match or -like operators.
- Be clear and concise in condition statements that are easy to read and understand.
- Indentation: Indent the code inside If-Else statements to make it easier to read and understand.
- Use comments: Add comments to your code to explain what it does and why.
- Using Ternary operators: Ternary operators are shorthand If-Else statements that allow you to execute a single line of code based on a condition.
- Test your code: Test your If-Else statements with different values to ensure they work as expected.
Troubleshooting common issues with If-Else statements in PowerShell
Common issues when writing If-Else statements in PowerShell include:
- Forgetting to use curly braces, Forgetting to close parentheses
- Using the wrong comparison operator. For example, use single = instead of -eq to check for equality.
- If the condition is not evaluated as true or false as expected, check the syntax and logic of the statement.
- Missing the – before comparison operators like -eq
- Checking strings without quotes around them
- Check that the code inside the if-else statement is correct. If the code is not executing as expected, check the logic of the code.
- If you are using multiple if-else statements, make sure that the conditions do not conflict with each other.
- Ensure that the variables used in the if-else statement are declared and assigned values before execution.
Wrapping up
Remember to use descriptive variable names, comparison operators, indentation, comments, and testing to ensure your If-Else statements work as expected.
How to use the Ternary operator in PowerShell?
PowerShell 7 Introduced the new syntax for ternary operators. The ternary operator is a simplified if-else statement. Here is an example with the Test-path cmdlet:$FileExists = (Test-Path -path "C:\Temp") ? "Path exists" : "Path not found"
How to Check for Empty Strings or Null Values in PowerShell?
Can you have an if statement inside an if statement PowerShell?
Yes, you can have an if statement inside an if statement in PowerShell. This is known as nested if statements. It allows you to add conditional logic to create more complex scripts, by evaluating multiple conditions.
How to check two conditions in if in PowerShell?
How do you write or condition in PowerShell?
What are the alternatives to if statements?
Some alternatives to if statements in PowerShell include switch statements, ternary operators, and using functions or modules to handle different conditions. These alternatives can provide more concise and efficient code in certain scenarios.
How do I use multiple if else in PowerShell?
To use multiple if and else statements in PowerShell, you can use multiple elseif statements or nest them! We explained examples of both approaches above.
Can you use == in PowerShell?
No, in PowerShell, you use -eq for equality comparison instead of ==.
How to check two conditions in if in PowerShell?
Syntax of Else If in PowerShell
if (condition1) {
# Code to execute if condition1 is true
} elseif (condition2) {
# Code to execute if condition2 is true
} else {
# Code to execute if none of the above conditions are true
}
Example of Else If in PowerShell
Let’s look at a practical example to understand how else if
works in PowerShell:
$number = 15
if ($number -lt 10) {
Write-Output "The number is less than 10."
} elseif ($number -lt 20) {
Write-Output "The number is between 10 and 19."
} else {
Write-Output "The number is 20 or greater."
}
Why Use Else If in PowerShell?
Using else if
statements in PowerShell scripts can make your code more readable and efficient. It allows you to handle multiple conditions without writing nested if
statements, which can become cumbersome and difficult to manage.
Common Use Cases for Else If in PowerShell
- Validating User Input: You can use
else if
statements to validate user input and provide appropriate feedback. - Error Handling: Use
else if
to handle different types of errors in your scripts. - Conditional Execution: Execute different blocks of code based on varying conditions.
Statistics on PowerShell Usage
- According to a survey by Stack Overflow, 35% of developers use PowerShell for scripting and automation.
- PowerShell is used by 70% of IT professionals for managing Windows environments.
Else If in PowerShell is Like a Traffic Light
Think of else if
statements in PowerShell as a traffic light system. The if
statement is the green light, allowing cars to go if the condition is met. The else if
statement is the yellow light, providing an alternative route if the green light condition is not met. Finally, the else
statement is the red light, stopping all other conditions and providing a default action.
FAQ Section
What is the difference between If and Else If in PowerShell?
The if
statement checks the initial condition, while the else if
statement checks an alternative condition if the initial condition is not met.
Can I use multiple Else If statements in PowerShell?
Yes, you can use multiple else if
statements to check various conditions in your script.
How do I handle errors using Else If in PowerShell?
You can use else if
statements to check for specific error conditions and handle them accordingly in your script.
Is Else If case-sensitive in PowerShell?
No, PowerShell is not case-sensitive, so elseif
, ElseIf
, and ELSEIF
are all valid.
Can I nest Else If statements in PowerShell?
External Links
- PowerShell Documentation – Official Microsoft documentation on PowerShell.
- PowerShell Else If Statement – Tutorial on using
else if
statements in PowerShell. - PowerShell Basics – A beginner’s guide to PowerShell on Pluralsight.
Question: When defining the Expression value for custom properties, can we include either a try/catch or an if condition to handle errors and/or capture details of errors for logging purposes, without messing up the expression value itself?
Start-Transcript -Path 'c:\temp\log.txt' -Force
## List of AD user objects
$OU = "OU=Users,DC=company,DC=com"
$Users = Get-ADUser -LDAPFilter '(&(objectCategory=Person)(sAMAccountName=*))' -SearchBase $OU -Properties *
## this array will make sense later...
$missingMgrs = [System.Collections.ArrayList]@()
## Defined properties through splatting:
$ChosenProperties = @{
"Property" = @(
# built-in attributes:
'Name', 'sAMAccountName', 'EmailAddress'
# custom attributes below:
@{
Label = "ManagerSAmAccountName"
Expression = {
Get-ADUser $_.Manager -Properties DisplayName |Select -Expand sAMAccountName
}
}
)
}
$Users | Select-Object @ChosenProperties
Stop-Transcript
An excerpt from the transcript might look like this:
Name sAMAccountName EmailAddress ManagerSAmAccountName
---- -------------- ------------ ---------------------
Person One pone [email protected] managera
Person Two ptwo [email protected] managerb
>> TerminatingError(Get-ADUser): "Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again."
Person Three pthree [email protected]
>> TerminatingError(Get-ADUser): "Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again."
Person Four pfour [email protected]
Person Five pfive [email protected] managera
Expression = {
if ($($_.Manager.Length) -gt 0) {
Get-ADUser $_.Manager -Properties DisplayName |Select -Expand sAMAccountName
} else {
$missingMgrs.Add("$($_.Name) is missing a manager.")
}
}
and at the end, just before stopping transcript:
Write-Output $missingMgrs
However, that generates the results like this:
Name sAMAccountName EmailAddress ManagerSAmAccountName
---- -------------- ------------ ---------------------
Person One pone [email protected] managera
Person Two ptwo [email protected] managerb
>> TerminatingError(Get-ADUser): "Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again."
Person Three pthree [email protected] 0
>> TerminatingError(Get-ADUser): "Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again."
Person Four pfour [email protected] 1
Person Five pfive [email protected] managera
[...]
Person Three is missing a manager.
Person Four is missing a manager.
Back to the original question: Is there a way to write a custom property using an if/else so that the Expression’s value gets evaluated only when the if condition is met?
Windows PowerShell — программа, который объединяет в себе командную оболочку и среду для написания сценариев. Она базируется на .NET и предоставляет средства для управления компьютером и автоматизации рутинных задач. Платформа обладает функциональностью полноценного объектно-ориентированного языка, включая поддержку переменных, функций, классов и объектов.
В отличие от многих других командных оболочек, PowerShell при работе оперирует не строками, а объектами. Это позволяет разрабатывать и применять сложные логические конструкции. Важно отметить, что интерпретатор PowerShell полностью совместим со стандартными командами cmd.exe и способен выполнять их функции без ограничений.
Взаимодействие с командами осуществляется в интерактивном режиме внутри терминала. Однако, если требуется сохранить используемый скрипт, более удобным вариантом станет использование среды ISE.
Windows PowerShell ISE представляет собой интегрированное средство разработки сценариев для языка PowerShell. Здесь можно создавать, сохранять и запускать скрипты с выделением синтаксиса, автоматическим дополнением, справочником команд и инструментами отладки. PowerShell ISE является легаси-инструментом, специфичным для версий языка до 5.1 включительно. В более поздних версиях предпочтение отдается универсальным интегрированным средам разработки с плагинами.
С начала 2016 года язык получил кросс-платформенную поддержку. Теперь его можно применять не только в операционных системах Windows 7, 8, 10, и 11, но и на macOS (начиная с версии 10.13), а также на различных популярных дистрибутивах Linux (подробная информация о совместимых дистрибутивах доступна в официальной документации).
Как открыть PowerShell в Windows
Как правило, PowerShell уже установлен на вашем компьютере по умолчанию. Однако, если по какой-то причине его нет, вы можете воспользоваться инструкциями, предоставленными Microsoft. В дополнение, в официальной документации имеются подробные руководства по установке на macOS и Linux.
PowerShell является независимым от версии операционной системы инструментом и работает одинаково стабильно как на Windows 10, так и на Windows Server.
Существует два основных метода для запуска PowerShell или PowerShell ISE в системе Windows: через меню «Пуск» и с помощью приложения «Выполнить».
- Для того чтобы открыть PowerShell через меню «Пуск», пройдите к папке Windows PowerShell, откройте её и выберите необходимое приложение. В этой директории доступны как 32-разрядные версии (отмечены как x86 в скобках), так и 64-разрядные версии терминала и ISE.

- Чтобы запустить PowerShell через приложение «Выполнить», используйте комбинацию клавиш Win + R. Когда появится окно, введите
powershell
илиpowershell ise
(в зависимости от того, какое приложение вам нужно) и нажмите кнопку ОК.

Команды (командлеты) PowerShell
В языке программы PowerShell команды носят название командлеты (от английского «cmdlet»). Все они формируются с использованием шаблона «Глагол-Существительное», или «Действие-Объект». Например, Get-Services
и Start-Process
. Благодаря такой структуре, можно легко понять предназначение команды, даже если вы с ней ещё не работали ранее.
Синтаксис командлетов
После имени самого командлета следует указание параметров и их значений. Между всеми частями команды следует проставлять пробелы. Вот пример синтаксиса командлета, который позволяет перейти в директорию C:\
:
Set-Location -LiteralPath C:\ -PassThru
Разберем его на составные части:
Set-Location
— буквально «вызвать команду». Этот командлет позволяет выполнять указанный блок сценария.-LiteralPath C:\
— здесь передаем блок сценария, в котором используется командаSet-Location
для перехода в каталогC:\
.-PassThru
— по умолчанию командлетInvoke-Command
не возвращает результат выполнения. Этот параметр указывает на необходимость вывода информации о местоположении, в которое был выполнен переход с помощью командыSet-Location
.

Важно отметить, что регистр букв в командах PowerShell не имеет значения. Таким образом, данную команду можно записать в виде заглавных букв, строчных букв или даже смешанного регистра, и она все равно будет выполняться:
sEt-loCATion -PATH c:\ -passthru
Когда в одной строке объединены несколько команд, они разделяются точкой с запятой
.;
Иногда команда может быть слишком длинной. Для разделения на несколько строк можно использовать символ обратного апострофа `
в месте переноса. Новую строку можно создать, нажав Shift + Enter (для переноса строки ниже текущей) или Ctrl + Enter (для переноса строки выше текущей).
Разделим предыдущую команду:
Set-Location ` -LiteralPath C:\ ` -PassThru

Алиасы
В процессе работы с терминалом иногда может быть неудобно постоянно вводить полные названия командлетов. Именно поэтому у наиболее часто используемых командлетов существуют псевдонимы (алиасы) — их сокращенные варианты.
Чтобы получить список доступных алиасов, вы можете воспользоваться командой Get-Alias
. Кроме того, данной команде также доступен псевдоним gal
.

Чтобы получить список алиасов для конкретного командлета, вы можете использовать параметр -Definition
. Пример:
Get-Alias -Definition Set-Location

Если вам нужно узнать полное название командлета по его алиасу, используйте параметр -Name
. Этот параметр необязателен, так как он является аргументом по умолчанию.
# Оба следующих варианта эквивалентны: Get-Alias -Name clear Get-Alias clear

Особенности обработки путей к каталогам
Для многих командлетов необходимо предоставить путь к файлу или каталогу. Это делается с использованием строки, например: C:\Windows\System32
.
Однако, если в пути встречается пробел или другой специальный символ, PowerShell будет рассматривать его как разделитель. Например:
# Следующая команда не будет выполнена корректно Set-Location C:\Program Files

PowerShell «воспринимает» пробел и интерпретирует его так, будто путь к папке закончился на слове Program
, а files
— это уже значение другого параметра.
Чтобы избежать подобных ситуаций, существует два метода:
- Экранировать символы с помощью обратного апострофа
`
:C:\Program` Files
. Однако это может быть неудобным, если путь длинный. - Поместить весь путь в одинарные или двойные кавычки:
'C:\Program Files'
или"C:\Program Files"
(желательнее использовать одинарные кавычки).
Кроме того, в PowerShell существуют сокращения для быстрого доступа к ближайшим директориям:
- Точка
.
указывает на текущий каталог. Например,Get-ChildItem .
позволяет просмотреть содержимое текущего местоположения. - Две точки
..
указывают на родительский каталог. Например,Set-Location ..
позволяет перейти к родительскому каталогу. Это может быть полезно, если вы находитесь в глубоко вложенной директории.
Большинство командлетов имеют параметры -Path
и -LiteralPath
, позволяющие указать путь к файлу или папке. Разница между ними заключается в том, что в -Path
можно включать переменные, в то время как —LiteralPath
интерпретирует символы буквально, даже если они содержат имя переменной.
Get-Help: как изучать новые командлеты
Для получения подробной информации о конкретном командлете воспользуйтесь командой Get-Help Название-Командлета
. Пример:
Get-Help Get-Childitem

У команды Get-Help
имеется несколько полезных параметров:
-Detailed
предоставляет более подробную справку по командлету.-Full
предоставляет полную справку.-Examples
демонстрирует примеры использования командлета.-Online
перенаправляет пользователя на веб-страницу с соответствующей документацией.
Объекты и конвейеры (пайплайны) в PowerShell
Когда вы работаете с командлетами в PowerShell, они возвращают не просто строки, а объекты — структуры данных, содержащие набор свойств и методов.
То, что отображается в терминале после выполнения команды в виде строки, на самом деле является визуальным представлением объекта. Программа PowerShell отображает определенные свойства объектов в виде таблицы, но далеко не все свойства могут быть отображены таким образом.
Аналогично тому, как командлеты могут возвращать объекты, они также могут принимать и обрабатывать их. Вы можете создать команду, которая возвращает объект, передать этот объект другому командлету, получить объект из него и так далее — этот процесс и называется конвейерами или пайплайнами.
Пример работы конвейера в PowerShell
Команда Get-Process
возвращает список запущенных процессов на компьютере. При передаче ей имени процесса (или шаблона, созданного с помощью регулярных выражений), команда выведет только соответствующие элементы списка.
Рассмотрим пример, где вызываем запущенный процесс PowerShell
:
Get-Process powershell

Мы получаем объект и таблицу, отображающую некоторые его свойства. Чтобы узнать все свойства и методы, давайте передадим этот объект командлету Get-Member
. Для этого используется конвейер:
Get-Process powershell | Get-Member

Команда Get-Member
получает объект от команды Get-Process
и выводит таблицу со всеми его свойствами и методами. Результат работы Get-Member
также представляет собой объект (точнее, список объектов), который можно передать по конвейеру дальше.
Допустим, нужно вывести только те строки, в которых MemberType
равно Property
. Для этого используем команду Where-Object
:
Get-Process powershell | Get-Member | Where-Object {$_.MemberType -eq 'Property'}

Команда Where-Object
последовательно обходит каждый объект, полученный от команды Get-Member
. Выражение в фигурных скобках — логическое:
$_
ссылается на текущий объект (то есть на отдельную строку в таблице);.MemberType
обращается к значению свойстваMemberType
в этом объекте;-eq
выполняет сравнение между выражением слева и выражением справа от него;'Property'
представляет значение, которое ожидаем увидеть у свойстваMemberType
.
Более подробно о логических выражениях рассказано ниже.
Форматирование таблиц с помощью конвейеров
Командлет Format-Table
в PowerShell предоставляет возможность настроить вывод таблицы в терминале: выбирать нужные свойства и методы, устанавливать ширину столбцов, группировать данные по нескольким таблицам и т. д.
Форматируем таблицу, полученную с помощью командлета Get-Member
. Следует использовать следующий синтаксис:
Get-Process powershell | Get-Member | Format-Table -AutoSize -Wrap -GroupBy MemberType -Property Name, Definition

Разберем параметры командлета Format-Table
:
-AutoSize
выравнивает ширину столбцов в соответствии с размерами их содержимого. Это позволяет оптимально использовать ширину экрана.-Wrap
переносит содержимое ячейки на новую строку, если оно не помещается в текущих размерах экрана. По умолчанию, если текст не помещается, он обрезается.-GroupBy
позволяет разделить одну таблицу на несколько, сгруппированных по значению определенного свойства. В данном случае, для каждого значенияMemberType
будет создана отдельная таблица.-Property
определяет, какие свойства объекта будут отображены в таблице в качестве столбцов. В данном примере, мы указали свойстваName
иDefinition
.
Эти параметры позволяют настраивать внешний вид таблицы, сделать вывод более читабельным и структурированным.
Сортировка таблиц с помощью конвейеров
Командлет Sort-Object
в PowerShell позволяет сортировать список объектов (таблицу) по значениям их свойств (столбцов). Давайте отсортируем результат, полученный с помощью командлета Get-Member
, по столбцу Name
в алфавитном порядке. Для этого воспользуемся параметром -Property
, который действует аналогично параметру у командлета Format-Table
:
Get-Process powershell | Get-Member | Sort-Object -Property Name

Командлет Sort-Object в PowerShell имеет также другие полезные параметры:
-Descending
сортирует объекты в порядке убывания. Например:
Get-Process powershell | Get-Member | Sort-Object -Property Name -Descending
-Unique
удаляет дубликаты и возвращает только уникальные объекты. Например:
Get-Process powershell | Get-Member | Sort-Object -Property Name -Unique
- Параметр
-Top
получает число N и отображает первые N объектов в таблице. Например:
Get-Process | Sort-Object -Property CPU -Top 10
- Параметр
-Bottom
получает число N и отображает последние N объектов в таблице. Например:
Get-Process | Sort-Object -Property Memory -Descending -Bottom 5
Эти параметры позволяют более гибко настраивать сортировку и отображение объектов в выводе.
Фоновое выполнение команд
Определенные задачи могут требовать значительного времени на выполнение. Примеры таких задач включают установку и обновление программного обеспечения или поиск файлов в обширной директории. Важно помнить, что во время выполнения одной команды в PowerShell нельзя вводить другие команды.
Рассмотрим пример: предположим, нужно найти файл powershell.exe
на всем диске C. Для этой цели воспользуемся командлетом Get-ChildItem
с параметром -Recurse
. Это позволит ему искать файл не только в текущем каталоге, но и во всех его подкаталогах.
Следует учитывать, что PowerShell может столкнуться с папками, к которым у него нет доступа. Чтобы обойти возможные ошибки, добавим параметр -ErrorAction SilentlyContinue
. Это означает, что в случае ошибки команда не будет генерировать уведомления, а просто продолжит выполнение.
Таким образом, данная ситуация выглядит следующим образом:
Get-ChildItem -Path C:\ -Name powershell.exe -Recurse -ErrorAction SilentlyContinue

Очевидно, что во время выполнения задачи, командная строка становится недоступной. Для принудительного прерывания выполнения задачи можно воспользоваться сочетанием клавиш Ctrl + C. Важно убедиться, что при этом ничего не выделено, чтобы избежать возможного восприятия компьютером как команды «Копировать».
Start-Job {Get-ChildItem -Path C:\ -Name powershell.exe -Recurse -ErrorAction SilentlyContinue}

Параллельно возможно выполнение любого числа фоновых задач. В дополнение к командлету Start-Job
, предназначенному для управления фоновыми задачами, существуют и другие командлеты:
Get-Job
предоставляет отчет о состоянии фоновых задач.Wait-Job
блокирует консоль до завершения фоновой задачи.Stop-Job
прекращает выполнение фоновой задачи.Receive-Job
выводит результаты выполнения фоновой задачи и очищает их из памяти. Для сохранения результатов в памяти используйте параметр-Keep
.
Опции Wait-Job
, Stop-Job
и Receive-Job
требуют указания имени Name
или идентификатора Id
конкретной задачи или задач (в случае нескольких). Это можно сделать непосредственно или в связке с командлетом Get-Job
.
Get-Job Job1

Работа с файлами
PowerShell предоставляет удобные средства для работы с файлами. Вот некоторые ключевые методы:
Для создания файла используйте командлет New-Item
с указанием пути к файлу:
New-Item -Path "C:\путь\к\файлу\новыйфайл.txt" -ItemType File
Чтобы записать данные в файл, используйте Out-File
или Set-Content
:
"Содержимое файла" | Out-File -FilePath "C:\путь\к\файлу\новыйфайл.txt" Set-Content -Path "C:\путь\к\файлу\новыйфайл.txt" -Value "Новое содержимое файла"
Для чтения содержимого файла в массив используйте Get-Content
:
$содержимое = Get-Content -Path "C:\путь\к\файлу\новыйфайл.txt"
Для получения информации о файле (размер, дата создания и др.) используйте Get-Item
:
$информацияОФайле = Get-Item -Path "C:\путь\к\файлу\новыйфайл.txt"
Для копирования файла в другое место используйте Copy-Item
:
Copy-Item -Path "C:\путь\к\файлу\новыйфайл.txt" -Destination "C:\путь\к\копия\новыйфайл.txt"
Для удаления файла воспользуйтесь командлетом Remove-Item
:
Remove-Item -Path "C:\путь\к\файлу\новыйфайл.txt" -Force
Помните, что операции удаления файлов необратимы, поэтому будьте осторожны при их использовании.
Работа в PowerShell ISE
Командная оболочка PowerShell представляет собой удобный инструмент для выполнения малых, кратких однострочных задач. Однако для создания и сохранения более сложных сценариев существует интегрированная среда разработки скриптов PowerShell ISE.
PowerShell ISE представляет собой инструмент, состоящий из трех основных панелей:
- Область скриптов в верхней части экрана, предназначенная для написания сценариев.
- Консольная область в нижней части экрана, которая функционирует как обычный терминал, позволяя вводить команды в интерактивном режиме.
- Панель команд в правой части экрана, предоставляющая полное руководство по командам PowerShell. В ней также есть конструктор, который помогает задать значения нужных параметров.
Комментарии в коде
Вот пример PowerShell скрипта с комментариями:
# Это комментарий в одну строку, начинается с символа '#' и продолжается до конца строки. # Пример переменной $имя = "John" $возраст = 30 # Вывод информации Write-Host "Привет, $имя! Тебе $возраст лет." # Это многострочный комментарий, который начинается с '<#' и заканчивается '#>'. <# Этот блок комментария может быть многострочным и располагаться на нескольких строках, чтобы объяснить более сложные участки кода. #> # Функция для сложения двух чисел function Сложить-Числа { param( [int]$число1, [int]$число2 ) $результат = $число1 + $число2 return $результат } # Вызов функции и вывод результата $результатСложения = Сложить-Числа -число1 5 -число2 7 Write-Host "Результат сложения: $результатСложения"
Хорошая практика — комментировать код таким образом, чтобы другие разработчики (или вы в будущем) могли легко понять, как работает код и какие цели преследовались при его написании.
Советы по написанию хорошего кода:
- Применяйте нотацию PascalCase для названий командлетов, функций, параметров, свойств, методов, переменных и классов. Разработчики Powershell выпустили для этого гайд. Не рекомендуется:
get-service
,Get-service
,GET-SERVICE
. Рекомендуется:Get-Service
. - Используйте полные названия командлетов. Алиасы удобны для интерактивного режима, но в скриптах они могут затруднить понимание. Не рекомендуется:
dir
,gci
,ls
. Рекомендуется:Get-ChildItem
. - Применяйте стиль One True Brace для форматирования вложенных блоков кода. Если вы используете фигурные скобки, внутренний код отделяется табуляцией (четыре пробела), а фигурные скобки размещаются следующим образом:
if ($var1 -eq $var2) { # Код внутри условия } else { # Код внутри else # Еще код внутри else }
Исключение: когда код внутри фигурных скобок небольшой, его можно записать в одну строку:
Get-ChildItem | Where-Object { $_.Length -gt 10mb }
Запуск скриптов
В PowerShell ISE имеется возможность выполнять код как целиком, так и частично, а также предоставляются инструменты для отладки. Скрипты сохраняются в файлах с расширением .ps1
. Однако запустить скрипт, просто дважды щелкнув по нему, не получится. Вместо этого вы можете нажать правую кнопку мыши и выбрать опцию Выполнить с помощью PowerShell
.
Также существует возможность запуска скрипта из оболочки. Например, предположим, у вас есть файл скрипта test_script.ps1 в каталоге C:\Scripts
. Вы можете выполнить его двумя способами:
- Используя команду
PowerShell -File C:\Scripts\test_script.ps1
из любого места. Это позволяет запустить скрипт, указав полный путь к файлу. - Используя команду
.\test_script.ps1
, если вы находитесь в каталогеC:\Scripts
. Это запустит скрипт, находясь в том же каталоге, что и файл скрипта.
Такие методы позволяют управлять выполнением PowerShell скриптов из разных мест и с разных уровней оболочки.
Политика выполнения. Как разрешить выполнения скриптов
По умолчанию запрещено выполнение файлов с PowerShell-скриптами, и это сделано с целью обеспечения безопасности. Вы можете узнать текущую политику выполнения с помощью командлета Get-ExecutionPolicy
. Вот какие варианты политики выполнения могут быть доступны:
- Restricted (Установлена по умолчанию) — запрещено выполнение любых скриптов. Это означает, что нельзя будет запустить ни один скрипт.
- AllSigned — разрешено выполнение только тех скриптов, которые были подписаны доверенным разработчиком. Это обеспечивает повышенный уровень безопасности, так как только подписанные и проверенные скрипты могут быть выполнены.
- RemoteSigned — разрешено выполнение подписанных доверенным разработчиком скриптов, а также собственных скриптов. Это предоставляет баланс между безопасностью и удобством, позволяя запускать свои скрипты.
- Unrestricted — разрешено выполнение любых скриптов без каких-либо ограничений. Это предоставляет наивысший уровень гибкости, но может повысить риск безопасности.
Чтобы ваши файлы с расширением .ps1 запускались, вам следует изменить политику выполнения на RemoteSigned. Для этого выполните следующие шаги:
- Откройте PowerShell от имени администратора. Для этого щелкните правой кнопкой мыши по значку PowerShell на панели задач или в меню «Пуск» и выберите «Запуск от имени администратора».
- В открывшемся окне PowerShell введите следующую команду и нажмите Enter:
Set-ExecutionPolicy RemoteSigned
- Подтвердите изменение политики выполнения, нажав клавишу
Y
(Yes).
Теперь вы сможете запускать свои файлы .ps1 без ограничений. Однако, имейте в виду, что изменение политики выполнения может повлиять на безопасность системы, поэтому будьте осторожны и убедитесь, что вы запускаете только те скрипты, которые вы знаете и доверяете.