SwitchKing PoSH

Changelog

  • 2013-10-06 (Rikard Ronnkvist) First release
  • 2013-10-06 (Rikard Ronnkvist) Added info on relative commands.

Requirements

SwitchKing.psm1

#requires -version 3
<#
Version history:
    2013-10-06   Rikard Ronnkvist   First release.
    2013-10-06   Rikard Ronnkvist   Added info on relative commands.

Usage:
   PS:>Import-Module SwitchKing
   PS:>Get-Command -Module SwitchKing
   PS:>Get-Help Get-SwitchKingInfo -Examples
   PS:>Get-Help Set-SwitchKingDevice -Examples

Not sure where to save the file?
   PS:>Write-Host (Join-Path (Split-Path -Path $profile -Parent) "Modules\SwitchKing\SwitchKing.psm1")
#>
[cmdletbinding()]
PARAM ()

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#region Helpers
Function Get-SKHelperValidateMinutesParam {
<#
.SYNOPSIS
    Helper to validate input in functions
#>
    PARAM (
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] $Minutes = 60,
        [Parameter(Mandatory=$false)] [switch] $GetParams
    )

    $validParams = @(
        [int] (New-TimeSpan (Get-Date) (Get-Date).AddHours(1)).TotalMinutes,
        [int] (New-TimeSpan (Get-Date) (Get-Date).AddHours(3)).TotalMinutes,
        [int] (New-TimeSpan (Get-Date) (Get-Date).AddHours(6)).TotalMinutes,
        [int] (New-TimeSpan (Get-Date) (Get-Date).AddHours(12)).TotalMinutes,
        [int] (New-TimeSpan (Get-Date) (Get-Date).AddHours(24)).TotalMinutes,
        [int] (New-TimeSpan (Get-Date) (Get-Date).AddDays(2)).TotalMinutes,
        [int] (New-TimeSpan (Get-Date) (Get-Date).AddDays(7)).TotalMinutes,
        [int] (New-TimeSpan (Get-Date) (Get-Date).AddDays(30)).TotalMinutes,
        [int] (New-TimeSpan (Get-Date) (Get-Date).AddYears(1)).TotalMinutes
    )

    if ($GetParams.IsPresent) {
        Return $validParams | Sort-Object
    } else {
        $MinutesOk = $false
        $validParams | Foreach-Object {
            If ($Minutes -like $_) { $MinutesOk = $true }
        }

        Return $MinutesOk
    }
}
Function Get-SKHelperValidateCommandParam {
<#
.SYNOPSIS
    Helper to validate input in functions
#>
    PARAM (
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] $Command = "",
        [Parameter(Mandatory=$false)] [switch] $GetParams
    )
    $validParamsDevices = @(
        "TurnOn",
        "TurnOff",
        "Synchronize",
        "CancelSemiauto",
        "TurnOnFake",
        "TurnOfFfake",
        "Dim/0",
        "Dim/10",
        "Dim/20",
        "Dim/30",
        "Dim/40",
        "Dim/50",
        "Dim/60",
        "Dim/70",
        "Dim/80",
        "Dim/90",
        "Dim/100",
        "DimFake/0",
        "DimFake/10",
        "DimFake/20",
        "DimFake/30",
        "DimFake/40",
        "DimFake/50",
        "DimFake/60",
        "DimFake/70",
        "DimFake/80",
        "DimFake/90",
        "DimFake/100",
        "Synchronize"
    )
    $validParamsOther = @(
        "AddValue?Value=*",
        "SetValueRelative?Value=*&Action=*&MinValue=*&MaxValue=*",
        "AddFutureValue?Value=*&TimeStamp=*",
        "CommandQueue?Operation=*&Target=*",
        "Activate",
        "EntityLogentries?Maxcount=*&NewerThan=*",
        "EntityLogentries/Latest"
    )

    if ($GetParams.IsPresent) {
        Return $validParamsDevices | Sort-Object
    } else {
        $CommandOk = $false
        $validParamsDevices | Foreach-Object {
            If ($Command -like $_) { $CommandOk = $true }
        }

        $validParamsOther | Foreach-Object {
            If ($Command -like $_) { $CommandOk = $true }
        }

        Return $CommandOk
    }
}

