Centralized Function

Hi,
Can we have functions centralized? EG, not need to repeat them on every page or dashboard?

Thanks

sure,

I just dot source the function file in my dashboard page, the same for dashboard pages

#.source functions
Get-ChildItem (Join-Path $PsscriptRoot -ChildPath ‘src’) -Filter “*.ps1” | ForEach-Object {
. $_.FullName
}

#add all the pages
$pages = Get-ChildItem (Join-Path -Path $PSScriptRoot -ChildPath “pages”) -Recurse -File | ForEach-Object {
& $PSItem.FullName
}

1 Like

Thank you for your response.

I might not have been clear with my question.

I am new to PowerShell universal so I just wanted to know where can I write functions and how to access them from different places.

Hi @Rajan52,

The 2 most popular options are:

  1. Create a Module to host your functions in and place it in the modules folder (Can be considered overfill for a few functions)
  2. Declare your functions in your dashboard or a loaded page as shown by @DavidB

e.g.

Where I have placed a comment on line 5. You can load a page here containing your functions if you wish to keep them all in a ps1 file.

2 Likes

I am just giving my two cents, but option 1 is very annoying to work with. I don’t seem to be able to target that file in vscode and it requires you to not only save the file, but also restart any existing dashboards so that they reload the module. This makes debugging tedious and has led me to completely avoid this option. Option 2 used to not be very tidy, but with the introduction of pages I think it makes the most sense. Reminds me of when people would create a “measures” table in powerBI to store their DAX code!

1 Like

Hi @djanszen,

Agreed, however, these are purely options to solve a problem in the absence of any others.

In development, I would create the function in the main page, then later on move the snippet of code to its final destination.

2 Likes

@djanszen
Apologies if that came over a little blunt that was far from my intention.

Solutions are not always streamlined or elegant on the 1st iteration :slight_smile:

Nope. Not at all. That is why I quoted the PowerBI DAX example, which is owned by Microsoft!

1 Like

I just dot source everything. I maintain the same file structure that holds all source scripts on my workstation as on PSU using dropbox or pcloud or onedrive so the script files sync. Edit the dot sourced files locally and they upload on any changes in a few seconds. Dashboard can be restarted from VS Code as well.

1 Like