PowerShell Basics

Basic use of PowerShell

  • type of data
    • Basic data types
      • Data type conversion
        • implicit type conversion
        • cast
    • Collection type
      • define collection
      • Add element
      • Remove element
    • dictionary type
      • definition dictionary
      • Add element
      • Remove element
      • access element
      • sort
    • object
      • Create object
      • Add attributes
      • Add method
      • transfer
  • Relational operators
    • arithmetic operators
    • comparison operator
      • Value size comparison
      • Array element comparison
      • text match comparison
      • Type comparison
    • Logical Operators
  • conditional judgment statement
    • Where-Object
      • grammar
      • example
    • if…elseif…else
      • grammar
      • example
      • ternary operator
        • grammar
        • example
    • switch
      • grammar
      • example
  • loop statement
    • For
      • grammar
      • example
    • ForEach-Object
      • grammar
      • example
    • While/Do While
      • grammar
      • example
  • function
    • Format
    • example
      • Functions that take arbitrary arguments
      • Functions that use named parameters
  • PowerShell common commands
  • script
    • Create script
      • Create scripts via editor (recommended)
      • Create script via redirect
    • run script
      • execution strategy
        • View execution strategy
        • Change execution strategy
    • Pass parameters to the script
      • Return all arguments via $args
      • Pass parameters using parameter names

Data type

Basic data types

PowerShell itself is developed based on .Net, so the basic data types in .Net can also be used in PowerShell, but [] is used in PowerShell to identify specific data types. For example [int], [bool], [string], etc.

Use -is in PowerShell to determine whether a variable is of the specified data type

# Define an integer variable named a
$a = 10
# You can specify the data type when defining the variable
[double]$b = 1.0

#The result is True
$a -is [int]

#The result is False
$a -is [double]

#The following statement will output that the type of variable b is Double type
Write-Host "b'Type is $($b.GetType())"
# output
# b'Type is double

Data type conversion

Implicit type conversion

PowerShell’s default data type conversion will use the type of the first variable as the target type, and the variable types of all subsequent operations will be converted to the first type.

$a = 1
$b = "2"

$a + $b
#The result returned at this time is 3, because the first variable a in the current operation is of type int, and all subsequent variables will be converted to int type.

$b + $a
#The result returned at this time is 21, because the first variable b in the current operation is of type string, and all subsequent variables will be converted to string type.

Forced type conversion

$a = 1
$b = "2"

# method one
[int]$b + $a

# Method Two
($b -as [int]) + $a

Collection type

Definition collection

To define a collection, we need to use the format of @(Object1, Object2, Object3...)

example:

# Define a collection named a
$a = @('a', 'b', 'c') # Equivalent to $a = 'a','b','c'

# If you need to define an empty collection, you must write it as
$b = @()

Add element

$a = @()

$a + = 'a'
$a + = 'b'

Write-Host $a
# Output:
# a b

Remove element

To remove elements, you need to use the Where query (abbreviated as ?) to find out the elements to be retained, and then reassign the retained element set to the variable

$a = @('a', 'b', 'c')

# remove c
# -ne means not equal to
# ? {$_ -ne 'c'} means that items not equal to 'c' are put into set a
$a = $a | ? {<!-- -->$_ -ne 'c'}

Write-Host $a
# Output:
# a b

Dictionary type

Definition dictionary

To define a dictionary, we need to use the format @{key1=value1;key2=value2;...}

example:

# Define a dictionary named a
$a = @{<!-- -->'a'=10; 'b'=23; 'c'=15} # Equivalent to $a = @{a=10; b=23; c=15}

# If you need to define an empty dictionary, you must write it as
$b = @{<!-- -->}

Add element

$a = @{<!-- -->}

$a.Add("a", "aaa")

Notice

Dictionary keys are not allowed to be repeated. If the same value already exists, an error will be reported when adding it.
You can first determine whether the key exists before adding it. The code is as follows

if (-not $a.ContainsKey("a"))
{<!-- -->
    $a.Add("a", "aaa")
}

Remove element

$a = @{<!-- -->"a"="aaa"; "b"="bbb"}