Function Get-SKHelperValidateRelativeCommandParam {
<#
.SYNOPSIS
    Helper to validate input in functions
#>
    PARAM (
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] $Command = "",
        [Parameter(Mandatory=$false)] [switch] $GetParams
    )
    $validParams = @(
        "inc",
        "increase",
        "add",
        "plus",
        "dec",
        "decrease",
        "subtract",
        "minus"
    )
    if ($GetParams.IsPresent) {
        Return $validParams | Sort-Object
    } else {
        $CommandOk = $false
        $validParams | Foreach-Object {
            If ($Command -like $_) { $CommandOk = $true }
        }

        Return $CommandOk
    }
}


Function Get-SKHelperUrlEncodedString {
<#
.SYNOPSIS
    Helper to URL encode a string
#>
    PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] [string] $inputString
    )

    [Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
    Return [web.httputility]::urlencode($inputString.Trim())
}

Function Get-SKHelperRest {
<#
.SYNOPSIS
    Helper to get SwitchKing info via REST
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true)]  [string] $RestCall,
        [Parameter(Mandatory=$true)]  [string] $ArrayName,
        [Parameter(Mandatory=$false)] [string] $ArrayLoop = ""
	)

    $xml = Invoke-SKHelperRawRestCall -restCall $RestCall -SwitchKing $SwitchKing

    if ($xml -eq $false) {
        $info = $false
    } else {
        $info = @()

        if ($ArrayLoop -eq "" ) {
            $xml."$($ArrayName)" | ForEach-Object {
                $info += $_
            }
        } else {
            $xml."$($ArrayName)"."$($ArrayLoop)" | ForEach-Object {
                $info += $_
            }
        }
    }

    Return $info
}

Function Set-SKHelperRest {
<#
.SYNOPSIS
    Helper to set SwitchKing info via REST
#>
    PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [string] $restCall
    )

    $xml = Invoke-SKHelperRawRestCall -restCall "$($restCall)" -SwitchKing $SwitchKing

    If ( [string]$xml.string."#text" -eq "OK" ) {
        Return $true
    } else {
        Write-Verbose "Error calling SwitchKing: $($xml.string.'#text')"
        Return $false
    }
}

Function Add-SKHelperRest {
<#
.SYNOPSIS
    Helper to add data to SwitchKing via REST
#>
    PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [string] $restCall
    )

    $xml = Invoke-SKHelperRawRestCall -restCall "$($restCall)" -SwitchKing $SwitchKing

    Return $xml.RESTOperationResult
}

Function Invoke-SKHelperRawRestCall {
<#
    .SYNOPSIS
        Helper to talk to REST-API
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
		[string][alias("REST", "Call")] $restCall,
        [switch] $Binary
	)

    TRY {
        # Compose URL
        $url = "$($SwitchKing.URL)/$($restCall)"

        # Set credentials
        $skCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $SwitchKing.User, $SwitchKing.SecurePassword

        # Run the web request        
        $webRequest = Invoke-WebRequest -Uri $url -Credential $skCredentials -Method Get -ContentType "application/x-www-form-urlencoded"

        if ($Binary.IsPresent) {
            Return $webRequest
        } else {
            # Decode html in response
            [System.Reflection.Assembly]::LoadWithPartialName("System.web")
            $webRequest = [string] $webRequest
            $webRequest = [system.web.httputility]::htmldecode( $webRequest )
        
            # Return as XML
            Return  $webRequest
        }
    }
    CATCH {
        Write-Verbose "Error calling SwitchKing: $($error[0])"
        Return $false
    }

}

#endregion Helpers
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#region Generic

