Search code examples
powershellpowershell-remoting

Setting Power Plan on multiple server using Powershell


I want to set "High Performance" powerplan on multiple server machines. I've the following script which is running fine when I execute this on the servers one by one.

Set-PowerPlan "High performance"

function Set-PowerPlan {

[CmdletBinding(SupportsShouldProcess = $True)]

param (

    [ValidateSet("High performance", "Balanced", "Power saver")]

    [ValidateNotNullOrEmpty()]

    [string] $PreferredPlan = "High Performance"
      )

Write-Host "Setting power plan to `"$PreferredPlan`""

$guid = (Get-WmiObject -Class Win32_PowerPlan -Namespace root\cimv2\power -Filter "ElementName='$PreferredPlan'").InstanceID.ToString()

$regex = [regex]"{(.*?)}$"

$plan = $regex.Match($guid).groups[1].value

powercfg -S $plan

$Output = "Power plan set to "

$Output += "`"" + ((Get-WmiObject -Class Win32_PowerPlan -Namespace root\cimv2\power -Filter "IsActive='$True'").ElementName) + "`""

 Write-Host $Output
}

How to pass a list of servers to this script so that the power plan is set on all servers recursively?


Solution

  • Just add the computername parameter to your function and Get-WmiObject inside it. Also I used this solution to launch process remotely.

    function Set-PowerPlan {
    
        [CmdletBinding(SupportsShouldProcess = $True)]
        param (
    
            [ValidateSet("High performance", "Balanced", "Power saver")]
            [ValidateNotNullOrEmpty()]
            [string]$PreferredPlan = "High Performance",
            [string]$ComputerName = $env:COMPUTERNAME
        )
    
        Write-Host "Setting power plan to `"$PreferredPlan`""
    
        $guid = (Get-WmiObject -Class Win32_PowerPlan -Namespace root\cimv2\power -Filter "ElementName='$PreferredPlan'" -ComputerName $ComputerName).InstanceID.ToString()
    
        $regex = [regex]"{(.*?)}$"
    
        $plan = $regex.Match($guid).groups[1].value
    
        #powercfg -S $plan
        $process = Get-WmiObject -Query "SELECT * FROM Meta_Class WHERE __Class = 'Win32_Process'" -Namespace "root\cimv2" -ComputerName $ComputerName
        $results = $process.Create("powercfg -S $plan")
    
        $Output = "Power plan set to "
        $Output += "`"" + ((Get-WmiObject -Class Win32_PowerPlan -Namespace root\cimv2\power -Filter "IsActive='$True'" -ComputerName $ComputerName).ElementName) + "`""
    
        Write-Host $Output
    }
    
    $ServerList = @(
        'CompName1',
        'Compname2'
    )
    
    foreach ($server in $ServerList ) {
        Set-PowerPlan -PreferredPlan 'High performance' -ComputerName $comp
    }