Powershell Practice
PowerShell is not just a terminal tool; it is one of the most comprehensive automation platforms in the Windows environment.\n\nThis section will demonstrate PowerShell's powerful capabilities in daily management, remote operations, and cross-technology integration through **three major categories of practical application scenarios**:\n\n* Daily management task automation\n* Remote management\n* Integration with other technologies\n\n* * *\n\n## OneγDaily Management Task Automation\n\n### 1.1 Batch File Renaming\n\n#### Requirement:\n\nRename all `.txt` files in a directory to a unified prefix plus serial number format, such as: `log_001.txt`, `log_002.txt`, etc.\n\n#### Example Code:\n\n$files = Get-ChildItem -Path "D:\\Logs" -Filter "*.txt" $count = 1foreach ($file in $files) { $newName = "log_{0:D3}.txt" -f $count Rename-Item -Path $file.FullName -NewName $newName $count++}\n### Scheduled Temporary File Cleanup\n\n#### Example: Delete temporary files older than 7 days\n\n$targetPath = "C:\\Windows\\Temp"Get-ChildItem -Path $targetPath -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse\nIt is recommended to save the script as a `.ps1` file and use Task Scheduler to execute it regularly.\n\n### System Information Collection Script\n\n$info = @{ 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 = ::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)} $info | Format-List\n\n* * *\n\n### Log Analysis and Report Generation\n\n$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"\n\n* * *\n\n## TwoγRemote Management\n\n### PowerShell Remoting Basics\n\nPowerShell Remoting is a mechanism for remote command execution through WinRM.\n\nEnable remote functionality (run as administrator):\n\nEnable-PSRemoting -Force\n### Using `Invoke-Command` to Execute Remote Commands\n\nInvoke-Command -ComputerName "Server01" -ScriptBlock { Get-Service -Name "W32Time"}\nSupports batch execution on multiple hosts:\n\n$servers = @("Server01", "Server02")Invoke-Command -ComputerName $servers -ScriptBlock { Get-Process | Where-Object { $_.CPU -gt 100 }}\n### Remote Session Management\n\nCreate a session:\n\n$session = New-PSSession -ComputerName "Server01"\nEnter the session:\n\nEnter-PSSession $session\nExecute commands:\n\nInvoke-Command -Session $session -ScriptBlock { Get-Date }\nClose the session:\n\nRemove-PSSession $session\n### Security Considerations\n\n* Use HTTPS instead of HTTP (configure certificates)\n* Avoid using plaintext passwords; recommend using credential objects:\n\n$cred = Get-CredentialInvoke-Command -ComputerName "Server01" -Credential $cred -ScriptBlock { hostname }\n\n* * *\n\n## ThreeγIntegration with Other Technologies\n\n### PowerShell and .NET Framework\n\nPowerShell has built-in access to .NET class libraries and can invoke almost all .NET APIs.\n\n#### Example: Get File MD5 Hash\n\nfunction Get-FileHashMD5 { param ($path) $md5 = [System.Security.Cryptography.MD5]::Create() $bytes = [System.IO.File]::ReadAllBytes($path) $hash = $md5.ComputeHash($bytes) return (::ToString($hash)).Replace("-", "")}Get-FileHashMD5 "D:\\file.zip"\n### Calling REST APIs\n\n#### Example: Call JSON API to get weather information\n\n$response = Invoke-RestMethod -Uri "https://api.weatherapi.com/v1/current.json?key=APIKEY&q=Beijing" $response.location.name $response.current.temp_c\n### Database Connection Basics (SQL Server Example)\n\n$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} $connection.Close()\n\n* * *\n\n### Interacting with Office Applications\n\n#### Example: Write Data Using Excel COM Object\n\n$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\n\n* * *\n\n## FourγSummary\n\n| Application Type | Practical Use | Technical Points |\n| --- | --- | --- |\n| Local Automation | Batch renaming, file cleanup, system information | File system, timers, objects |\n| Log Analysis | Check error logs and generate reports | Text processing, filtering, exporting |\n| Remote Operations | Multi-host batch operations, remote sessions | `Invoke-Command`, `PSSession` |\n| Technology Integration | Integration with REST API, databases, Excel | `Invoke-RestMethod`, COM, ADO.NET |\n| .NET Support | Call underlying APIs for extended functionality | Using .NET class libraries |
YouTip