Function Get-SwitchKingInfo {
<#
    .SYNOPSIS
        Returns an object with all connection and server information needed for SwitchKing-CMD'lets
    .DESCRIPTION
        The function will test a connection to SwitchKing. If connection is OK it will return some information about the server and the credentials beeing used.
    .EXAMPLE
        $MySkConnection = Get-SwitchKingInfo -ServerName "server.home.local" -User "MyUser" -Password "SecretPassword"
        Using Plain Text password
    .EXAMPLE
        $MySkConnection = Get-SwitchKingInfo -ServerName "server.home.local" -User "MyUser" -SecurePassword (Read-Host -Prompt "Enter password" -AsSecureString)
        Gives the user a prompt to enter password
    .PARAMETER ServerName
        Name or IP to server
    .PARAMETER Port
        The port number to use
    .PARAMETER User
        Username defined in SwitchKing
    .PARAMETER Password
        Password defined in SwitchKing as Plain Text
    .PARAMETER SecurePassword
        Password defined in SwitchKing as Secure String
#>
  	PARAM (
		[Parameter(Mandatory=$false)][alias("Server", "IP")][ValidateNotNullOrEmpty()] [string] $ServerName = "localhost",
        [Parameter(Mandatory=$false)][ValidateRange(1,65535)] [int] $Port = 8800,
        [Parameter(Mandatory=$true) ][ValidateNotNullOrEmpty()] [string] $User,
        [Parameter(Mandatory=$false) ][alias("Pass", "PlainTextPassword")] [string] $Password = "",
        [Parameter(Mandatory=$false) ][alias("SecurePass")] [SecureString] $SecurePassword = $null
	)

    if ($Password -eq "" -and $SecurePassword -eq $null) {
        Throw "Missing Password or SecurePassword!"
    }

    # Plain text is used if SecurePassword isnt available
    if ($SecurePassword -eq $null) {
        $SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
    }

    $SwitchKing = [PSCustomObject] @{
        Url = "http://$($serverName):$($port)"
        User = $User
        SecurePassword = $SecurePassword
    }

    Write-Verbose "Testing secure connection to $($SwitchKing.url)"
    $SystemSettings = Get-SwitchKingSystemSettings -SwitchKing $SwitchKing 

    If ($SystemSettings -eq $false) {
        $connectionOk = $false
        Return $false
    } else {
        $Location = ($SystemSettings | Where-Object { $_.Name -eq "CurrentLocationCoord" }).Value -split "&&"
        $LocationLat = $Location[0]
        $LocationLong = $Location[1]
    
        $SwitchKing = [PSCustomObject] @{
            Url = $SwitchKing.Url
            User = $SwitchKing.User
            SecurePassword = $SwitchKing.SecurePassword
            ServerVersion = ($SystemSettings | Where-Object { $_.Name -eq "ServerVersion" }).Value
            ServerIdentity = ($SystemSettings | Where-Object { $_.Name -eq "ServerIdentity" }).Value
            ServerDbVersion = ($SystemSettings | Where-Object { $_.Name -eq "CurDbVersion" }).Value
            ServerLocationLat = $LocationLat
            ServerLocationLong = $LocationLong
            ServerPlatform = ($SystemSettings | Where-Object { $_.Name -eq "Platform" }).Value
        }

        Return $SwitchKing

    }
}

#endregion Generic
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#region Get status

Function Get-SwitchKingSystemSettings {
<#
    .SYNOPSIS
        Returns System Settings
    .EXAMPLE
        Get-SwitchKingSystemSettings -SwitchKing ( Get-SwitchKingInfo -ServerName "server.home.local" -User "MyUser" -Password "SecretPassword" )
    .EXAMPLE
        $MySkConnection | Get-SwitchKingSystemSettings
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing
	)

    Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "SystemSettings" -ArrayName "ArrayOfRESTSystemSetting" -ArrayLoop "RESTSystemSetting"
}

Function Get-SwitchKingDevices {
<#
    .SYNOPSIS
        Returns device(s)
    .EXAMPLE
        $MySkConnection | Get-SwitchKingDevices
        Return all devices
    .EXAMPLE
        Get-SwitchKingDevices -SwitchKing $MySkConnection -DeviceID 12
        Return device with ID 12
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo¨s
    .PARAMETER DeviceID
        If you only want info from one device
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$false)] [alias("ID", "Device")] [int] $DeviceID = -1
	)

    if ($DeviceID -eq -1) {
        Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "Devices" -ArrayName "ArrayOfRESTDevice" -ArrayLoop "RESTDevice"
    } else {
        Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "Devices/$($DeviceId)" -ArrayName "RESTDevice"
    }
}

