Thursday, February 19, 2015

Roku Controls With PowerShell

This is a GUI I created that will interact with any Roku boxes that may be on your network.  Not only that, I was able to figure out how to convert some c# to PowerShell to send out SSDP broadcasts for network device discovery.  This enables the GUI to discover any Roku boxes without having to know the IP address off hand.  It is not complete, but works well.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
Add-Type -TypeDefinition @"
    public enum RokuCommands
    {
        Home,
        Rev,
        Fwd,
        Play,
        Select,
        Left,
        Right,
        Down,
        Up,
        Back,
        InstantReplay,
        Info,
        Backspace,
        Search,
        Enter,
    }
"@


#GetAppIDS http://192.168.1.134:8060/query/apps
$Global:WebClient = new-object System.Net.WebClient

Function Discover-RokuDevices($Port){
    #Use unused port or it will fail
    $LocalEndPoint = New-Object System.Net.IPEndPoint([ipaddress]::Any,$Port)

    $MulticastEndPoint = New-Object System.Net.IPEndPoint([ipaddress]::Parse("239.255.255.250"),1900)

    $UDPSocket = New-Object System.Net.Sockets.Socket([System.Net.Sockets.AddressFamily]::InterNetwork,[System.Net.Sockets.SocketType]::Dgram,[System.Net.Sockets.ProtocolType]::Udp)

    $UDPSocket.SetSocketOption([System.Net.Sockets.SocketOptionLevel]::Socket, [System.Net.Sockets.SocketOptionName]::ReuseAddress,$true)

    $UDPSocket.Bind($LocalEndPoint)

    $UDPSocket.SetSocketOption([System.Net.Sockets.SocketOptionLevel]::IP,[System.Net.Sockets.SocketOptionName]::AddMembership, (New-Object System.Net.Sockets.MulticastOption($MulticastEndPoint.Address, [ipaddress]::Any)))

    $UDPSocket.SetSocketOption([System.Net.Sockets.SocketOptionLevel]::IP, [System.Net.Sockets.SocketOptionName]::MulticastTimeToLive, 2)

    $UDPSocket.SetSocketOption([System.Net.Sockets.SocketOptionLevel]::IP, [System.Net.Sockets.SocketOptionName]::MulticastLoopback, $true)

    #Write-Host "UDP-Socket setup done...`r`n"
    #All SSDP Search
    $SearchString = "M-SEARCH * HTTP/1.1`r`nHOST:239.255.255.250:1900`r`nMAN:`"ssdp:discover`"`r`nST:ssdp:all`r`nMX:3`r`n`r`n"

    $UDPSocket.SendTo([System.Text.Encoding]::UTF8.GetBytes($SearchString), [System.Net.Sockets.SocketFlags]::None, $MulticastEndPoint| Out-Null

    #Write-Host "M-Search sent...`r`n"

    [byte[]]$RecieveBuffer = New-Object byte[] 64000

    [int]$RecieveBytes = 0

    $Response_RAW = ""
    $Timer = [System.Diagnostics.Stopwatch]::StartNew()
    $Delay = $True
    while($Delay){
        #15 Second delay so it does not run forever
        if($Timer.Elapsed.TotalSeconds -ge 5){Remove-Variable Timer$Delay = $false}
        if($UDPSocket.Available -gt 0){
            $RecieveBytes = $UDPSocket.Receive($RecieveBuffer, [System.Net.Sockets.SocketFlags]::None)

            if($RecieveBytes -gt 0){
                $Text = "$([System.Text.Encoding]::UTF8.GetString($RecieveBuffer, 0, $RecieveBytes))"
                $Response_RAW += $Text
            }
        }
    }

    $Rokus = [regex]::Matches($Response_RAW,"(http://)(\d{1,3}\.?){4}(:8060/)"| select -ExpandProperty value | select -Unique
    [regex]::Matches($Rokus, "(\d{1,3}\.)(\d{1,3}\.?){3}"| select -ExpandProperty value
}

Function Connect-Roku($IPAddress){
    $Global:Roku = "http://$($IPAddress):8060"
}

Function Send-RokuCommand([RokuCommands]$Command){
    $Global:WebClient.UploadString("$Global:Roku/keypress/$Command", "POST","")
}

Function Send-RokuText($Text,$RokuIPAddress){
    $Text.Replace(" ","%20")
    $Text.ToCharArray() | %{"$Roku/keypress/Lit_$_"#foreach{$Global:WebClient.UploadString("$Global:Roku/keypress/Lit_$_", "POST","")}
}

Function Launch-RokuApp($AppID){
    $WebClient.UploadString("$Global:Roku/launch/$AppID", "POST","")
}

Function Get-RokuApps(){
    ([xml]$WebClient.DownloadString("$Global:Roku/query/apps")).apps.app | select "#Text", ID
}

$RokuList = Discover-RokuDevices -Port 65433 
Connect-Roku -IPAddress $RokuList.Item(0)

####Build Form####
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$Form_Main = New-Object System.Windows.Forms.Form
$Form_Main.Size = [System.Drawing.Point]"640,480"

$Roku_Listbox = New-Object System.Windows.Forms.ListBox
$Roku_Listbox.Items.AddRange($RokuList)
$Roku_Listbox.SelectedIndex = 0
$Roku_Listbox.Add_SelectedIndexChanged({$Global:Roku = "http://$($Roku_Listbox.SelectedItem):8060"})
$Roku_Listbox.Size = [System.Drawing.Point]"100,50"
$Roku_Listbox.Location = [System.Drawing.Point]"10,10"
$Form_Main.Controls.Add($Roku_Listbox)


$Group_Arrows = New-Object System.Windows.Forms.GroupBox
$Group_Arrows.Size = [System.Drawing.Point]"150,100"
$Group_Arrows.Location = [System.Drawing.Point]"100,50"

$Arrow_up = New-Object System.Windows.Forms.Button
$Arrow_up.Text = [char]0x2191
$Arrow_up.Size = [System.Drawing.Point]"30,30"
$Arrow_up.Location = [System.Drawing.Point]"60,20"
$Arrow_up.Add_Click({Send-RokuCommand -Command Up})
$Group_Arrows.Controls.Add($Arrow_up)

$Arrow_Down = New-Object System.Windows.Forms.Button
$Arrow_Down.Text = [char]0x2193
$Arrow_Down.Size = [System.Drawing.Point]"30,30"
$Arrow_Down.Location = [System.Drawing.Point]"60,60"
$Arrow_Down.Add_Click({Send-RokuCommand -Command Down})
$Group_Arrows.Controls.Add($Arrow_Down)

$Arrow_Left = New-Object System.Windows.Forms.Button
$Arrow_Left.Text = [char]0x2190
$Arrow_Left.Size = [System.Drawing.Point]"30,30"
$Arrow_Left.Location = [System.Drawing.Point]"20,60"
$Arrow_Left.Add_Click({Send-RokuCommand -Command Left})
$Group_Arrows.Controls.Add($Arrow_Left)

$Arrow_Right = New-Object System.Windows.Forms.Button
$Arrow_Right.Text = [char]0x2192
$Arrow_Right.Size = [System.Drawing.Point]"30,30"
$Arrow_Right.Location = [System.Drawing.Point]"100,60"
$Arrow_Right.Add_Click({Send-RokuCommand -Command Right})
$Group_Arrows.Controls.Add($Arrow_Right)

$Apps = Get-RokuApps
$App_Box = New-Object System.Windows.Forms.ListBox
$App_Box.Items.AddRange(($Apps | select -ExpandProperty "#Text"))
$App_Box.Add_SelectedIndexChanged({$Global:AppSelection = $Apps | where{$_."#Text" -eq $App_Box.SelectedItem} | select -ExpandProperty id})
$App_Box.Size = [System.Drawing.Point]"150,200"
$App_Box.Location = [System.Drawing.Point]"400,10"

$App_Box_Fire = New-Object System.Windows.Forms.Button
$App_Box_Fire.Size = [System.Drawing.Point]"150,50"
$App_Box_Fire.Location = [System.Drawing.Point]"400,220"
$App_Box_Fire.Text = "Go to App!"
$App_Box_Fire.Add_Click({Launch-RokuApp -AppID $Global:AppSelection})

$Group_PlayControls = New-Object System.Windows.Forms.GroupBox
$Group_PlayControls.Size = [System.Drawing.Point]"200,200"
$Group_PlayControls.Location = [System.Drawing.Point]"100,150"

$Play_Pause = New-Object System.Windows.Forms.Button
$Play_Pause.Size = [System.Drawing.Point]"50,50"
$Play_Pause.Location = [System.Drawing.Point]"75,130"
$Play_Pause.Text = "$([char]0x34)`n$([char]0x3B)"
$Play_Pause.Font = New-Object System.Drawing.Font("Webdings",12,[System.Drawing.FontStyle]::Bold)
$Play_Pause.Add_Click({Send-RokuCommand -Command Play})
$Group_PlayControls.Controls.Add($Play_Pause)

$Reverse = New-Object System.Windows.Forms.Button
$Reverse.Size = [System.Drawing.Point]"50,50"
$Reverse.Location = [System.Drawing.Point]"25,130"
$Reverse.Text = "$([char]0x37)"
$Reverse.Font = New-Object System.Drawing.Font("Webdings",12,[System.Drawing.FontStyle]::Bold)
$Reverse.Add_Click({Send-RokuCommand -Command Rev})
$Group_PlayControls.Controls.Add($Reverse)

$Fast_Forward = New-Object System.Windows.Forms.Button
$Fast_Forward.Size = [System.Drawing.Point]"50,50"
$Fast_Forward.Location = [System.Drawing.Point]"125,130"
$Fast_Forward.Text = "$([char]0x38)"
$Fast_Forward.Font = New-Object System.Drawing.Font("Webdings",12,[System.Drawing.FontStyle]::Bold)
$Fast_Forward.Add_Click({Send-RokuCommand -Command Fwd})
$Group_PlayControls.Controls.Add($Fast_Forward)

$Replay = New-Object System.Windows.Forms.Button
$Replay.Size = [System.Drawing.Point]"50,50"
$Replay.Location = [System.Drawing.Point]"25,25"
$Replay.Text = "$([char]0x71)"
$Replay.Font = New-Object System.Drawing.Font("Webdings",12,[System.Drawing.FontStyle]::Bold)
$Replay.Add_Click({Send-RokuCommand -Command InstantReplay})
$Group_PlayControls.Controls.Add($Replay)

$Info = New-Object System.Windows.Forms.Button
$Info.Size = [System.Drawing.Point]"50,50"
$Info.Location = [System.Drawing.Point]"125,25"
$Info.Text = "*"
$Info.Font = New-Object System.Drawing.Font("Calibri",36,[System.Drawing.FontStyle]::Bold)
$Info.Add_Click({Send-RokuCommand -Command Info})
$Group_PlayControls.Controls.Add($Info)

$Enter = New-Object System.Windows.Forms.Button
$Enter.Size = [System.Drawing.Point]"150,50"
$Enter.Location = [System.Drawing.Point]"25,77"
$Enter.Text = "OK"
$Enter.Font = New-Object System.Drawing.Font("Calibri",12,[System.Drawing.FontStyle]::Bold)
$Enter.Add_Click({Send-RokuCommand -Command Enter})
$Group_PlayControls.Controls.Add($Enter)

#Add TextBox for input
#Home buton
#Back button
#Enter button does not work??

$Form_Main.Controls.Add($Group_PlayControls)
$Form_Main.Controls.Add($Group_Arrows)
$Form_Main.Controls.Add($App_Box)
$Form_Main.Controls.Add($App_Box_Fire)
$Form_Main.ShowDialog()

Thursday, February 12, 2015

Powershell WSUS Client Front End

This is a script that I wrote which uses the WSUS APIs in windows (COM) and presents the user with a GUI to select and install updates.  I was very happy to learn how to use a listview .NET control in this exercise.


Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

#####################
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'

function Show-Console {
   $consolePtr = [Console.Window]::GetConsoleWindow()
  #5 show
 [Console.Window]::ShowWindow($consolePtr, 5)
}

function Hide-Console {
    $consolePtr = [Console.Window]::GetConsoleWindow()
  #0 hide
 [Console.Window]::ShowWindow($consolePtr, 0)
}
#####################
#uncomment next line to hide console window to make things prettier if run from SCCM application/package for instance
#Hide-Console
Start-Process -FilePath "wuauclt.exe" -ArgumentList "/a /resetauthorization /detectnow"

#Alternate detection than wuauclt, not sure if it does the resetauthorization switch
#$AutoUpdate = New-Object -ComObject Microsoft.Update.AutoUpdate
#$AutoUpdate.DetectNow()

$UpdateCollection = New-Object -ComObject "Microsoft.Update.UpdateColl"
$Searcher = New-Object -ComObject "Microsoft.Update.Searcher"
$Session = New-Object -ComObject "Microsoft.Update.Session"
$Downloader = $Session.CreateUpdateDownloader()
$Installer = New-Object -ComObject "Microsoft.Update.Installer"

#May be necessary to specify other parameters to use a WSUS server
#$Searcher.ServerSelection = 0 #Default
#$Searcher.Online = $False

$LoadingForm = New-Object System.Windows.Forms.Form
$LoadingForm.Size = [System.Drawing.Point]"300,300"
$LoadingForm.FormBorderStyle = "None"
$LoadingForm.TopMost = $true
$LoadingForm.BackColor = [System.Drawing.Color]::PaleTurquoise
$LoadingForm.StartPosition = "CenterScreen"
$LoadingLabel = New-Object System.Windows.Forms.Label
$LoadingLabel.Text = "Loading updates, please wait..."
$LoadingLabel.Location = [System.Drawing.Point]"25,100"
$LoadingLabel.Font = "Calibri, 25"
$LoadingLabel.Size = [System.Drawing.Point]"300,200"
$LoadingForm.Controls.Add($LoadingLabel)
$LoadingForm.Show()

#Allow update scan time to work
Start-Sleep -Seconds 30

$NotInstalled = $Searcher.Search("IsInstalled=0")

$LoadingForm.Close()
#>
########Begin Form
Function New-Button($Text,$X,$Y,$ScriptBlock){
    $Button = New-Object System.Windows.Forms.Button
    $Button.Size = [System.Drawing.Point]"200,50"
    $Button.Location = [System.Drawing.Point]"$x,$y"
    $Button.Text = $Text
    $Button.Add_Click($ScriptBlock)
    $Button
}

########Begin Form
   
$Form = New-Object System.Windows.Forms.Form
$Form.Size = [System.Drawing.Point]"800,600"
$Form.StartPosition = "CenterScreen"
$Form.FormBorderStyle = "FixedSingle"
$Form.TopMost = $true
$Form.MinimizeBox = $false
$Form.MaximizeBox = $false

$ListView = New-Object System.Windows.Forms.ListView
$ListView.Size = [System.Drawing.Point]"400,400"
$ListView.Location = [System.Drawing.Point]"50,50"
$ListView.CheckBoxes = $true
$ListView.View = [System.Windows.Forms.View]::Details
$ListView.Width = $Form.ClientRectangle.Width - 100
$ListView.Height = $Form.ClientRectangle.Height - 150
$ListView.Anchor = "Top, Left, Right, Bottom"

$ListView.Columns.Add("Title",-2) | Out-Null
$ListView.Columns.Add("GUID",0) | Out-Null
$ListView.Columns.Add("Needs Reboot",-2) | Out-Null
$ListView.add_ItemChecked({if(.$EvalChecks){$OKButton.Enabled = $true}else{$OKButton.Enabled = $false}})
   
Foreach($Update in $NotInstalled.Updates){
        if($Update.InstallationBehavior.CanRequestUserInput -eq $false){
        $ListViewItem = New-Object System.Windows.Forms.ListViewItem($Update.Title)
        #$ListViewItem.SubItems.Add($Update.KBArticleIDs.Item(0)) | Out-Null
        #$ListViewItem.SubItems.Add([int]($Update.MaxDownloadSize / 1MB)) | Out-Null
        #$ListViewItem.SubItems.Add($Update.LastDeploymentChangeTime.ToString()) | Out-Null
        $ListViewItem.SubItems.Add($Update.Identity.UpdateID) | Out-Null
        $ListViewItem.SubItems.Add($Update.RebootRequired.ToString()) | Out-Null
        $ListView.Items.Add($ListViewItem) | Out-Null
    }
}

$EvalChecks = {
    ($ListView.Items | select -ExpandProperty checked | ?{$_ -eq $true} | Measure-Object | select -ExpandProperty count) -gt 0
}

$InstallUpdates = {
    $Form.Hide()
    $CheckedUpdates = $ListView.Items | where{$_.Checked} | select -ExpandProperty SubItems | Where{$_.Text -match "\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b"} | select -ExpandProperty Text
    $Installer = New-Object -ComObject "Microsoft.Update.Installer"
    $UpdateCollection = New-Object -ComObject "Microsoft.Update.UpdateColl"
    $DownloadCollection =  New-Object -ComObject "Microsoft.Update.UpdateColl"

    Foreach($Selected_Update in $CheckedUpdates){
        $UpdateToInstall = $NotInstalled.Updates | Where{$_.Identity.UpdateID -in $Selected_Update}
        #Check if already downloaded, no need to duplicate effort
        if(!$UpdateToInstall.IsDownloaded){
            $DownloadCollection.Add($UpdateToInstall)
        }

        $UpdateCollection.Add($UpdateToInstall)
        if($Installer.RebootRequiredBeforeInstallation){[System.Windows.Forms.MessageBox]::Show("A reboot is required before the remaining updates can be installed.");$Form.Close();break}
    }
       
        $Downloader.Updates = $DownloadCollection
        $Downloader.Download()

        $Installer.Updates = $UpdateCollection
        $Installer.Install()
        $Form.Close()
}

$CancelButton = New-Button -Text "Cancel" -X 425 -Y 485 -ScriptBlock {$ListView.Items | %{$_.Checked = $false};$Form.Close()}
$OKButton = New-Button -Text "Install Selection" -X 175 -Y 485 -ScriptBlock $InstallUpdates

$CheckBox_Select_All = New-Object System.Windows.Forms.CheckBox
$CheckBox_Select_All.Size = [System.Drawing.Point]"100,20"
$CheckBox_Select_All.Location = [System.Drawing.Point]"55,25"
$CheckBox_Select_All.Text = "Select All"
$CheckBox_Select_All.Add_CheckedChanged({
    If($CheckBox_Select_All.Checked){
        $ListView.Items | %{$_.Checked = $true}
    }
    elseif(! $CheckBox_Select_All.Checked){
        $ListView.Items | %{$_.Checked = $false}
    }
})
$Form.Controls.Add($CheckBox_Select_All)

$Title = New-Object System.Windows.Forms.Label
$Title.Text = "The Chicoine Patching Tool"
$Title.Font = "Calibri,20"
$Title.Location = [System.Drawing.Point]"250,10"
$Title.Size = [System.Drawing.Point]"500,40"
   
$Form.Controls.Add($Title)
$Form.Controls.Add($ListView) | Out-Null
$Form.Controls.Add($OKButton)
$Form.Controls.Add($CancelButton)
$Form.Add_Shown({if(.$EvalChecks){$OKButton.Enabled = $true}else{$OKButton.Enabled = $false}})
#[System.Windows.Forms.Application]::Run($Form)
$Form.ShowDialog()