$a.Remove("a")

Access elements

$a = @{<!-- -->"a"="aaa"; "b"="bbb"}

$a["a"]
#The above method is the same as the following method
$a.a

Sort

$a.GetEnumerator() | Sort-Object Name

Notice:

Directly sorting the dictionary is invalid, you need to call the GetEnumerator() method first

Object

Create objects

An object can be created via New-Object.

Next we will create a Human object, which has three attributes: name, gender, age, and a SayHello method

$human = New-Object object

Add attributes

You can use Add-Memeber to add attributes, but its -MemberType needs to be set to NoteProperty

Add-Member -InputObject $human -Name Name -Value "xiaoming" -MemberType NoteProperty
Add-Member -InputObject $human -Name Sex -Value "Man" -MemberType NoteProperty
Add-Member -InputObject $human -Name Age -Value 18 -MemberType NoteProperty

# Equivalent to
# $human | Add-Member NoteProperty Name "xiaoming"

Add method

You can use Add-Memeber to add methods, but its -MemberType needs to be set to ScriptMethod

Add-Member -InputObject $human -Name SayHello -Value {<!-- -->"Hello!"} -MemberType ScriptMethod

# Equivalent to
# $human | Add-Member ScriptMethod SayHello {"Hello!"}

Call

# Call object properties
$human.Name
$human.Sex
$human.Age

# Call object method
$human.SayHello()

# The following method can also be executed successfully, but it will not execute the SayHello function, but will return the basic information of the method.
$human.SayHello

Relational operators

Arithmetic operators

Operator Meaning
+ Addition operation
Subtraction operation
* Multiplication Operation
/ Division operation
% Remainder operation

Comparison operators

Value size comparison

Operator Meaning
-[i|c]eq Equal
-[i|c]ne Not equal
-[i|c]gt Greater than
-[i|c]ge Greater than or equal to
-[i|c]lt less than
-[i|c]le Less than or equal

The prefix in square brackets is optional, i means case insensitive, c means case sensitive, the default is i

"a" -eq "A"
# output
#True

"a" -ceq "A"
# output
#False

If the left side of the expression is a set, PowerShell will compare the elements in the left array with the right elements one by one, and finally return a set of elements that meet the conditions.

12, 3, 21, 14, 9 -gt 10
# Equivalent to using the where statement below
# 12, 3, 21, 14, 9 | ? {$_ -gt 10}

# output
12
twenty one
14

Array element comparison

Operator Meaning
-contains Contains
-notcontains Does not contain
12, 3, 21, 14, 9 -contains 3
# output
#True

12, 3, 21, 14, 9 -contains 4
# output
#False

12, 3, 21, 14, 9 -notcontains 4
# output
#True

Text matching comparison

Operator Meaning
-like match
-notlike not match
-match match
-notmatch not match

-like and -notlike use character + wildcard * for matching
-match and -notmatch use regular expression for matching

"Hello world" -like "llo"
# output
#False

"Hello world" -like "*llo"
# output
#False

"Hello world" -like "*llo*"
# output
#True

"Hello world" -notlike "*llo"
# output
#True

"Hello world" -notlike "*llo*"
# output
#False

"Hello world" -match "^[a-zA-Z] + \sworld$"
# output
#True

"Hello world" -match "^[a-zA-Z] + world$"
# output
#False

"Hello world" -notmatch "^[a-zA-Z] + \sworld$"
# output
#False

Type comparison

Operator Meaning
-is is
-isnot is not
1 -is [int]
# output
#True

1 -isnot [int]
# output
#False

Logical operators

Operator Meaning
-not No, you can also use!
-and and
-or or
-xor XOR
-not $True
# output
#False

!$True
# output
#False

$True -and $False
# output
#False

$True -and $True
# output
#True

$True -or $True
# output
#True

$True -or $False
# output
#True

$False -or $False
# output
#False

$False -xor $False
# output
#False

$True -xor $False
# output
#True

Conditional judgment statement

Where-Object

Grammar

Collection/Dictionary/... | Where-Object/? {<!-- -->Judgment Statement}

Example