Function Get-SwitchKingDeviceGroups {
<#
    .SYNOPSIS
        Returns group(s)
    .EXAMPLE
        $MySkConnection | Get-SwitchKingDeviceGroups
        Return all groups
    .EXAMPLE
        Get-SwitchKingDeviceGroups -SwitchKing $MySkConnection -GroupID 12
        Return group with ID 12
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER GroupID
        If you only want info from one group
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$false)] [alias("ID", "Group")] [int] $GroupID = -1
	)

    if ($GroupID -eq -1) {
        Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "DeviceGroups" -ArrayName "ArrayOfRESTDeviceGroup" -ArrayLoop "RESTDeviceGroup"
    } else {
        Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "DeviceGroups/$($GroupID)" -ArrayName "RESTDeviceGroup"
    }
}

Function Get-SwitchKingDataSources {
<#
    .SYNOPSIS
        Returns datasource(s)
    .EXAMPLE
        $MySkConnection | Get-SwitchKingDataSources
        Return all datasources
    .EXAMPLE
        Get-SwitchKingDataSources -SwitchKing $MySkConnection -DataSourceID 12
        Return datasource with ID 12
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER DataSourceID
        If you only want info from one datasource
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$false)][alias("ID", "SourceID", "Source")] [int] $DataSourceID = -1
	)

    if ($DataSourceID -eq -1) {
        Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "DataSources" -ArrayName "ArrayOfRESTDataSource" -ArrayLoop "RESTDataSource"
    } else {
        Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "DataSources/$($DataSourceID)" -ArrayName "RESTDataSource"
    }
}

Function Get-SwitchKingDataSourceValues {
<#
    .SYNOPSIS
        Returns value(s) from a single DataSource
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true)][alias("ID", "SourceID", "Source")] [int] $DataSourceID,
        [Parameter(Mandatory=$false)][alias("Count", "Max")] [int] $maxCount = 10,
        [Parameter(Mandatory=$false)][alias("Newer")] [DateTime][ValidateScript({$_ -le (Get-Date)})] $newerThan = (Get-Date).AddHours(-1)
	)

    Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "datasources/$($DataSourceID)/values?maxcount=$($maxCount)&newerthan=$(Get-SKHelperUrlEncodedString $newerThan)" -ArrayName "ArrayOfRESTDataSourceValue" -ArrayLoop "RESTDataSourceValue"
}

Function Get-SwitchKingDataSourceGraph {
<#
    .SYNOPSIS
        Create a PNG with a graph
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true)][alias("ID", "SourceID", "Source")] [int] $DataSourceID,
        [Parameter(Mandatory=$false)][alias("X")] [int] $width = 800,
        [Parameter(Mandatory=$false)][alias("Y")] [int] $height = 600,
        [Parameter(Mandatory=$false)][alias("History", "Minutes")][ValidateScript({Get-SKHelperValidateMinutesParam -Minutes $_ })] [Int] $minutesOfHistory = 60,
        [Parameter(Mandatory=$true)][string] $filePath
	)

    $graph = Invoke-SKHelperRawRestCall -SwitchKing $SwitchKing -RestCall "datasources/$($DataSourceID)/graph.png?width=$($width)&height=$($height)&minutesofhistory=$($minutesOfHistory)" -Binary
    if ($graph -ne $false) {
        Return Set-Content -Path $filePath -Encoding Byte -Value $graph.content
    } else {
        Return $false
    }
}

Function Get-SwitchKingSenarios {
<#
    .SYNOPSIS
        Returns scenarios
    .EXAMPLE
        $MySkConnection | Get-SwitchKingSenarios
        Return all scenarios
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing
	)

    Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "Scenarios" -ArrayName "ArrayOfRESTScenario" -ArrayLoop "RESTScenario"
}

Function Get-SwitchKingSystemModes {
<#
    .SYNOPSIS
        Returns System Modes
    .EXAMPLE
        Get-SwitchKingSystemModes -SwitchKing $MySkConnection
        Return all System Modes
    .EXAMPLE
        $MySkConnection | Get-SwitchKingSystemModes -Active
        Return active System Mode
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER Active
        Only return Active System Mode
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$false)] [switch] $Active
	)

    #Todo: If (Test-OkVersion -MinRequired "3.0.0" -CurrentVersion $SwitchKing.ServerVersion -eq $false) { Throw "Need at least 3.0.0" }

    If ( $Active.IsPresent ) {
        Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "systemmodes/active" -ArrayName "RESTSystemMode"
    } else {
        Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "systemmodes" -ArrayName "ArrayOfRESTSystemMode" -ArrayLoop "RESTSystemMode"
    }
}

