Getting PowerShell to work with Home Assistant

Posted by Jon Bullen on 2018-06-06
Estimated Reading Time 1 Minutes
Words 247 In Total

I wanted to turn on and off my office lamp from my desktop, sure I can use a switch but it is hooked up to Home Assistant so lets make it automatic! The main scenario was to toggle it at 10pm so when I get distracted it will let me know the time. You can use this for just about anything and at some point I will add more functions. Here is the snippet for now. You can set the values of global in your profile or in the launching script. As long as they are set this will work.

Script

Just past this into a file and run after updating the password, URL for your Home Assistant installation and then the entity id.

function Set-HomeAssistantAccess($AccessKey, $BaseUrl) {
    $Global:HomeAssistantAccessKey = $AccessKey
    $Global:HomeAssistantBaseUrl = $BaseUrl
    $Global:HomeAssistantHeader = @{ "x-ha-access" = $AccessKey; "Content-Type" = "application/json"}
}

function Set-HomeAssistantSwitchState {
    param (
        [String] $Entity,
        [ValidateNotNullOrEmpty()]
        [ValidateSet('On', 'Off')]
        [String] $State
    )

    $body = @{entity_id = $Entity} | ConvertTo-Json
    switch ($State) {
        "On" { Invoke-RestMethod -Method POST -Uri "$Global:HomeAssistantBaseUrl/services/switch/turn_on" -Headers $Global:HomeAssistantHeader -Body $body }
        "Off" { Invoke-RestMethod -Method POST -Uri "$Global:HomeAssistantBaseUrl/services/switch/turn_off" -Headers $Global:HomeAssistantHeader -Body $body }
        Default {}
    }
}

Set-HomeAssistantAccess -AccessKey "youraccesskey" -BaseUrl "https://yourdomainorip/api"
Set-HomeAssistantSwitchState -Entity "switch.yourlightentityid" -State On
Set-HomeAssistantSwitchState -Entity "switch.yourlightentityid" -State Off

Home Assistant


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you!