Powershell GUI fronted (WPF) to run categorized console scripts

⌈⌋ branch:  ClickyColoury


Check-in [e114cf1bc5]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Migration to PS5 file renaming. Remove function copying in New-GuiThread;
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: e114cf1bc5b4cb08f8459c22e8e2aa1bb8877821
User & Date: mario 2018-04-08 09:47:38
Context
2018-04-08
12:30
Merge PowerShell5 support (still runs on PS2.0 !) check-in: b51a20fe04 user: mario tags: trunk
09:49
reapply changes from trunk to ps5 check-in: 0298a592f2 user: mario tags: ps5
09:47
Migration to PS5 file renaming. Remove function copying in New-GuiThread; check-in: e114cf1bc5 user: mario tags: trunk
2017-09-24
15:32
Mini tool to look up some basic infos on servers/hostnames check-in: 8d7d5133e8 user: mario tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Name change from modules/wpf.psm1 to modules/guimenu.psm1.

1
2
3
4
5
6
7
8
9
10
11
12
13
..
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
...
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
...
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

222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# api: ps
# title: WPF + WinForms
# description: WinForm and WPF shortcuts, GUI and thread handling
# depends: menu, clipboard, sys:presentationframework, sys:system.windows.forms, sys:system.drawing
# doc: http://fossil.include-once.org/clickycoloury/wiki/W
# version: 1.0.7
# license: MITL
# type: functions
# category: ui
# config:
#   { name: cfg.threading, type: bool, value: 1, description: Enable threading/runspaces for GUI/WPF version }
#   { name: cfg.autoclear, type: int, value: 300, description: Clear output box after N seconds. }
#   { name: cfg.noheader, type: bool, value: 0, description: Disable script info header in output. }
................................................................................
Add-Type -AN System.Drawing, System.Windows.Forms, Microsoft.VisualBasic
# [System.Windows.Forms.Application]::EnableVisualStyles()
# [System.Windows.Forms.Application]::SetCompatibleTextRenderingDefault($true)

#-- init vars
$ModuleDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$BaseDir = Split-Path -Parent $ModuleDir
$global:GUI = [hashtable]::Synchronized(@{Host=$Host})
$menu = @()
$global:last_output = 1.5


#-- WPF/WinForms widget wrapper
function W {
    <#
      .SYNOPSIS
................................................................................
    #>

    #-- ImgDir
    $ImgDir = $BaseDir
    #if (Test-Path "$($env:APPDATA)\multitool\img") { $ImgDir = "$($env:APPDATA)/multitool" }

    #-- load
    $xaml = ((Get-Content "$BaseDir/modules/wpf.xaml" | Out-String) -replace "e:/","$ImgDir/")
    $w = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml]$xaml)))

    #-- save aliases int $GUI (sync hash across all threads/runspaces)
    $GUI.w = $w
    $GUI.styles = $w.Resources
    $shortcuts = "Window,Menu,Ribbon,Grid_EXTRAS,Output,machine,username,bulkcsv"
    $shortcuts.split(",") | % { $GUI.$_ = $w.findName($_) } | Out-Null

    #--- return
    return $w
}


................................................................................
      .EXAMPLE
         New-GuiThread {code} -Funcs "copy1,copy2" -Vars "menu,GUI" -Modules "WPF"
      .NOTES
         Does not work with PS 5.0 yet (presumably scoping or syntax issue with func duplication).
    #>
    Param(
        $code = {},
        $funcs = "WPF-Window,W,WF,WD,Add-GuiMenu,Get-IconPath,Create-GuiParamFields,"+
                 "Out-Gui,Out-Html,Ask-Gui,Add-ButtonHooks,AD-Search,Get-MachineCurrentUser,"+
                 "Set-Clipboard,Set-ClipboardHtml,Get-Clipboard,Get-NotepadCSV,Extract-PluginMeta,preg_match_all",
        $modules = "",
        $vars = "menu",
        $level = "",
        [switch]$invoke=$true
    )

    #-- create, add functions and code
    $shell = [PowerShell]::Create()
    $shell.AddScript((
        ($funcs.split(",")  |  ? { $_ }  |  % { 
            $func = Get-Command $_ -CommandType Filter,Function,Cmdlet
           "$($func.CommandType) $($func.Name) { $($func.Definition) };`r`n"
        }) -join "`r`n"
    )) | Out-Null
