Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PowerShell Scripting

PowerShell Scripting


Introduction

PowerShell is a powerful command-line scripting language that can run commands interactively and compose them into script files for complex automation tasks.

This article will guide you step by step through the fundamentals of PowerShell script development, including:


I. Getting Started with PowerShell Scripts

Creating script files (.ps1)

A PowerShell script file is a plain text file with .ps1 as its extension, containing a set of PowerShell commands to execute.

Example: hello.ps1

# hello.ps1
Write-Output "Hello from PowerShell script!"

Can be created with any text editor (VS Code recommended) .ps1 files.

Execution Policy

For security reasons, Windows by default does not allow script execution, so you need to set the execution policy.

View the current policy:

Get-ExecutionPolicy

Temporarily set to allow local scripts to run:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

RemoteSigned: Local scripts run without a signature, but downloaded scripts must be signed by a trusted publisher.

Methods for running scripts

Run from the command line:


.\hello.ps1

Run by specifying the PowerShell executable:


powershell.exe -File .\hello.ps1
pwsh.exe -File .\hello.ps1   # PowerShell 7+

Right-click "Run with PowerShell" (requires policy configuration)

Parameter passing and handling

You can define how the script receives external parameters:

Example: A parameterized script greet.ps1

param (
    [string]$name,
    [int]$age
)

Write-Output "你好,$name,你的年龄是 $age 岁。"

Passing arguments at runtime:

.\greet.ps1 -name "小明" -age 18

It also supports default values and parameter validation:

param (
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$City = "Beijing"
)

II. Using Functions

Function definition and calling

function Say-Hello {
    Write-Output "Hello from function"
}

Say-Hello

Parameter declaration and validation

Functions can also take parameters using the param block to define:

function Add-Numbers {
    param (
        [int]$a,
        [int]$b
    )
    return $a + $b
}

Add-Numbers -a 3 -b 5  # 输出 8

You can also use positional parameters:

function Add {
    param ($x, $y)
    $x + $y
}
Add 10 20

Return value handling

A PowerShell function returns all output by default (including Write-Output).

it is recommended to use return to return explicitly:

function Get-Square {
    param ([int]$num)
    return $num * $num
}

$result = Get-Square -num 6
Write-Output $result

Function scope

Variables defined inside a function are local by default:

function Demo-Scope {
    $message = "Hello"
}
Demo-Scope
Write-Output $message  # 无法访问

To access a variable from outside, use a scope prefix:

$global:x = 5

III. Modular Development

What is a PowerShell module

A module is a collection of functions, scripts, and resources used to organize code and facilitate reuse.

Common module types:

Importing and using modules

Use Import-Module Import a module:

Import-Module MyModule.psm1

View loaded modules:

Get-Module

Call functions from a module:

Say-Hello

Introduction to PowerShell Gallery

PowerShell Gallery is PowerShell's official module repository where you can download and install thousands of modules.

Example of installing a module:

Install-Module -Name PSReadLine

Updating a module:

Update-Module PSReadLine

Creating a simple custom module

Create a MyModule.psm1 file and add functions:

# MyModule.psm1
function Greet-User {
    param ([string]$name)
    Write-Output "欢迎你,$name"
}

Import and call it in a script:

Import-Module .\MyModule.psm1
Greet-User -name "小红"

Tip: You can place the module file in $env:PSModulePath so the system recognizes it automatically.


IV. Summary

Content Description
.ps1 file PowerShell script extension that stores commands
param Used to define script/function parameters
Set-ExecutionPolicy Controls whether a script is allowed to run
function Encapsulates reusable code and improves structural clarity
Module (.psm1) Organizes multiple functions for portability
PowerShell Gallery Official module repository for downloading third-party modules