PowerShell Scripting
Introduction
PowerShell is a powerful command-line scripting language. Not only can it run commands interactively, but it can also combine commands into script files to accomplish complex automation tasks.
This article will guide you step by step through the basic skills of PowerShell script development, including:
- How to create and run
.ps1scripts - How to define and use functions
- How to carry out modular development and reuse your script logic
1. Getting Started with PowerShell Scripts
Creating Script Files (.ps1)
PowerShell script files are plain text files with the.ps1extension, containing a set of PowerShell commands to execute.
Example: hello.ps1
# hello.ps1 Write-Output "Hello from PowerShell script!"
You can use any text editor (VS Code recommended) to create.ps1files.
Execution Policy
For security reasons, Windows by defaultdoes not allow running scripts, 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 can run without a signature, but downloaded scripts must be signed by a trusted publisher.
Running Scripts
Run from the command line:
.\hello.ps1
Specify the PowerShell executor to run:
powershell.exe -File .\hello.ps1 pwsh.exe -File .\hello.ps1 # PowerShell 7+
Right-click "Run with PowerShell" (requires policy settings)
Passing and Handling Parameters
You can define ways to accept external parameters in a script:
Example: Script with parameters greet.ps1
param (
[string]$name,
[int]$age
)
Write-Output "你好,$name,你的年龄是 $age 岁。"
Pass parameters when running:
.\greet.ps1 -name "小明" -age 18
Also supports default values and parameter validation:
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$City = "北京"
)
2. Using Functions
Function Definition and Invocation
function Say-Hello {
Write-Output "Hello from function"
}
Say-Hello
Parameter Declaration and Validation
Functions can also have parameters, defined using aparamblock:
function Add-Numbers {
param (
[int]$a,
[int]$b
)
return $a + $b
}
Add-Numbers -a 3 -b 5 # 输出 8
Positional parameters can also be used:
function Add {
param ($x, $y)
$x + $y
}
Add 10 20
Return Value Handling
PowerShell functions return all output by default (includingWrite-Output)。
It is recommended to usereturnto 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 variables by default:
function Demo-Scope {
$message = "Hello"
}
Demo-Scope
Write-Output $message # 无法访问
To access variables from outside, you can use scope prefixes:
$global:x = 5
3. Modular Development
What is a PowerShell Module
A module is a collection of multiple functions, scripts, and resources, used to organize code and facilitate reuse.
Common module types:
- Script modules (
.psm1) - Manifest modules (
.psd1) - Binary modules (.dll)
Importing and Using Modules
UseImport-Moduleto import a module:
Import-Module MyModule.psm1
View loaded modules:
Get-Module
Call functions in a module:
Say-Hello
Introduction to PowerShell Gallery
PowerShell GalleryIt is the official module repository for PowerShell, where you can download and install thousands of modules.
Example of installing a module:
Install-Module -Name PSReadLine
Update a module:
Update-Module PSReadLine
Creating a Simple Custom Module
Create a new 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 module files into paths in
$env:PSModulePathso the system automatically recognizes them.
4. Summary
| Content | Description |
|---|---|
.ps1File |
PowerShell script extension, storing commands |
param |
Used to define script/function parameters |
Set-ExecutionPolicy |
Controls whether scripts are allowed to run |
| Function | Encapsulates reusable code, improving structural clarity |
Module (.psm1) |
Organizes multiple functions, enabling portability |
| PowerShell Gallery | Official module repository, where you can download third-party modules |