#Write-Host -f green "'''$code'''"
    $shell.AddScript($code) | Out-Null

    #-- separate thread
    $shell.Runspace = [runspacefactory]::CreateRunspace()
    $shell.Runspace.ApartmentState = "STA"
    $shell.Runspace.ThreadOptions = "ReuseThread"         
    $shell.Runspace.Open() | out-null

    #-- add vars, modules
    $shell.Runspace.SessionStateProxy.SetVariable("GUI", $GUI) | out-null
    $shell.Runspace.SessionStateProxy.SetVariable("vars", @{}) | out-null

    $shell.Runspace.SessionStateProxy.SetVariable("in_thread", 1) | out-null
    $vars.split(",")  |  ? { $_ } |  % { $shell.Runspace.SessionStateProxy.SetVariable($_, (get-variable $_).value) } | Out-Null
    #$modules.split(",") | ?{$_} | % { $shell.Runspace.SessionStateProxy.ImportPSModule($_) } | Out-Null

    #-- start
    if ($invoke) {
       $handle = $shell.BeginInvoke()
    }
    return $shell
}
#-- no worky
function Attach-StreamEventHandler {
    #-- attaches an event handler to runspace streams (.error and .warning) to capture output
    #$shell.AddScript({
    #    $GUI.stream_error = $Error
    #})
    #Register-ObjectEvent -InputObject $shell.streams.error -EventName DataAdded -Action ({
    #    @{error="err"} | Out-String | Out-Gui -f Red
    #})
    #$shell.streams.error.add_DataAdded({
       # Param($sender, $event)
       #  $Error | Out-Gui -f Red
       #  @($Sender) | out-string | Out-Gui -f Red
       #  [void]($sender.ReadAll() | % { $_.Message | Out-Gui })
       #  Out-Gui "error" -f Red
    #})
}


#-- Look up icon basename path variations
function Get-IconPath {
    <#
      .SYNOPSIS
         Looks up alternative filenames for icons.





|







 







|
|







 







|





|







 







|
<
<








<
<
<
<
<
<
<











>
|

<







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







1
2
3
4
5
6
7
8
9
10
11
12
13
..
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
...
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
...
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
222

















223
224
225
226
227
228
229
# api: ps
# title: WPF + WinForms
# description: WinForm and WPF shortcuts, GUI and thread handling
# depends: menu, clipboard, sys:presentationframework, sys:system.windows.forms, sys:system.drawing
# doc: http://fossil.include-once.org/clickycoloury/wiki/W
# version: 1.0.9
# license: MITL
# type: functions
# category: ui
# config:
#   { name: cfg.threading, type: bool, value: 1, description: Enable threading/runspaces for GUI/WPF version }
#   { name: cfg.autoclear, type: int, value: 300, description: Clear output box after N seconds. }
#   { name: cfg.noheader, type: bool, value: 0, description: Disable script info header in output. }
................................................................................
Add-Type -AN System.Drawing, System.Windows.Forms, Microsoft.VisualBasic
# [System.Windows.Forms.Application]::EnableVisualStyles()
# [System.Windows.Forms.Application]::SetCompatibleTextRenderingDefault($true)

#-- init vars
$ModuleDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$BaseDir = Split-Path -Parent $ModuleDir
#$global:GUI = [hashtable]::Synchronized(@{Host=$Host})
#$menu = @()
$global:last_output = 1.5


#-- WPF/WinForms widget wrapper
function W {
    <#
      .SYNOPSIS
................................................................................
    #>

    #-- ImgDir
    $ImgDir = $BaseDir
    #if (Test-Path "$($env:APPDATA)\multitool\img") { $ImgDir = "$($env:APPDATA)/multitool" }

    #-- load
    $xaml = ((Get-Content "$BaseDir/modules/kbt5.xaml" | Out-String) -replace "e:/","$ImgDir/")
    $w = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml]$xaml)))

    #-- save aliases int $GUI (sync hash across all threads/runspaces)
    $GUI.w = $w
    $GUI.styles = $w.Resources
    $shortcuts = "Window,Menu,Ribbon,Grid_EXTRAS,Output,machine,username"
    $shortcuts.split(",") | % { $GUI.$_ = $w.findName($_) } | Out-Null

    #--- return
    return $w
}


