Saturday, 1 December 2018

Get remote PC sleep settings

The following PowerShell code is designed to get the sleep settings of a remote PC. It was developed due to a number of PCs dropping their network connections when left idle (eg user in a meeting), which subsequently caused issues then accessing filestores (needing a restart to resolve). The tricky part was converting the hexadecimal into a 16-base decimal so you have something that makes sense on-screen. The tool can ultimately be incorporated as a module so you can call it straight from a PowerShell console.

I will publish my tool for remotely disabling the sleep settings in my next post.

function Get-SleepSettings {
Gets remote PC(s) Sleep settings.
Get-SleepSettings queries the active Power Scheme and returns
the AC (Mains) & DC (Battery) Sleep values in minutes.
.PARAMETER ComputerName
PC name(s) to query.

Specify this switch to create a text log file of the PC(s)
that could not be queried.
When used with -LogErrors, specifies the file path and name
to which the failed PC(s) will be written. Defaults to
current Powershell directory.
Get-SleepSettings -ComputerName pc123
Get-SleepSettings -ComputerName pc123, pc456 -Verbose

                    HelpMessage="Computer name")]

        [string]$ErrorLog = (Get-Location).Path,

    BEGIN {
        Write-Verbose "Error log will be $ErrorLog"

        Write-Verbose 'Beginning PROCESS block'

        ForEach ($computer in $ComputerName) {

            #Run the below command on the remote PC
            Invoke-Command -ComputerName $computer -ScriptBlock {
                #Enable Verbose logging

                #Get active PC power scheme (eg 'High performance' or 'Balanced')
                $scheme = (Get-WmiObject -Namespace Root\CIMV2\power -Class win32_powerplan  -Filter  isActive='true' ). ElementName
                Write-Verbose "Power scheme is $scheme"

                #Query active power scheme for Sleep setting
                $settingindex = powercfg.exe /query scheme_$scheme sub_sleep standbyidle | Where-Object {$_ -Like "*Setting Index*"}

                #For each power scheme (AC/DC) convert hexadecimal to 16-base decimal for seconds
                ForEach ($setting in $settingindex) {
                    Write-Verbose "Getting ready to split and convert $setting"
                    $power = $setting.split()[5]
                    $hex = $setting.split()[9]
                    $minutes = [Convert]::toint16("$hex",16) / 60

                    If ($minutes -eq 0) {
                        Write-Host "$env:computername Sleep setting for $power is Never"
                    Else {
                    Write-Host "$env:computername Sleep setting for $power is $minutes minutes"

            Write-Verbose 'End of function'
    END {}

Get Remote PC Sleep Settings.ps1

No comments:

Post a Comment