我刚刚开始使用 Powershell。我有一个 bat 文件,它简单地启动以下 PowerShell 脚本,然后每 5 秒重新显示我感兴趣的服务的状态。它工作正常(尽管我可以使用一些关于如何使这个更清洁的指示),除了每次重新绘制屏幕时都会出现短暂的烦人闪烁。因此,我想将其更改为睡眠间隔为 1 秒或 500 毫秒,但仅在内容更改时才进行重新绘制。或者,如果更容易无条件地重新绘制 dos 屏幕,而不会导致它闪烁,那么我也会对这个解决方案感到满意。另外请帮我清理代码。到目前为止,我很害怕 PowerShell 中的函数、变量等,因为当我尝试使用 C 系列/Python 语法和构造时,PS 经常对我大喊大叫。
# When you run this script, it will show a simple window with the status of the services;
# Do we want to XYZ as well?
# To assign $true value, use:
#PowerShell.exe .\ShowServices.ps1 -showXYZ:$true
#param([switch]$showXYZ=$false)
param([switch]$showXYZ=$true)
# Build a regex for services
$servicesRegex = "Microsoft.*|Network.*"
if ($showXYZ -eq $true) { $servicesRegex = $servicesRegex + "|XYZ.*" }
# Controlling the appearance of the window
$pshost = get-host
$pswindow = $pshost.ui.rawui
$newsize = $pswindow.buffersize
$newsize.height = 3000
$newsize.width = 50
$pswindow.buffersize = $newsize
$newsize = $pswindow.windowsize
$newsize.height = 10
$newsize.width = 50
$pswindow.windowsize = $newsize
$global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
#$global:ComputerName = gc env:computername
#$pswindow.WindowTitle = "Service statuses for {0} on {1}." -f $CurrentUser.Name, $ComputerName
$pswindow.WindowTitle = "Service statuses for {0}." -f $CurrentUser.Name
# Clear the screen once
clear
# Formatting details.
[int]$global:len1 = 35
[int]$global:len2 = 8
[int]$global:sleepInterval = 5 #seconds - I want this to be more frequent, but not annoying.
function printHeader
{
Write-Host("") # Blank line
[string]$line = "{0,-$global:len1} {1,-$global:len2}" -f "Service Name", "Status"
Write-Host $line
Write-Host("_" * $global:len1 + " " + "_" * $global:len2)
}
function printService($serviceObject)
{
[string]$foreColor = "yellow" # Default color, if neither Stopped nor Running
if ($serviceObject.status -eq "Stopped") {$foreColor = "red" }
if ($serviceObject.status -eq "Running") {$foreColor = "green" }
[string]$outStr = "{0,-$global:len1} {1,-$global:len2}" -f $serviceObject.displayname, $serviceObject.status
Write-Host $outStr -foregroundcolor $foreColor #-backgroundcolor white
}
# The meat of it.
while($true)
{
printHeader
Get-Service | Where-Object {$_.name -match $servicesRegex} | ForEach-Object { printService($_) }
Start-Sleep -s $global:sleepInterval # Sleep x seconds
clear
}