................................................................................
      .EXAMPLE
         New-GuiThread {code} -Funcs "copy1,copy2" -Vars "menu,GUI" -Modules "WPF"
      .NOTES
         Does not work with PS 5.0 yet (presumably scoping or syntax issue with func duplication).
    #>
    Param(
        $code = {},
        $funcs = #"WPF-Window,W,WF,WD" no longer used, now reloading modules


        $modules = "",
        $vars = "menu",
        $level = "",
        [switch]$invoke=$true
    )

    #-- create, add functions and code
    $shell = [PowerShell]::Create()







    $shell.AddScript($code) | Out-Null

    #-- separate thread
    $shell.Runspace = [runspacefactory]::CreateRunspace()
    $shell.Runspace.ApartmentState = "STA"
    $shell.Runspace.ThreadOptions = "ReuseThread"         
    $shell.Runspace.Open() | out-null

    #-- add vars, modules
    $shell.Runspace.SessionStateProxy.SetVariable("GUI", $GUI) | out-null
    $shell.Runspace.SessionStateProxy.SetVariable("vars", @{}) | out-null
    $shell.Runspace.SessionStateProxy.SetVariable("ParentHost", $Host) | out-null
    $shell.Runspace.SessionStateProxy.SetVariable("in_thread", 1) | out-null #redundant now?
    $vars.split(",")  |  ? { $_ } |  % { $shell.Runspace.SessionStateProxy.SetVariable($_, (get-variable $_).value) } | Out-Null


    #-- start
    if ($invoke) {
       $handle = $shell.BeginInvoke()
    }
    return $shell
}



