Function Get-SwitchKingEvents {
<#
    .SYNOPSIS
        Get upcoming event(s) from SwitchKing
    .EXAMPLE
        Get-SwitchKingEvents -SwitchKing $MySkConnection
        Return all upcoming events
    .EXAMPLE
        $MySkConnection | Get-SwitchKingSystemModes -maxCount 5
        Get 5 upcoming events
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER maxCount
        Limit number of events
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [alias("Max", "Count")] [int] $maxCount = 10
	)

    Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "Events/future?maxCount=$($maxCount)" -ArrayName "ArrayOfRESTEvent" -ArrayLoop "RESTEvent"
}

Function Get-SwitchKingInterceptedEvents {
<#
    .SYNOPSIS
        Get intercepted events from SwitchKing (From Duo / Telldus Center)
    .EXAMPLE
        Get-SwitchKingInterceptedEvents -SwitchKing $MySkConnection
        Get intercepted events
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
#>
	PARAM (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("SK")] [PSCustomObject] $SwitchKing
	)

    Return Get-SKHelperRest -SwitchKing $SwitchKing -RestCall "Events/intercepted" -ArrayName "ArrayOfRESTMonitoredEntityEvent" -ArrayLoop "RESTMonitoredEntityEvent"
}

#endregion Get status
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#region Set status

Function Get-SwitchKingCommands {
<#
    .SYNOPSIS
        Get valid SwitchKing Commands
    .EXAMPLE
        Get-SwitchKingCommands
        Return an array with commands
#>
    Return Get-SKHelperValidateCommandParam -GetParams
}

Function Get-SwitchKingRelativeCommands {
<#
    .SYNOPSIS
        Get valid SwitchKing Relative Commands
    .EXAMPLE
        Get-SwitchKingRelativeCommands
        Return an array with commands
#>
    Return Get-SKHelperValidateRelativeCommandParam -GetParams
}

Function Get-SwitchKingMinutes {
<#
    .SYNOPSIS
        Get valid SwitchKing minutes
    .EXAMPLE
        Get-SwitchKingMinutes
        Return an array with minutes
#>
    Return Get-SKHelperValidateMinutesParam -GetParams
}