1,2,3,4,5 | ? {<!-- -->$_ -lt 3}
# output
# 1
# 2

# The following example is used to obtain stopped services
Get-Service | Where-Object {<!-- -->$_.Status -eq "Stopped"}
# Equivalent to the following
Get-Service | Where-Object Status -eq "Stopped"
Get-Service | where Status -eq "Stopped"
Get-Service | ? Status -eq "Stopped"

if…elseif…else

Grammar

if (<test1>)
    {<!-- --><statement list 1>}
[elseif (<test2>)
    {<statement list 2>}]
[else
    {<statement list 3>}]

Example

if ($a -gt 2) {<!-- -->
    Write-Host "The value $a is greater than 2."
}
elseif ($a -eq 2) {<!-- -->
    Write-Host "The value $a is equal to 2."
}
else {<!-- -->
    Write-Host ("The value $a is less than 2 or" +
        " was not created or initialized.")
}

Ternary operator

PowerShell 7.0 introduces the ternary operator

Grammar

<condition> ? <if-true> : <if-false>

Example

$message = (3 -ge 1) ? "3" : "1"

Notice

If an error is reported, you can check the powershell version through $psversiontable

switch

Grammar

Switch (<test-expression>)
{<!-- -->
    <result1-to-be-matched> {<!-- --><action>}
    <result2-to-be-matched> {<!-- --><action>}
}

Example

switch (3)
{<!-- -->
    1 {<!-- -->"It is one."}
    2 {<!-- -->"It is two."}
    3 {<!-- -->"It is three."}
    4 {<!-- -->"It is four."}
}
# output
# It is three.

switch (4, 2)
{<!-- -->
    1 {<!-- -->"It is one." }
    2 {<!-- -->"It is two." }
    3 {<!-- -->"It is three." }
    4 {<!-- -->"It is four." }
    3 {<!-- -->"Three again."}
}
# output
# It is four.
# It is two.

switch (4, 2)
{<!-- -->
    1 {<!-- -->"It is one."; Break}
    2 {<!-- -->"It is two." ; Break }
    3 {<!-- -->"It is three." ; Break }
    4 {<!-- -->"It is four." ; Break }
    3 {<!-- -->"Three again."}
}
# output
# It is four.

Loop statement

For

Grammar

For (;<test1>;) {<!-- --><statement list 1>}

Example

For($i = 1; $i -lt 5;$i + + ) {<!-- -->Write-Host $i }
# output
# 1
# 2
#3
#4

ForEach-Object

Grammar

Collection/Dictionary/... | ForEach-Object -Process {<!-- -->Execution Statement}
# Equivalent to
Collection/Dictionary/... | ForEach-Object {<!-- -->Execution Statement}
Collection/Dictionary/... | Foreach {<!-- -->Execution Statement}

Example

30000, 56798, 12432 | ForEach-Object -Process {<!-- -->$_/1024}
# output
# 29.296875
#55.466796875
#12.140625

While / Do While

Grammar

do {<!-- --><statement list 1>} while (<test1>)

while (<test1>) {<!-- --><statement list 1>}

Example

$i = 1
do {<!-- -->$i + = 1;Write-Host $i } while ($i -lt 5)
# output
# 2
#3
#4
#5

$i = 1
while ($i -lt 5){<!-- -->
    $i + = 1
    Write-Host $i
}
# output
# 2
#3
#4
#5

Notice

If you want to skip the current loop, you can use continue. If you want to end the current loop, you can use break

Function

Format

Function function name (parameter) {<!-- -->
    statement
}

The function can confirm the received parameters through $args

Example

Function using arbitrary parameters

# Define function
function SayHello {<!-- -->
    if ($args.Count -eq 0){<!-- -->"No argument"}
    else{<!-- -->
        $args | foreach{<!-- -->$_}
    }
}

# Call functions
SayHello
# output
# No argument

SayHello xiaoming
# output
#xiaoming

Function using named parameters

# Define function
function SayHello($name) {<!-- -->
    return "Hello " + $name
}

# Call functions
SayHello -name xiaoming
# output
#Hello xiaoming