#-- Look up icon basename path variations
function Get-IconPath {
    <#
      .SYNOPSIS
         Looks up alternative filenames for icons.

Name change from modules/wpf.xaml to modules/kbt5.xaml.

Changes to modules/starter.ps1.

1
2
3
4
5
6
7
8
9
10
11
12
13
..
70
71
72
73
74
75
76

77
78
79
80
81
82
83

84
85
86
87
88
89
90
..
98
99
100
101
102
103
104

105
106
107
108
109
110
111
112
113
114
115
116
117
# api: ps
# type: main
# title: ClickyColoury + TextyTypey - GUI+CLI tool frontend
# description: Convenience invocation of various Powershell and CMD scripts
# url: http://fossil.include-once.org/clickycoloury/
# version: 0.8.0
# depends: menu, wpf, clipboard
# category: misc
# config:
#   { name: cfg.gridview, type: select, value: Format-Table, select: Format-Table|Out-GridView, description: default table display mode }
#   { name: cfg.cli, type: bool, value: 0, description: Start console (CLI) version per default? }
#   { name: cfg.cached, type: bool, value: 0, description: Use CLIXML script cache on startup }
#   { name: debug, type: bool, value: 0, description: Powershell-internal } 
................................................................................
#-- restart if not in single-thread-apartment mode
if (-not [System.Management.Automation.Runspaces.Runspace]::DefaultRunSpace.ApartmentState -eq "STA") {
#    powershell.exe -Version 2.0 -STA -ExecutionPolicy unrestricted -File $curr_script_fn
#    break 2
}

#-- modules

$global:GUI = [hashtable]::Synchronized(@{Host=$Host})
Import-Module -DisableNameChecking "$($cfg.multitool_base)\modules\wpf.psm1"
Import-Module -DisableNameChecking "$($cfg.multitool_base)\modules\menu.psm1"
Import-Module -DisableNameChecking "$($cfg.multitool_base)\modules\clipboard.psm1"
if (!(Get-Module -Name ActiveDirectory)) { Import-Module ActiveDirectory }

#-- post init

$cfg.main = (Extract-PluginMeta $cfg.curr_script_fn)
#$global:GUI|FL



#-- predefined menu entries
$menu = @(
................................................................................
    $menu += @(Get-Item ($cfg.tool_dirs) | % { Extract-PluginMeta $_ } | ? { $_.api -and $_.type -and $_.title })
}
#-- add user plugins
if (Test-Path ($cfg.user_plugins_d)) {
    $menu += @(Get-Item "$($cfg.user_plugins_d)/*.ps1" | % { Extract-PluginMeta $_ } | ? { $_.type -and $_.api -eq "multitool" })
}
#-- run `type:init` plugins here

$menu | ? { $_.type -eq "init" -and $_.fn } | % { . $_.fn }


#-- CLI mode
if ($CLI) {
    Init-Screen
    $menu = $menu + @{key="m|menu"; category="extras"; title="print menu"; func='Print-Menu $menu'}
    Print-Menu $menu
    Process-Menu -Menu $menu -Prompt "TextyTypey"
}
#-- WPF multi-tool
else {
    echo "Starting GUI version..."





|







 







>

|





>







 







>





|







1
2
3
4
5
6
7
8
9
10
11
12
13
..
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
...
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# api: ps
# type: main
# title: ClickyColoury + TextyTypey - GUI+CLI tool frontend
# description: Convenience invocation of various Powershell and CMD scripts
# url: http://fossil.include-once.org/clickycoloury/
# version: 0.8.5
# depends: menu, wpf, clipboard
# category: misc
# config:
#   { name: cfg.gridview, type: select, value: Format-Table, select: Format-Table|Out-GridView, description: default table display mode }
#   { name: cfg.cli, type: bool, value: 0, description: Start console (CLI) version per default? }
#   { name: cfg.cached, type: bool, value: 0, description: Use CLIXML script cache on startup }
#   { name: debug, type: bool, value: 0, description: Powershell-internal } 
................................................................................
#-- restart if not in single-thread-apartment mode
if (-not [System.Management.Automation.Runspaces.Runspace]::DefaultRunSpace.ApartmentState -eq "STA") {
#    powershell.exe -Version 2.0 -STA -ExecutionPolicy unrestricted -File $curr_script_fn
#    break 2
}

#-- modules
Write-Host "Loading modules.."
$global:GUI = [hashtable]::Synchronized(@{Host=$Host})
Import-Module -DisableNameChecking "$($cfg.multitool_base)\modules\guimenu.psm1"
Import-Module -DisableNameChecking "$($cfg.multitool_base)\modules\menu.psm1"
Import-Module -DisableNameChecking "$($cfg.multitool_base)\modules\clipboard.psm1"
if (!(Get-Module -Name ActiveDirectory)) { Import-Module ActiveDirectory }

#-- post init
Write-Host "Scanning plugins.."
$cfg.main = (Extract-PluginMeta $cfg.curr_script_fn)
#$global:GUI|FL



#-- predefined menu entries
$menu = @(
................................................................................
    $menu += @(Get-Item ($cfg.tool_dirs) | % { Extract-PluginMeta $_ } | ? { $_.api -and $_.type -and $_.title })
}
#-- add user plugins
if (Test-Path ($cfg.user_plugins_d)) {
    $menu += @(Get-Item "$($cfg.user_plugins_d)/*.ps1" | % { Extract-PluginMeta $_ } | ? { $_.type -and $_.api -eq "multitool" })
}
#-- run `type:init` plugins here
Write-Host "Init plugins.."
$menu | ? { $_.type -eq "init" -and $_.fn } | % { . $_.fn }


#-- CLI mode
if ($CLI) {
    cls ; Init-Screen
    $menu = $menu + @{key="m|menu"; category="extras"; title="print menu"; func='Print-Menu $menu'}
    Print-Menu $menu
    Process-Menu -Menu $menu -Prompt "TextyTypey"
}
#-- WPF multi-tool
else {
    echo "Starting GUI version..."