Function Set-SwitchKingDevice {
<#
    .SYNOPSIS
        Set status on a device
    .EXAMPLE
        Get-SwitchKingDevices -SwitchKing $MySkConnection | Where-Object { $_.GroupName -eq "Outside Lights" } | Set-SwitchKingDevice -Command "turnoff" -SwitchKing $MySkConnection
        Send the command TurnOff to a devices in a group named 'Outside Lights'
    .EXAMPLE
        Get-SwitchKingDevices -SwitchKing $MySkConnection | Where-Object { $_.Name -eq "Kitchen Light" } | Set-SwitchKingDevice -Command "dim/40" -SwitchKing $MySkConnection
        Send the command Dim/40 to the device named 'Kitchen Light'
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER Device
        Device(s) returned from Get-SwitchKingDevice
    .PARAMETER Command
        Command to send, user Get-SwitchKingCommands to list valid commands
#>
	PARAM (
        [Parameter(Mandatory=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [PSCustomObject] $Device,
        [Parameter(Mandatory=$true)] [ValidateScript({Get-SKHelperValidateCommandParam -Command $_ })] [string] $Command
	)

	BEGIN {}
	PROCESS {
		Foreach ($SkDevice in $Device) {
            If ($Command -like "*dim*/*" -and $SkDevice.SupportsAbsoluteDimLvl -eq $false) {
                Write-Verbose "Device ID $($SkDevice.ID) ($($SkDevice.Name)) doesn't support dim-commands"
                Return $false
            } else {
                Write-Verbose "Send $($Command) to device $($SkDevice.ID) ($($SkDevice.Name))"
                Return Set-SKHelperRest -SwitchKing $SwitchKing -RestCall "devices/$($SkDevice.ID)/$($Command)"
            }
		}
    }
    END {}
}

Function Set-SwitchKingDeviceGroup {
<#
    .SYNOPSIS
        Set status on a group
    .EXAMPLE
        Get-SwitchKingDeviceGroup -SwitchKing $MySkConnection | Where-Object { $_.Name -like "Inside*" } | Set-SwitchKingDeviceGroup -Command "turnoff" -SwitchKing $MySkConnection
        Send the command TurnOff to a group starting with 'Inside' in the name
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER DeviceGroup
        Device(s) returned from Get-SwitchKingDeviceGroups
    .PARAMETER Command
        Command to send, user Get-SwitchKingCommands to list valid commands
#>
	PARAM (
        [Parameter(Mandatory=$true)][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("Group")] [PSCustomObject] $DeviceGroup,
        [Parameter(Mandatory=$true)] [ValidateScript({Get-SKHelperValidateCommandParam -Command $_ })] [string] $Command
	)

	BEGIN {}
	PROCESS {
		Foreach ($SkDeviceGroup in $DeviceGroup) {
            Write-Verbose "Send $($Command) to device $($SkDeviceGroup.ID) ($($SkDeviceGroup.Name))"
            Return Set-SKHelperRest -SwitchKing $SwitchKing -RestCall "devicegroups/$($SkDeviceGroup.ID)/$($Command)"
		}
    }
    END {}
}

Function Set-SwitchKingScenario {
<#
    .SYNOPSIS
        Activate a Scenario
    .EXAMPLE
        Get-Get-SwitchKingSenarios -SwitchKing $MySkConnection | Where-Object { $_.Name -eq "Movie Time" } | Set-Get-SwitchKingSenario -SwitchKing $MySkConnection
        Activate the scenario named 'Movie Time'
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER Scenario
        Scenario returned from Get-SwitchKingSenarios
#>
	PARAM (
        [Parameter(Mandatory=$true)][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] [PSCustomObject] $Scenario
	)

    Write-Verbose "Set scenario $($Scenario.ID) ($($Scenario.Name)) as active"
    Return Set-SKHelperRest -SwitchKing $SwitchKing -RestCall "commandqueue?operation=changescenario&target=$($Scenario.ID)"
}

Function Set-SwitchKingSystemMode {
<#
    .SYNOPSIS
        Activate a System Mode
    .EXAMPLE
        Get-Get-SwitchKingSystemModes -SwitchKing $MySkConnection | Where-Object { $_.Name -eq "Home" } | Set-Get-SwitchKingSenario -SwitchKing $MySkConnection
        Activate the System Mode 'Home'
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER SystemMode
        Scenario returned from Get-SwitchKingSystemMode
#>
	PARAM (
        [Parameter(Mandatory=$true)][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )][alias("Mode")] [PSCustomObject] $SystemMode
	)

    Write-Verbose "Set SystemMode $($SystemMode.ID) ($($SystemMode.Name)) as active"
    Return Set-SKHelperRest -SwitchKing $SwitchKing -RestCall "commandqueue?operation=changesystemmode&target=$($SystemMode.ID)"
}

#endregion Set status
# ------------------------------------------------------------------------------------------------------------
#region Add Values
Function Add-SwitchKingDataSourceValue {
<#
    .SYNOPSIS
        Add A value to a Data Source
    .EXAMPLE
        Get-SwitchKingDataSources -SwitchKing $MySkConnection | Where-Object { $_.Name -eq "Powershell Test" } | Add-SwitchKingDataSourceValue -Value 4 -SwitchKing $MySkConnection
        Add value 4 to a datasource named 'Powershell Test'
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER DataSource
        Result from Get-SwitchKingDataSources
    .PARAMETER Value
        Value to add
#>
	PARAM (
        [Parameter(Mandatory=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [alias("ID", "Source")] [PSCustomObject] $DataSource,
        [Parameter(Mandatory=$true)] [string] $Value
	)

	BEGIN {}
	PROCESS {
		Foreach ($SkDataSource in $DataSource) {
            Write-Verbose "Adding value $($Value) to DataSource ID $($SkDataSource.ID) ($($SkDataSource.Name))"
            Return Add-SKHelperRest -SwitchKing $SwitchKing -RestCall "datasources/$($SkDataSource.ID)/addvalue?value=$(Get-SKHelperUrlEncodedString $Value)"
		}
    }
    END {}
}

Function Add-SwitchKingDataSourceRelativeValue {
<#
    .SYNOPSIS
        Add a relative value to a Data Source
    .EXAMPLE
        Get-SwitchKingDataSources -SwitchKing $MySkConnection | Where-Object { $_.Name -eq "Powershell Test" } | Add-SwitchKingDataSourceRelativeValue -Value 3 -SwitchKing $MySkConnection -Action '?' -minValue 2 -maxValue 5
        Add a relative value to a datasource named 'Powershell Test'
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER DataSource
        Result from Get-SwitchKingDataSources
    .PARAMETER Value
        Relative value to add
    .PARAMETER Action
        Command to send, user Get-SwitchKingRelativeCommands to list valid commands
    .PARAMETER minValue
        Min limit to add
    .PARAMETER maxValue
        Min limit to add
#>

	PARAM (
        [Parameter(Mandatory=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [alias("ID", "Source")] [PSCustomObject] $DataSource,
        [Parameter(Mandatory=$true)] [int] $Value,
        [Parameter(Mandatory=$true)] [string] $Action,
        [Parameter(Mandatory=$true)][alias("Min")] [int] $minValue,
        [Parameter(Mandatory=$true)][alias("Max")] [int] $maxValue
	)


	BEGIN {}
	PROCESS {
		Foreach ($SkDataSource in $DataSource) {
            Write-Verbose "Adding Relative Value $($Value) to DataSource ID $($SkDataSource.ID) ($($SkDataSource.Name))"

            Return Add-SKHelperRest -SwitchKing $SwitchKing -RestCall "datasources/$($SkDataSource.ID)/setvaluerelative?value=$($Value)&action=$($Action)&minValue=$($minValue)&maxValue=$($maxValue)"
		}
    }
    END {}
}

Function Add-SwitchKingDataSourceFutureValue {
<#
    .SYNOPSIS
        Add A value to a Data Source
    .EXAMPLE
        Get-SwitchKingDataSources -SwitchKing $MySkConnection | Where-Object { $_.Name -eq "Powershell Test" } | Add-SwitchKingDataSourceFutureValue -Value (Get-Random -Minimum 1 -Maximum 20) -SwitchKing $MySkConnection -timeStamp (Get-Date).AddMinutes(2)
        Add a random value between 1 and 20 to a datasource named 'Powershell Test'
    .PARAMETER SwitchKing
        Result from Get-SwitchKingInfo
    .PARAMETER DataSource
        Result from Get-SwitchKingDataSources
    .PARAMETER Value
        Value to add
    .PARAMETER timeStamp
        Future time to add the value
#>
	PARAM (
        [Parameter(Mandatory=$true )][alias("SK")] [PSCustomObject] $SwitchKing,
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [alias("ID", "Source")] [PSCustomObject] $DataSource,
        [Parameter(Mandatory=$true)] [string] $Value,
        [Parameter(Mandatory=$true)] [DateTime][ValidateScript({$_ -gt (Get-Date)})] $timeStamp

	)

	BEGIN {}
	PROCESS {
		Foreach ($SkDataSource in $DataSource) {
            Write-Verbose "Adding Future Value $($Value) to DataSource ID $($SkDataSource.ID) ($($SkDataSource.Name)) at $($timeStamp)"

            Return Add-SKHelperRest -SwitchKing $SwitchKing -RestCall "datasources/$($SkDataSource.ID)/addfuturevalue?value=$(Get-SKHelperUrlEncodedString $Value)&timestamp=$(Get-SKHelperUrlEncodedString $timeStamp)"
		}
    }
    END {}
}

#endregion Add Values
# ------------------------------------------------------------------------------------------------------------
# Export all functions except Helpers
Get-ChildItem Function: | Where-Object { $_.ModuleName -eq "SwitchKing" -and $_.Name -notlike "*-SKHelper*" } | ForEach-Object {
    Export-ModuleMember -Function $_.Name -Alias $_.Name.Replace("SwitchKing", "SK")
}
# ------------------------------------------------------------------------------------------------------------
#>
Posted in

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>