PowerShell Basic Syntax

PowerShell is not just a command-line tool; it is also a complete scripting language. Learning its basic syntax is an important first step, just like learning a new programming language.

This section will introduce in detail the most basic syntax elements in PowerShell, including variables, comments, data types, operators, conditional statements, loop structures, and more, laying a solid foundation for writing scripts later.


1. Comments

Comments in PowerShell are similar to those in most programming languages. They are used to explain code and are not executed.

Single-line comments use#at the beginning:

# 这是一个单行注释
Write-Output "Hello, PowerShell"

Multi-line comments are enclosed with<#and#>wrapped in:

<#
This is a multi-line comment
Can be used for documentation
#>

2. Variables

Defining Variables

In PowerShell, variables start with the$$ symbol, without needing to declare the type in advance:

$name = "Alice"
$age = 25

Using Variables

Write-Output "Name: $name"

You can also use string interpolation:

Write-Output "User: $($name), Age: $($age)"

3. Data Types

PowerShell is a weakly typed language, but every variable has a corresponding .NET type underneath.

Type Example
String $str = "Hello"
Integer $num = 123
Decimal $pi = 3.14
Boolean $isTrue = $true
Array $arr = @(1, 2, 3)
Hash Table $h = @{Name="Tom"; Age=30}

You can use.GetType()to view the variable type:

$str.GetType().Name   # String

4. Operators

Category Example Description
Arithmetic Operations + - * / % Common mathematical operations
Comparison Operations -eq -ne -lt -gt Equal, not equal, less than, greater than
Logical Operations -and -or -not Logical operators
String -like -match -replace Pattern matching and replacement
Containment Operations -in -contains Collection checks

Example:

5 -eq 5       # True
"abc" -like "a*"  # True

5. Conditional Statements

if Statement

if ($age -ge 18) {
    Write-Output "成年人"
} else {
    Write-Output "未成年人"
}

if-elseif-else

if ($score -ge 90) {
    "优秀"
} elseif ($score -ge 60) {
    "及格"
} else {
    "不及格"
}

6. Loop Structures

for Loop

for ($i = 1; $i -le 5; $i++) {
    Write-Output "第 $i 次循环"
}

foreach Loop

$colors = @("Red", "Green", "Blue")
foreach ($color in $colors) {
    Write-Output "颜色:$color"
}

while Loop

$count = 0
while ($count -lt 3) {
    Write-Output $count
    $count++
}

7. Function Definitions

PowerShell allows you to define custom functions, with the syntax as follows:

function Say-Hello {
    param([string]$name)
    Write-Output "Hello, $name!"
}

Say-Hello -name "PowerShell"

You can also use a more concise syntax:

function Square($x) { return $x * $x }
Square 5  # 输出 25

8. Error Handling

Use thetry {} catch {}block to handle statements that may cause errors:

try {
    Get-Item "C:\NotExist.txt"
} catch {
    Write-Output "找不到文件"
}

9. Basic Script File Format

PowerShell script files use the.ps1.ps1 extension. You can create them using VS Code or Notepad:

# hello.ps1
$name = "World"
Write-Output "Hello, $name"

Run it in PowerShell:

.\hello.ps1

Note: If the script fails to execute, check the execution policy (Get-ExecutionPolicy). If necessary, useSet-ExecutionPolicyto allow scripts to run.

Other Extensions