PowerShell Practical Applications
PowerShell is not just a terminal tool; it is one of the most comprehensive automation platforms on Windows.
This section will use three major categories of practical application scenariosto demonstrate PowerShell's powerful capabilities in daily management, remote operations, and cross-technology integration:
- Daily management task automation
- Remote management
- Integration with other technologies
I. Daily Management Task Automation
1.1 Batch file renaming
Requirement:
Rename all files in a directory .txt to a unified prefix plus sequence number format, e.g.:log_001.txt, log_002.txt , etc.
Example code:
$files = Get-ChildItem -Path "D:\Logs" -Filter "*.txt"
$count = 1
foreach ($file in $files) {
$newName = "log_{0:D3}.txt" -f $count
Rename-Item -Path $file.FullName -NewName $newName
$count++
}
Scheduled cleanup of temporary files
Example: Delete temporary files older than 7 days
$targetPath = "C:\Windows\Temp"
Get-ChildItem -Path $targetPath -Recurse |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
Remove-Item -Force -Recurse
It is recommended to save the script as a .ps1 file and run it periodically using Task Scheduler.
System information collection script
$info = [PSCustomObject]@{
ComputerName = $env:COMPUTERNAME
OSVersion = (Get-CimInstance Win32_OperatingSystem).Caption
Uptime = ((Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToString()
CPU = (Get-CimInstance Win32_Processor).Name
RAM_GB = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)
}
$info | Format-List
Log analysis and report generation
$logPath = "C:\inetpub\logs\LogFiles\W3SVC1\*.log"
$lines = Get-Content $logPath | Where-Object { $_ -match "500" }
$lines.Count
$lines | Out-File "C:\Reports\error_500_report.txt"
II. Remote Management
PowerShell Remoting Basics
PowerShell Remoting is the mechanism for executing remote commands via WinRM.
Enable remoting (run as administrator):
Enable-PSRemoting -Force
Use Invoke-Command Execute remote commands
Invoke-Command -ComputerName "Server01" -ScriptBlock {
Get-Service -Name "W32Time"
}
Supports batch execution across multiple hosts:
$servers = @("Server01", "Server02")
Invoke-Command -ComputerName $servers -ScriptBlock {
Get-Process | Where-Object { $_.CPU -gt 100 }
}
Remote session management
Establish a session:
$session = New-PSSession -ComputerName "Server01"
Enter a session:
Enter-PSSession $session
Execute a command:
Invoke-Command -Session $session -ScriptBlock { Get-Date }
Close a session:
Remove-PSSession $session
Security considerations
- Use HTTPS instead of HTTP (configure certificates)
- Avoid plaintext passwords; use credential objects:
$cred = Get-Credential
Invoke-Command -ComputerName "Server01" -Credential $cred -ScriptBlock { hostname }
III. Integration with Other Technologies
PowerShell and the .NET Framework
PowerShell has built-in access to .NET class libraries and can call almost any .NET API.
Example: Get the MD5 value of a file
function Get-FileHashMD5 {
param ([string]$path)
$md5 = [System.Security.Cryptography.MD5]::Create()
$bytes = [System.IO.File]::ReadAllBytes($path)
$hash = $md5.ComputeHash($bytes)
return ([BitConverter]::ToString($hash)).Replace("-", "")
}
Get-FileHashMD5 "D:\file.zip"
Calling a REST API
Example: Call a JSON interface to get weather information
$response = Invoke-RestMethod -Uri "https://api.weatherapi.com/v1/current.json?key=APIKEY&q=Beijing"
$response.location.name
$response.current.temp_c
Database connection basics (using SQL Server as an example)
$connectionString = "Server=localhost;Database=TestDB;Integrated Security=True"
$query = "SELECT TOP 10 * FROM Users"
$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$command = $connection.CreateCommand()
$command.CommandText = $query
$connection.Open()
$reader = $command.ExecuteReader()
while ($reader.Read()) {
Write-Output $reader["UserName"]
}
$connection.Close()
Interacting with Office applications
Example: Write data using an Excel COM object
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$workbook = $excel.Workbooks.Add()
$sheet = $workbook.Worksheets.Item(1)
$sheet.Cells.Item(1, 1) = "Name"
$sheet.Cells.Item(1, 2) = "Score"
$sheet.Cells.Item(2, 1) = "Alice"
$sheet.Cells.Item(2, 2) = 95
IV. Summary
| Application type | Practical use | Technical point |
|---|---|---|
| Local automation | Batch renaming, file cleanup, system information | File system, timers, objects |
| Log analysis | Check error logs and generate reports | Text processing, filtering, exporting |
| Remote operations | Multi-host batch operations, remote sessions | Invoke-Command, PSSession |
| Technology integration | Working with REST APIs, databases, and Excel | Invoke-RestMethod, COM, ADO.NET |
| .NET support | Call low-level APIs to extend functionality | Use .NET class libraries |