#Define a function with default parameters
function SayHello($name="xiaowang") {<!-- -->
    return "Hello " + $name
}
# Call functions
SayHello -name xiaoming
# output
#Hello xiaoming
SayHello
# output
#Hello xiaowang

PowerShell common commands

PowerShell (command line) Description
Get-ChildItem Gets items and subkeys in one or more specified locations.
Get-Clipboard Get the contents of the clipboard.
Get-ComputerInfo Get the combined object of system and operating system properties.
Get-Content Gets the content of the item at the specified location.
Get-Item Gets the item at the specified location.
Get-ItemProperty Get the properties of the specified item.
Get-Location Get information about the current working location or a location stack.
Get-Process Get the process running on the local computer.
Get-Service Get the service on the computer.
Get-TimeZone Get the current time zone or a list of available time zones.
Get-Command List available commands.
Get-Help Print the command’s documentation on the console.
Set-Clipboard Set the contents of the clipboard.
Set-Content Writes new content or replaces existing content in the file.
Set-Item Changes the value of an item to the value specified in the command.
Set-ItemProperty Create or change the property value of an item.
Set-Location Sets the current working location to the specified location.
Set-Service Start, stop and suspend services and change the properties of services.
Set-TimeZone Sets the system time zone to the specified time zone.
Clear-Host Clear the screen.
Copy-Item Copy files and folders to another location.
Move-Item Move files and folders to a new location.
Remove-Item Delete a file or folder.
Rename-Item Rename a single file, folder, hard link or symbolic link.
Write-Output Gets the items and subitems in one or more specified positions.
Stop-Process Get items and subkeys in one or more specified locations.
Invoke-WebRequest Get web page content on the Internet.

Script

Create script

Create scripts via editor (recommended)

You can create a file with the suffix ps1 directly through the editor, and then you can start writing scripts

Create script via redirect

You can redirect the script statements to be executed to a script file through the console

'Hello PowerShell' > MyScript.ps1

# A slightly longer script can use the following method
@'
Hello
PowerShell
'@ > MyScript.ps1

Run script

Whether the script can be executed depends on the execution policy of PowerShell (Only administrators can modify the execution policy). PowerShell generally prohibits script execution.

Execution strategy

View execution policy

To view the execution policy of PowerShell, you can view it through the Get-ExecutionPolicy command

Policy Description
Unrestricted Unsigned scripts can run
Restricted/Default No script execution is allowed
RemoteSigned There are no restrictions on local scripts, but scripts from the network must be signed
AllSigned Requires all scripts and configuration files to be signed Signed by a trusted publisher, including scripts written on the local machine
Bypass Does not block any operations and does not cause any warnings or prompts

Change execution policy

To change the execution policy of PowerShell, you can view it through the Set-ExecutionPolicy command

#Run with administrator privileges
Set-ExecutionPolicy Bypass

If modified to the correct execution strategy, directly enter the script name to run

Pass parameters to the script

Return all parameters via $args

# Run script
.\MyScript.ps1 "Hello"

At this point, you can get the incoming parameters Hello through $args

Pass parameters using parameter names

param($Name,$Age)

"Name=$Name"
"Age=$Age"
.\MyScript.ps1 -Name xiaoming -Age 18
# Equivalent to
.\MyScript.ps1 -Age 18 -Name xiaoming
.\MyScript.ps1 xiaoming 18

# output
# Name=xiaoming
# Age=18

You can also bind other information such as parameter binding types.

param(
    [string]$Name=$(throw "Parameter missing: -Name Name"),
    [int]$Age=$(throw "Parameter missing: -Age x as number")
)

"Name=$Name"
"Age=$Age"
.\MyScript.ps1 xiaoming 18
# output
# Name=xiaoming
# Age=18

# An error will be reported below
.\MyScript.ps1 xiaoming
# output
# Parameter missing: -Age x as number

# An error will be reported below because the type is restricted.
.\MyScript.ps1 18 xiaoming

If you want to learn more about PowerShell, you can refer to PowerShell Commands and Scripts (1) – Understanding PowerShell. I think this blogger writes better than me.

For more detailed knowledge, please refer to the Microsoft official website – What is PowerShell?