PowerShell Practical Applications
PowerShell is not just a terminal tool; it is one of the most comprehensive automation platforms in the Windows environment.
This section will usethree 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
1. Daily Management Task Automation
1.1 Batch File Renaming
Requirement:
All files in a directory.txtare renamed to the format of a unified prefix plus a sequence number, such as:log_001.txt、log_002.txtetc.
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.ps1a file, and then use Task Scheduler to run it periodically.
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"
2. Remote Management
PowerShell Remoting Basics
PowerShell Remoting is a mechanism for executing remote commands via WinRM.
Enable remote functionality (run as administrator):
Enable-PSRemoting -Force
UsageInvoke-CommandExecute Remote Commands
Invoke-Command -ComputerName "Server01" -ScriptBlock {
Get-Service -Name "W32Time"
}
Supports batch execution on multiple hosts:
$servers = @("Server01", "Server02")
Invoke-Command -ComputerName $servers -ScriptBlock {
Get-Process | Where-Object { $_.CPU -gt 100 }
}
Remote Session Management
Create a session:
$session = New-PSSession -ComputerName "Server01"
Enter the session:
Enter-PSSession $session
Execute commands:
Invoke-Command -Session $session -ScriptBlock { Get-Date }
Close the session:
Remove-PSSession $session
Security Considerations
- Use HTTPS instead of HTTP (configure certificates)
- Avoid using plaintext passwords; it is recommended to use credential objects:
$cred = Get-Credential
Invoke-Command -ComputerName "Server01" -Credential $cred -ScriptBlock { hostname }
3. Integration with Other Technologies
PowerShell and .NET Framework
PowerShell has built-in access to .NET class libraries and can call almost all .NET APIs.
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 REST APIs
Example: Call a JSON API 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 (Example: SQL Server)
$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: Use the Excel COM object to write data
$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
4. Summary
| Application Type | Practical Use | Technical Points |
|---|---|---|
| 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 | Batch operations on multiple hosts, remote sessions | Invoke-Command, PSSession |
| Technical Integration | Integration with REST APIs, databases, and Excel | Invoke-RestMethod, COM, ADO.NET |
| .NET Support | Call underlying APIs to implement extended functionality | Use .NET class libraries |