Repository navigation
Using Functions in Button Actions #6
Replies: 1 comment
|
Right, functions from your script aren't visible inside an action. The reason determines the workarounds:
So any of these work. I checked each by reproducing the same pipeline (one reused runspace, actions passed as 1. Dot-source a helpers file (or Add-UICanvasButton 'Run' -Action {
. 'C:\Tools\MyApp\helpers.ps1' # absolute path: $PSScriptRoot is empty here
Get-Greeting 'button A'
}After the first action has loaded it, other actions can call 2. Insert the path at authoring time. Since the action is just text, build it with $helpers = Join-Path $PSScriptRoot 'helpers.ps1'
Add-UICanvasButton 'Run' -Action ([scriptblock]::Create(". '$helpers'; Get-Greeting 'button A'"))3. Copy functions you already defined in your script into the action: function Get-Thing { param($x) "thing: $x" }
function Format-Thing { param($t) "[$t]" }
$defs = foreach ($n in 'Get-Thing','Format-Thing') {
"function $n {`n$((Get-Item "function:$n").ScriptBlock)`n}"
}
Add-UICanvasButton 'Run' -Action ([scriptblock]::Create(
($defs -join "`n") + "`n" + 'Show-UICanvasToast (Format-Thing (Get-Thing "clicked"))'
))This keeps everything in one script file, with no external helpers file. Note that variables from your script aren't available inside actions either, for the same reason. To pass data, use reactive state ( |
Uh oh!
There was an error while loading. Please reload this page.
Hello,
I've been playing around with PoshUI and as far as I can tell from using it and the documentation I've read is that in a button action, I cannot use functions that are defined outside of the action. Is there anyway to get around this or a way to import functions into the action?
All reactions