当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 更多 PowerShell 监控提示

作者:精品下载站 日期:2024-12-14 07:53:47 浏览:15 分类:玩电脑

更多 PowerShell 监控提示


哇。你们都喜欢 PowerShell 提示还是什么?我的显示向上/向下信息的提示很受欢迎。再多几个怎么样?正如我在上一篇文章中提到的,对于 PowerShell 提示功能来说,性能非常关键。我尝试了多种不同的技术,我认为使用运行空间和同步哈希表是最好的方法。考虑到这一点,这里还有一些 PowerShell 提示函数。

首先是一个提示,显示一台或多台远程计算机上 C: 驱动器的可用磁盘空间百分比。我正在使用 Get-Volume 来检索此信息。在我之前的函数中,我对计算机名称进行了硬编码。在此版本中,我将它们放在脚本文件夹中的文本文件中。在 Do 循环中,我获取列表,过滤掉空白行并修剪空格。

$computers = Get-Content -Path c:\scripts\watch.txt | where-object {$_ -match $_} |
foreach-object {$_.trim()}
$results = $computers | ForEach-Object {
try {
    $c = Get-Volume -DriveLetter c -CimSession $_ -ErrorAction Stop |
        Add-Member -MemberType ScriptProperty -Name PctFree -Value {($($this.SizeRemaining) / $($this.size)) * 100 -as [int]} -Force -passthru
    $val = $c.PctFree
}
Catch {
    $val = '??'
}

现在我可以通过修改文本文件来动态更改提示。首次加载提示时,哈希表没有值,因此我显示“工作中”。一旦有数据,提示就会反映可用空间的百分比。

[玩转系统] 更多 PowerShell 监控提示

因为我假设磁盘空间不会快速变化,所以运行空间中的循环每分钟仅运行一次。与我的其他提示函数一样,此代码位于 GitHub 上。

SpacePrompt.ps1:

function prompt {

    Try {
        Get-Variable -Name rsHash -Scope global -ErrorAction Stop | Out-Null
    }
    Catch {
        #create the runspace and synchronized hashtable
        $global:rsHash = [hashtable]::Synchronized(@{Computername = $env:computername; results = ""; date = (Get-Date)})
        $newRunspace = [runspacefactory]::CreateRunspace()
        #set apartment state if available
        if ($newRunspace.ApartmentState) {
            $newRunspace.ApartmentState = "STA"
        }
        $newRunspace.ThreadOptions = "ReuseThread"         
        $newRunspace.Open()
        $newRunspace.SessionStateProxy.SetVariable("rsHash", $rsHash)  

        $pscmd = [PowerShell]::Create().AddScript( {  

                do {
                    #define the list of computers to test
                    #filter out blank lines and trim any spaces to clean up names.
                    $computers = Get-Content -Path c:\scripts\watch.txt | where-object {$_ -match $_} |
                        foreach-object {$_.trim()}
                    $results = $computers | ForEach-Object {
                        try {
                            $c = Get-Volume -DriveLetter c -CimSession $_ -ErrorAction Stop |
                                Add-Member -MemberType ScriptProperty -Name PctFree -Value {($($this.SizeRemaining) / $($this.size)) * 100 -as [int]} -Force -passthru
                            $val = $c.PctFree
                        }
                        Catch {
                            $val = '??'
                        }
                        [pscustomobject]@{
                            Computername = $_.toupper()
                            PctFree      = $val
                        }
                    }

                    $global:rsHash.results = $results
                    $global:rsHash.date = Get-Date
                    #set a sleep interval between tests
                    Start-Sleep -Seconds 60
                } while ($True)

            })

        $pscmd.runspace = $newrunspace
        [void]$psCmd.BeginInvoke()

    } #catch

    Write-Host "[" -NoNewline
  
    if ($global:rshash.results) {
        $global:rshash.results | Sort-Object -Property Computername |
            ForEach-Object {
            if ($_.pctfree -eq '??') {
                $fg = "magenta"
            }
            elseif ($_.pctfree -le 20) {
                $fg = "red"
            }
            elseif ($_.pctfree -le 50) {
                $fg = "yellow"
            }
            else {
                $fg = "green"
            }
            Write-Host $_.computername -NoNewline
            Write-Host " $($_.pctfree)% " -ForegroundColor $fg -NoNewline
        } #foreach data item
    } #if results  
    else {
        Write-Host "working..." -NoNewline -ForegroundColor Cyan
    }

    Write-Host "]" -NoNewline

    "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
}

但是,等等还有更多!显示可用内存百分比的变体怎么样?此版本还使用我的计算机列表。但为了提高效率,我为每台计算机创建 PSSession。这使我能够运行 Invoke-Command,以更有效的方式通过 Get-CimInstance 从 Win32_OperatingSystem 类获取信息。我遇到的问题是服务器宕机或不可用。在我的函数中,我删除损坏的 PSSession,并为列表中尚未打开会话的计算机创建新会话。我没有考虑到从列表中删除计算机并在提示中删除会话。如果需要,您可以添加该代码。或者,只需更新列表并删除 $rshash 变量。或者重新启动 PowerShell 会话。

[玩转系统] 更多 PowerShell 监控提示

该功能可以在此处在线找到。

MemUsagePrompt.ps1:

function prompt {

    Try {
        Get-Variable -Name rsHash -Scope global -ErrorAction Stop | Out-Null
    }
    Catch {
        #create the runspace and synchronized hashtable
        $global:rsHash = [hashtable]::Synchronized(@{Computername = $env:computername; results = ""; date = (Get-Date)})
        $newRunspace = [runspacefactory]::CreateRunspace()
        #set apartment state if available
        if ($newRunspace.ApartmentState) {
            $newRunspace.ApartmentState = "STA"
        }
        $newRunspace.ThreadOptions = "ReuseThread"         
        $newRunspace.Open()
        $newRunspace.SessionStateProxy.SetVariable("rsHash", $rsHash)  

        $pscmd = [PowerShell]::Create().AddScript( {                      
                    
                #define a pssession option to speed up connections
                $opt = New-PSSessionOption -OpenTimeout 1000 -MaxConnectionRetryCount 1

                do {
                    #define the list of computers to test
                    #filter out blank lines and trim any spaces to clean up names.
                    $computers = Get-Content -Path c:\scripts\watch.txt | 
                        Where-Object {$_ -match $_} |
                        Foreach-Object {$_.trim()}

                    #make sure there are sessions for all computers in the list
                    $computers | Where-Object {(get-pssession).where( {$_.state -eq 'opened'}).computername -notcontains $_} |
                        ForEach-Object {
                        New-PSSession -ComputerName $_ -SessionOption $opt
                        }
                    #remove broken sessions
                    Get-PSSession | Where-Object {$_.state -eq 'broken'} | Remove-PSSession
                   
                    $data = Invoke-command -ScriptBlock {
                        Get-CimInstance -ClassName win32_operatingsystem -Property TotalVisibleMemorySize, FreePhysicalMemory
                    } -Session (Get-PSSession) 

                    $results = $data | Sort-Object -Property PSComputername |
                        ForEach-Object {
                        [int]$val = ($_.FreePhysicalMemory / $_.TotalVisibleMemorySize) * 100

                        [pscustomobject]@{
                            Computername = $_.PSComputername.toUpper()
                            PctFree      = $val
                        }
                    }

                    $global:rsHash.results = $results
                    $global:rsHash.date = Get-Date
                    #set a sleep interval between tests
                    Start-Sleep -Seconds 10
                } while ($True)

            })

        $pscmd.runspace = $newrunspace
        [void]$psCmd.BeginInvoke()

    } #catch
      
    Write-Host "FreeMem"
    Write-Host "[" -NoNewline

    if ($global:rshash.results) {
        $global:rshash.results | Sort-Object -Property Computername |
            ForEach-Object {
            if ($_.pctfree -le 30) {
                $fg = "red"
            }
            elseif ($_.pctfree -le 60) {
                $fg = "yellow"
            }
            else {
                $fg = "green"
            }
            Write-Host " $($_.computername) " -NoNewline
            Write-Host "$($_.pctfree)%" -ForegroundColor $fg -NoNewline
        } #foreach data item
    } #if results  
    else {
        Write-Host "working..." -NoNewline -ForegroundColor Cyan
    }
        
    Write-Host " ]" -NoNewline

    "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
    
}

我正在研究一项更全面的遥测提示。我喜欢突破界限,这绝对是极端的。感谢您的热情。享受。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