Only this pageAll pages
Powered by GitBook
Couldn't generate the PDF for 128 pages, generation stopped at 100.
Extend with 50 more pages.
1 of 100

v1

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

API

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Automation

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Dashboard

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Data Display

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Data Visualization

Loading...

Loading...

Feedback

Loading...

Loading...

Loading...

Loading...

Inputs

Input controls for Universal Dashboard

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Navigation

Loading...

Loading...

Loading...

Layout

Loading...

Loading...

Loading...

Utilities

Loading...

Surfaces

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Get Started

Get started with PowerShell Universal

Install PowerShell Universal

You can install PowerShell Universal as a service using Chocolatey.

choco install powershelluniversal

You can install PowerShell Universal using the Universal PowerShell module.

Install-Module Universal
Install-PSUServer -AddToPath
Start-PSUServer -Port 5000

You can install PowerShell Universal using the Universal PowerShell module.

Install-Module Universal
Install-PSUServer -AddToPath
Start-PSUServer -Port 5000

Open PowerShell Universal

By default, PowerShell Universal is running on port 5000 of localhost. You can access the admin console with the user name admin and any password.

PowerShell Universal Visual Studio Code Extension

You can connect to your instance of PowerShell Universal, browse and insert samples and get up and running right away.

Install the Extension

Install the extension by searching for it in the extension page and clicking Install.

Connect to PowerShell Universal

Click the PowerShell Universal icon on the left hand side and the extension will attempt to connect using the default URL and user name. The extension will notify you once it has connected.

Inserting a Sample

Learn more about the various features of PowerShell Universal

You'll need to install the PowerShell Universal server. but you can use the command line below to get started quickly.

We recommend installing the to provide the best possible editing experience.

are available via the sample browser. You can select a sample and insert it into your PowerShell Universal instance. You'll need to save the file that is opened by Visual Studio Code for the sample to be inserted.

There are a lot of ways to do so
PowerShell Universal Visual Studio Code Extension
Samples
APIs
Automation
Dashboards

Additional Resources

Download the latest version of PowerShell Universal.

The Ironman Software blog has articles about PowerShell Universal.

Connect with the PowerShell Universal community.

Chat with other PowerShell Universal users.

Purchase a license for the features of PowerShell Universal.

File a bug report or feature request for PowerShell Universal.

Check out video tutorials for PowerShell Universal.

Upgrading

This document covers upgrading the PowerShell Universal application.

General

The Universal application binaries can generally be upgraded without having to change the configuration or database manually. This document will cover how to upgrade the application and some caveats to be aware of in regards to configuration and data persistence.

Data Persistence

Data is persisted in a LiteDB database with a default location of %ProgramData%\UniversalAutomation\database.db. The database will not be deleted during an upgrade of any kind. Any schema updates to the database will happen the first time you start up the new version of Universal. You may wish to backup your database before performing an upgrade.

Configuration Persistence

Configuration files are stored by default in %ProgramData%\UniversalAutomation. Configuration files may be updated or transformed during an update. This will happen the first time that the new version of Universal server is started. You may wish to backup your configuration files before performing an upgrade.

If you are using git, changes to the Universal files will be synchronized after the server starts up.

appsettings.json

web.config

Dashboard Components and Frameworks

New versions of Universal may include new versions of Universal Dashboard Frameworks or Components. By default, these components and frameworks are deployed to %ProgramData%\PowerShellUniversal during startup of the Universal server. During an upgrade, these files are not deleted. This ensures that dashboards will continue to run on the previous dashboard framework and component versions.

You should have multiple versions of the dashboard frameworks and components available when you start the new version of Universal.

By default, new dashboards are set to always use the latest version of the dashboard framework. You can chose to set it to a specific version if you would like but will have to manually change the version during an upgrade.

Repository

Most of the settings for PowerShell Universal are stored within the repository folder. By default, this is in %ProgramData%\UniversalAutomation\Repository. While the upgrade should not affect these files, you may want to backup the files before upgrading.

ZIP Upgrade

Always ensure to run Unblock-File on Windows to unblock all the files extracted the ZIP. If you do not, PowerShell Universal will not function properly.

When upgrading an manual ZIP file installation, you will need to stop the application, delete the entire binary folder and replace it with the new binary folder. When you start the new version of Universal, new dashboard frameworks and components will be deployed and the existing database will be loaded.

MSI Upgrade

To upgrade using the MSI, you can simply run the new version of the MSI. The MSI is setup to always perform a major upgrade. This means it will stop and remove the service, delete the entire installation directory, reinstall with the new files and then install and start the new service.

You will want to follow the guide on data and configuration persistence above to ensure all your settings are saved.

If you have configured a service account for your MSI installation, you will need to set the service account after upgrading.

IIS Upgrade

When upgrading with IIS, you will need to first stop your application pool to ensure that the binaries used by IIS are no longer in use and then replace the binaries with the new ones. Ensure that you follow the configuration persistence recommendations above with regards to the web.config file.

LiteDB v5 Upgrade

PowerShell Universal uses LiteDB to store jobs, app tokens, identities and git sync history. The original version of LiteDB included with PSU is version 4. We will be moving to version 5 in a future version. We have added version 5 support but are not yet upgrading users databases. You can choose to upgrade your database to version 5 by adjusting your connection string to perform an upgrade on the database. We suggest backing up your database file before doing so.

In appsettings.json, you will need to change the database type to LiteDBv5 and add the upgrade parameter to the connection string.

    "Data": {
    "RepositoryPath": "%ProgramData%\\UniversalAutomation\\Repository",
    "ConnectionString": "filename=%ProgramData%\\UniversalAutomation\\database.db;upgrade=true",
    "DatabaseType": "LiteDBv5",

About

Universal is a platform for building web-based IT tools.

Universal is a cross-platform solution for developing web-based tools with PowerShell. It currently provides three main features which include APIs, Automation and Dashboards.

Universal provides an Administrator console, management REST API, PowerShell cmdlets and a idempotent configuration system using PowerShell scripts.

APIs

  • Build REST endpoints with PowerShell

  • Accept common HTTP verbs

  • Process request bodies

  • Build dynamic URLs with route parameters and query strings

Automation

  • Run scripts and view output, pipeline output, and parameters

  • Respond to feedback from cmdlets like Read-Host

  • Schedule scripts with CRON or one-time schedules

  • Automatically build input forms based on param blocks

  • Set variables and secrets that can be used throughout scripts

Dashboard

  • Build web pages with PowerShell script

  • Include input forms, charts and tables

  • Build interactive websites with buttons, message boxes and more

Platform

  • Cross-platform and supported on Windows and Linux

  • Git integration for configuration files, scripts and dashboards

  • Built-in authentication and authorization

  • Support for Windows PowerShell as well as PowerShell

Licensing

Free to Use

Universal offers a lot of functionality for free. Below is a list of the features that require a paid license.

API

You can run as many APIs are you want for free. You will need to purchase a license if you would like to enable authentication, authorization and rate limiting.

Automation

Dashboard

With the free version of dashboard, you can run unauthenticated dashboards. You will not have access to the diagnostics or console pages.

Samples that can be inserted into your PowerShell Universal system using the .

The appsettings.json file that is included in the application installation directory will be overwritten during upgrades. To avoid losing your settings in this file, consider installing it into the %ProgramData%\PowerShellUniversal folder. Universal will look at this folder first for

The web.config file that is included in the application installation directory will be overwritten during upgrades. If you have moved your web.config file to an alternate location, it will not be overwritten. When creating an IIS website, you can simply include the web.config file in the web app's directory and have the .

Universal is licensed per feature and per server. You do not need to buy the entire platform if you would like to use a single piece of functionality. Visit our on pricing.

With the free version of Automation you can run up to 25 jobs a day with 2 jobs running concurrently. You will need a license to use .

Downloads
Blog
Forums
Discord
Purchasing
Issue Tracker
Samples
PowerShell Universal extension for Visual Studio Code
Videos
binaries stored in a different location
Download Universal for free
website for more information
triggers

Licensing

PowerShell Universal is licensed per server. We provide licenses for individuals and organizations.

What's a server?

A server is a single running instance of PowerShell Universal.

Free Use Restrictions

Universal can be used forever for free with the following limitations.

Universal API

  • No authentication

  • No Rate Limiting

Universal Automation

  • 25 jobs per day

  • 2 concurrent jobs

  • No Triggers

Universal Dashboard

  • No authentication

  • No access to diagnostic tools

System Requirements

Windows

Linux

  • PowerShell v7.0 or great

  • Validated Distributions: Ubuntu 18.04

Mac OS X

Supported Browsers

Universal uses a variety of modern web frameworks and can have issues with older browsers such as Internet Explorer.

Visual Studio Code Extension

Learn about the Visual Studio Code extension for Universal.

PowerShell Universal can be managed with the PowerShell Universal Visual Studio Code extension. It allows you to connect to a local Universal instance and manage APIs, dashboards and scripts.

Installation

Configuration

The extension will prompt you for the URL and App Token used to connect to your PowerShell Universal instance. Follow the instructions within the extension when it starts up.

Features

The PowerShell Universal extension adds a new activity pane panel for PowerShell Universal. It has the following sections.

APIs

You can manage APIs with the extension. You will see a list of APIs. You can click the Open endpoints.ps1 button to view the endpoints file and add new endpoints. Clicking the refresh button will reload any endpoints you add. You can click the Insert Invoke-RestMethod to Console to add a call to the endpoint to the PowerShell Integrated Console.

Dashboards

You can manage dashboards with the extension. You will see a list of dashboards underneath this section. You can open the dashboards.ps1 script, open the a single dashboard's script, restart a dashboard and view dashboards. When you open a dashboard script, the dashboard modules will automatically be loaded so that IntelliSense works in VS Code.

Debug Dashboard Process

You can connect the Visual Studio debugger to the dashboard process by right clicking on the dashboard and click Debug Dashboard Process. This requires the PowerShell extension for Visual Studio Code.

After connecting the debugger, you can run commands such as Get-Runspace and Debug-Runspace to begin debugging aspects of your dashboard.

View Dashboard Logs

You can view dashboard logs by right clicking on the dashboard and clicking View Logs. They will open in a new tab.

Scripts

You can manage scripts with the extension. You will see a list of available scripts underneath this section. You can edit the scripts.ps1, edit an individual script and run scripts. When running scripts, you will receive feedback about the status of the script. Scripts with parameters are not supported in VS Code. You can still run them in PowerShell Universal.

Sample Browser

The sample browser can be used to insert samples from the PowerShell Universal Sample Repository into your PowerShell Universal instance. Just save the files it updates and your PowerShell Universal system will reflect the changes.

You can purchase a license on .

or greater or PowerShell v7.0 or greater

(only for Windows PowerShell)

The current version of the following web browsers are supported: , , , and

We make a best effort to support Internet Explorer 11 for Universal Dashboard. IE11 is not supported for the Admin Console. There may be issues with certain components as we do not extensively test each change in IE11. If you desire particular functionality in IE11, please .

You can download the extension from the . You can also download the extension from within the Visual Studio Code extension pane. Search for PowerShell Universal and click Install.

our website
Windows PowerShell v5.1
.NET Framework v4.7.2
Chrome
Firefox
Safari
Microsoft Edge
file an issue
Visual Studio Marketplace

Monitoring

Retro Dashboard

This retro looking dashboard displays the top 10 CPU and memory using processes, disk usage, and live CPU and network usage. It also demonstrates how to use themes to custom the backcolor, text color and font family.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUDashboard -Name 'Hacker Dash' -BaseUrl '/' -Component 'UniversalDashboard.Charts:1.3.1' -Framework 'UniversalDashboard:Latest' -Content {

    $Green =  '#4bdd35'

    $Theme = @{
        palette = @{
            primary = @{
                main = $Green
            }
            background = @{
                default = 'black'
                paper = 'black'
            }
            text = @{
                primary = $Green
            }
        }
        typography = @{
            fontFamily = "Consolas"
        }
    }

    $Pages = @()
    $Pages += New-UDPage -Name 'Hacker Dash' -Content {

        New-UDRow -Columns {
            New-UDColumn -LargeSize 4 -Content {
                    New-UDCard -Title 'Top CPU Usage Processes' -Content {
                        New-UDElement -Tag 'pre' -Content {
                            (Get-Process | Sort-Object -Property Cpu -Descending | Select-Object -First 10 | Out-String)
                        }
                    } 

            }
            New-UDColumn -LargeSize 4 -Content {
                $Data = Get-CimInstance -Class CIM_LogicalDisk | Select-Object @{Name="Size";Expression={$_.size/1gb}}, @{Name="FreeSpace";Expression={$_.freespace/1gb}}, @{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}}, DeviceID, DriveType | Where-Object DriveType -EQ '3'

                $SizeDs = New-UDChartJSDataset -DataProperty Size -Label Size -BackgroundColor $Green
                $MemoryDs = New-UDChartJSDataset -DataProperty FreeSpace -Label 'Free Space' -BackgroundColor $Green


                $Options = @{
                    Type = 'bar'
                    Data = $Data
                    Dataset = @($SizeDs, $MemoryDs)
                    LabelProperty = "DeviceId"
                }

                New-UDChartJS @Options
            }
            New-UDColumn -LargeSize 4 -Content {
                New-UDChartJSMonitor -LoadData {
                     Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select -Expand Average | Out-UDChartJSMonitorData
                } -Labels "CPU" -ChartBackgroundColor 'black' -ChartBorderColor $Green -RefreshInterval 1
            }
        }

        New-UDRow -Columns {
            New-UDColumn -LargeSize 4 -Content {
                    New-UDCard -Title 'Top Memory Usage Processes' -Content {
                        New-UDElement -Tag 'pre' -Content {
                            (Get-Process | Sort-Object -Property WorkingSet64 -Descending | Select-Object -First 10 | Out-String)
                        }
                    } 
            }
            New-UDColumn -LargeSize 4 -Content {
                New-UDChartJSMonitor -LoadData {
                     (Get-NetAdapterStatistics -Name 'Wi-Fi').SentBytes | Out-UDChartJSMonitorData
                } -Labels "Send Bytes" -ChartBackgroundColor 'black' -ChartBorderColor $Green -RefreshInterval 1
            }
            New-UDColumn -LargeSize 4 -Content {
                New-UDChartJSMonitor -LoadData {
                     (Get-NetAdapterStatistics -Name 'Wi-Fi').ReceivedBytes | Out-UDChartJSMonitorData
                } -Labels "Received Bytes" -ChartBackgroundColor 'black' -ChartBorderColor $Green -RefreshInterval 1
            }
        }



    } 

    New-UDDashboard -Title "Hello, World!" -Pages $Pages -Theme $Theme
    }
}

Windows Performance Counter Charts

In this example, we take advantage of Universal Dashboard scheduled endpoints, the in-memory cache and the UDMonitor component. We update the counter sets to use in the cache and load each of the counters' value in the set into an array to use in the dashboard. We then create a dashboard that dynamically creates UDMonitor charts within the page. Each monitor will update every 3 seconds with new data.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUDashboard -Name 'Performance' -BaseUrl '/' -Framework 'UniversalDashboard:Latest' -Content {

        $Schedule = New-UDEndpointSchedule -Every 5 -Second
        New-UDEndpoint -Schedule $Schedule -Endpoint {
            if (-not $Cache:CounterSets)
            {
                $Cache:CounterSets = Get-Counter -ListSet * | Select-Object -ExpandProperty 'CounterSetName'
                $Cache:CurrentSets = @( "IPv4")
            }

            $Cache:Data = @()
            foreach($set in $Cache:CurrentSets)
            {
                $Data = @{
                    Set = $set
                    Counters = @()
                }

                $Counters = (Get-Counter -ListSet $set).Paths
                foreach($Counter in $Counters)
                {

                    $Value = 0 
                    try {
                        $Value = (Get-Counter -Counter $Counter -ErrorAction SilentlyContinue).CounterSamples[0].CookedValue
                    } catch {}

                    $Data.Counters += @{ Name = $Counter; Value = $Value }
                }

                $Cache:Data += $Data
            }
        } | Out-Null

        New-UDDashboard -Title 'Performance' -Content {
            foreach($Data in $Cache:Data)
            {
                New-UDTypography -Text $Data.Set -Variant h4
                New-UDRow -Columns {
                    foreach($Counter in $Data.Counters)
                    {
                        New-UDColumn -Size 4 -LargeSize 3 -Content {
                            New-UDTypography -Text $Counter.Name
                            New-UDChartJSMonitor -LoadData {
                                $Set = $Cache:Data | Where-Object Set -eq $Data.Set
                                $Value = ($Set.Counters | Where-Object Name -eq $Counter.Name).Value
                                if (-not $Value)
                                {
                                    $Value = 0
                                }
                                $Value | Out-UDChartJSMonitorData
                            } -Labels "Value" -ChartBackgroundColor "#297741" -RefreshInterval 3 -DataPointHistory 10
                        } 
                    }
                }
            }
        }
    } -Component @("UniversalDashboard.Charts:1.3.0")
}

Active Directory

Active Directory examples for PowerShell Universal.

List Locked Accounts

Shows an example of how to list locked Active Directory accounts. This example assumes that the user running PowerShell Universal has access to the local Active Directory environment.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUScript -Name 'LockedAccounts' -ScriptBlock {
        Search-ADAccount -LockedOut
    }
}

Locked accounts will be listed on the job page's pipeline output.

You can also access the locked accounts by using the Universal PowerShell module.

$Job = Get-PSUJob -Script (Get-PSUScript -name 'LockedAccounts.ps1') -First 1 -OrderDirection Descending
Get-PSUJobPipelineOuptut -Job $Job

Reset Password

Shows an example of how to reset an Active Directory user account using PowerShell Universal Automation. This script accepts the identity of the account to reset, the password to set, whether to unlock the account and whether to require the user to change their password on logon.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUScript -Name 'Reset Password' -ScriptBlock {
        param(
            [String]$Identity,
            [String]$Password,
            [Switch]$Unlock,
            [Switch]$ChangePasswordOnLogon
        )

        $SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force

        Set-ADAccountPassword -Identity $Identity -NewPassword $SecurePassword -Reset -Server $ComputerName -Credential $Domain

        if ($Unlock)
        {
            Unlock-ADAccount –Identity $Identity -Server $ComputerName -Credential $Domain
        }

        if ($ChangePasswordOnLogon)
        {
            Set-ADUser –Identity $Identity -ChangePasswordAtLogon $true -Server $ComputerName -Credential $Domain
        }
    }
}

Restore Deleted User

In this example, we use Universal Dashboard to create a dashboard that displays a table that includes all the deleted user accounts for the domain. It creates a custom column with a button that includes a Restore button that executes a script to restore the specified account. This example assumes that the identity running the script is capable of accessing Active Directory.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUScript -Name 'Restore User.ps1' -ScriptBlock {
        param($DistinguishedName)

        Restore-ADObject -Identity $DistinguishedName
    }

    New-PSUDashboard -Name 'Restore User' -BaseUrl '/' -Framework 'UniversalDashboard:Latest' -Content {
        New-UDDashboard -Title 'Restore User' -Content {
            $Columns = @(
                New-UDTableColumn -Property Name -Title "Name"
                New-UDTableColumn -Property DistinguishedName -Title "Distinguished Name"
                New-UDTableColumn -Property Restore -Title Restore -Render {
                    $Item = $EventData
                    New-UDButton -Id "btn$($Item.ObjectGuid)" -Text "Restore" -OnClick { 
                        Show-UDToast -Message "Restoring user $($Item.Name)" -Duration 5000

                        Invoke-UAScript -Name 'Restore User.ps1' -DistinguishedName $Item.DistinguishedName | Tee-Object -Variable job | Wait-UAJob

                        $Job = Get-UAJob -Id $Job.Id 
                        if ($Job.Status -eq 'Completed')
                        {
                            Show-UDToast -Message "Restored user $($Item.Name)" -Duration 5000
                        }
                        else 
                        {
                            $Output = Get-UAJobOutput -JobId $Job.Id | Select-Object -Expand Message
                            Show-UDToast -Message "Failed to restore user. $($Output -join "`n")" -BackgroundColor red -MessageColor white -Duration 5000
                        }
                    }
                }
            )

            $DeletedUsers = Get-ADObject -Filter 'IsDeleted -eq $true -and objectClass -eq "user"' -IncludeDeletedObjects | ForEach-Object {
                @{
                    distinguishedname = $_.DistinguishedName
                    name = $_.Name
                }
            }
            New-UDTable -Data $DeletedUsers -Columns $Columns
        }
    }
}

Examples

Examples of PowerShell Universal configurations.

Component Examples

We maintain several component libraries that you can use in your dashboards directly or as examples.

Single-File Configuration Examples

This page contains examples of PowerShell Universal configurations. All examples are built using single-file hosting and configuration. These examples assume that you have PowerShell Universal installed. To install PowerShell Universal, use the following command line.

Install-Module Universal
Install-PSUServer -AddToPath

You can login to PowerShell Universal using the username admin and any password.

Table of Contents

  • Active Directory

  • Hyper-V

  • Image Processing

  • Monitoring

  • Slack

Hyper-V

Hyper-V examples for PowerShell Universal.

Virtual Machine Creator

This example can be used to create virtual machines on a Hyper-V host. This dashboard assumes it's being run on the host in question. You could adjust the dashboard script to run on a remote host.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUDashboard -Name 'Hyper-V' -BaseUrl '/' -Framework 'UniversalDashboard:Latest' -Content {

        $HostRam = Get-WMIObject -class Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | % {[Math]::Round(($_.sum / 1GB *0.97),0)-1}
        $HostName=hostname
        $SwitchList = @()
        Get-VMSwitch | Select-Object -ExpandProperty name | ForEach-Object {
            $SwitchList += $_
        }

        function Run-Checks
        {
            $VMHostInfo= Get-VMHost

            $BootISOTextBoxText = (Get-UDElement -Id 'VMBootISO')['value']
            $VHDRootTextBoxText = (Get-UDElement -Id 'VMVHDRoot')['value']
            $VMNameTextBoxText = (Get-UDElement -Id 'VMName')['value']
            $Generation = (Get-UDElement -Id 'VMGeneration')['value']
            $SwitchNameComboBoxText = (Get-UDElement -Id 'VMSwitch')['value']
            $RAMinGBTextBoxText = (Get-UDElement -Id 'VMRam')['value']
            $CPUCountTextBoxText = (Get-UDElement -Id 'VMCPU')['value']
            [int64]$VLANIDTextBoxText = (Get-UDElement -Id 'VMVLan')['value']

            #Paths and Gen Sets    
            if ($BootISOTextBoxText -and $BootISOTextBoxText -ne "") {$ISOFilePathValid = test-path $BootISOTextBoxText}
            if ($VHDRootTextBoxText -and $VHDRootTextBoxText -ne "") {$VHDBootPathValid = test-path $VHDRootTextBoxText}
            if ($Generation -eq 'Gen1') { $VMGeneration = 1 } else { $VMGeneration = 2 } 

            if ($VMNameTextBoxText.Length -ne 0) { $VMExists = Get-VM -name $VMNameTextBoxText -ErrorAction SilentlyContinue }

            if (-not (Test-Path $VMHostInfo.VirtualMachinePath) ) {Show-UDToast -Message  "Default Virtual Machine path is not valid in HyperV Host Settings"}
            elseif (-not (Test-Path $VMHostInfo.VirtualHardDiskPath) ) {Show-UDToast -Message  "Default Virtual Harddisk path is not valid in HyperV Host Settings"}
            elseif ($VMExists) {Show-UDToast -Message  "VM with that name already exists"}
            elseif ($VMNameTextBoxText.Length -eq 0) {Show-UDToast -Message  "Please Enter VM Name"}
            elseif ($SwitchNameComboBoxText -eq "Switch Name") {Show-UDToast -Message  "Please Select a Switch Name"}
            elseif ($ISOFilePathValid -eq $False) {Show-UDToast -Message  "ISO File path in invaild"}
            elseif ($VHDRootTextBoxText -eq "") {Show-UDToast -Message  "VHD Root path is blank.  Please enter a valid path"}
            elseif ($VHDBootPathValid -eq $False) {Show-UDToast -Message  "VHD Root path in invaild"}
            elseif ($RAMinGBTextBoxText.Length -eq 0) {Show-UDToast -Message  "Please Enter Ram Amount in GB"}
            elseif ([int64]$RAMinGBTextBoxText -lt 1) {Show-UDToast -Message  "Please Enter Ram Amount of at least 1GB"}
            elseif ([int64]$RAMinGBTextBoxText -gt $HostRam) {Show-UDToast -Message  "Please Enter Ram Amount of "+ $HostRam + "GB or bellow"}
            elseif ($CPUCountTextBoxText.Length -eq 0) {Show-UDToast -Message  "Please Enter a CPU Count"}
            elseif ([int64]$CPUCountTextBoxText.Length -eq 0) {Show-UDToast -Message  "Please Enter a CPU Count"}
            elseif ([int64]$CPUCountTextBoxText -lt 1) {Show-UDToast -Message  "Please Enter a CPU Count of at least 1"}
            elseif ([int64]$CPUCountTextBoxText -gt 64) {Show-UDToast -Message  "Please Enter a CPU Count of 64 or below"}
            elseif ([int64]$VLANIDTextBoxText -gt 999 -or [int64]$VLANIDTextBoxText -lt 1) {Show-UDToast -Message  "Please Enter VLAN ID between 1 and 999."}
            else 
            {
                (65..90) | ForEach-Object { 
                    $DriveLetter = [char]$_  

                    [int64]$value = (Get-UDElement -Id "Drive$DriveLetter")['value']

                    if ($value -gt 65536)
                    {
                        Show-UDToast -Message  "For $DriveLetter Drive please Enter a Disk Size of 65536 GB or below"
                        return $false
                    }
                } 

                Show-UDToast -Message  "Looking Good Man ;)"

                return $true
            }

            return $false
        }

        function Create-VMs
        {
            Run-Checks

            $BootISOTextBoxText = (Get-UDElement -Id 'VMBootISO')['value']
            $VHDRootTextBoxText = (Get-UDElement -Id 'VMVHDRoot')['value']
            $VMNameTextBoxText = (Get-UDElement -Id 'VMName')['value']
            $Generation = (Get-UDElement -Id 'VMGeneration')['value']
            [int]$SwitchNameComboBoxIndex = (Get-UDElement -Id 'VMSwitch')['value']
            $SwitchNameComboBoxText = $SwitchList[$SwitchNameComboBoxIndex]
            Show-UDToast -message ((Get-UDElement -Id 'VMSwitch') | ConvertTo-Json)
            $RAMinGBTextBoxText = (Get-UDElement -Id 'VMRam')['value']
            $CPUCountTextBoxText = (Get-UDElement -Id 'VMCPU')['value']
            $VLANIDTextBoxText = (Get-UDElement -Id 'VMVLan')['value']

            if ($Generation -eq 'Gen1') { $VMGeneration = 1 } else { $VMGeneration = 2 } 

            #Create VM

            try
            {
                New-VM -Name $VMNameTextBoxText -MemoryStartupBytes ([int]$RAMinGBTextBoxText*1073741824) -SwitchName $SwitchNameComboBoxText -Generation $VMGeneration -ErrorAction Stop
            }
            catch
            {
                $VMCrateFailed=$True
                Show-UDToast -Message ("VM " + $VMNameTextBoxText + " Failed to Create :( $($_.Exception.Message)")
            }


            if (-Not($VMCrateFailed -eq $True))
            {
                (65..90) | ForEach-Object { 
                    $DriveLetter = [char]$_  
                    [int64]$value = (Get-UDElement -Id "Drive$DriveLetter")['value']
                    if ($value -gt 0)
                    {
                        $Path = $VHDRootTextBoxText+"\"+$VMNameTextBoxText+"\"+$VMNameTextBoxText+"-"+$value+".vhdx"
                        if (-not (test-path $Path)) 
                        {
                            New-VHD -Path $Path -SizeBytes (Invoke-Expression ("$($Value)GB")) -Dynamic
                        } 
                        else 
                        {
                            $VHDPathExisted = $true
                        }
                    }
                } 

            Get-VM $VMNameTextBoxText | Set-VMProcessor -Count $CPUCountTextBoxText
            Get-VM $VMNameTextBoxText | set-VMNetworkAdapterVlan -Access -vlanId $VLANIDTextBoxText

            (65..90) | ForEach-Object { 
                $DriveLetter = [char]$_  
                [int64]$value = (Get-UDElement -Id "Drive$DriveLetter")['value']
                $Path = $VHDRootTextBoxText+"\"+$VMNameTextBoxText+"\"+$VMNameTextBoxText+"-"+$value+".vhdx"

                if (Test-Path $Path)
                {
                    Add-VMHardDiskDrive -VMName $VMNameTextBoxText -Path $Path -ControllerType SCSI -ControllerNumber 0
                }
            } 

            # 
            #  REMOVING NETWORK FROM THE BOOT ORDER

            #Set New Boot order
            if ($VMGeneration -eq "2")
                {
                    $old_boot_order = Get-VMFirmware -VMName $VMNameTextBoxText -ComputerName $HostName | Select-Object -ExpandProperty BootOrder
                    $new_boot_order = $old_boot_order | Where-Object { $_.BootType -ne "Network" }
                    Set-VMFirmware -VMName $VMNameTextBoxText -ComputerName $HostName -BootOrder $new_boot_order
                }


            #  ADD DVD Drive with ISO Attached
            if ($BootISOTextBoxText -ne "")
            {
                Get-VM $VMNameTextBoxText | Add-VMDvdDrive -Path $BootISOTextBoxText
            }

            if ($VHDPathExisted) {
                Show-UDToast -Message ("VM " + $VMNameTextBoxText + " Created OK, but at least one VHD already existed and was just reattached")
            }
            else 
            {
                Show-UDToast -Message ("VM " + $VMNameTextBoxText + " Created OK")}
            }
        }


        New-UDDashboard -Title "Hyper-V VM Creator" -Content {
            New-UDContainer -Children {
                New-UDTypography -Text "Hyper-V VM Creator" -Variant h3 

                New-UDRow -Columns {
                    New-UDColumn -LargeSize 6 -Content {
                        New-UDRow -Columns {
                            New-UDTextbox -Label 'VM Name' -Id 'VMName'
                        }
                        New-UDRow -Columns {
                            New-UDTextbox -Id 'VMRam' -Label 'RAM in GB' -Value $HostRam
                        }
                        New-UDRow -Columns {
                            New-UDTextbox -Id 'VMCPU' -Label 'CPU Count' -Value 2
                        }

                        New-UDRadioGroup -Label 'Generation' -Id 'VMGeneration' -Children {
                            New-UDRadio -Label 'Gen 1' -Value 'Gen1'
                            New-UDRadio -Label 'Gen 2' -Value 'Gen2'
                        } -Value 'Gen1'
                    }
                    New-UDColumn -LargeSize 6 -Content {
                        New-UDRow -Columns {
                            New-UDSelect -Id 'VMSwitch' -Label 'Switch Name' -Option {
                                $i = 0
                                $SwitchList | ForEach-Object {
                                    New-UDSelectOption -Value $i -Name $_
                                    $i++
                                }
                            }
                        }

                        New-UDTextbox -Id 'VMVLan' -Label 'VLAN ID'
                    }
                }

                New-UDRow -Columns {
                    New-UDColumn -LargeSize 12 -Content {
                        New-UDTextbox -Id 'VMBootISO' -Label 'Boot ISO'
                    }
                }

                New-UDRow -Columns {
                    New-UDColumn -LargeSize 12 -Content {
                        New-UDTextbox -Id 'VMVHDRoot' -Label 'VHD Root'
                    }
                }

                New-UDTypography -Text 'Drives' -Variant h4

                New-UDRow -Columns {
                    New-UDColumn -LargeSize 6 -Content {
                        New-UDRow -Columns {
                            # Loop through each letter of the alphabet
                            (65..90) | ForEach-Object { 
                                New-UDColumn -LargeSize 6 -Content {
                                    $DriveLetter = [char]$_  
                                    New-UDTextbox -Id "Drive$DriveLetter" -Placeholder $DriveLetter
                                }
                            } 
                        }
                    }
                    New-UDColumn -LargeSize 6 -Content {
                        New-UDButton -Text 'Do Some Checks' -OnClick { Run-Checks }
                        New-UDButton -Text 'Im feeling lucky Create Vm' -OnClick { Create-VMs }
                    }
                }
            }
        }
    }

}

Installation

Installation instructions for PowerShell Universal.

Getting Started

PowerShell Module

You can use the PowerShell Universal PowerShell module to install the Universal server. To install the module, use Install-Module.

Install-Module Universal

To install the Universal server, you can use Install-PSUServer.

Install-PSUServer -LatestVersion

You can configure the path that the server is stored in by using the -Path parameter.

Install-PSUServer -Path (Join-Path $Env:AppData "PSU")

You can add the PSU server to the PATH environment variable by use the -AddToPath parameter.

Install-PSUServer -AddToPath

Once the server has been installed, you can use Start-PSUServer to start it.

Start-PSUServer -Port 8080

You can specify the path to the executable using the -ExecutablePath parameter. If you have set the location of the server to -AddToPath with Install-PSUServer, Start-PSUServer should find the executable automatically.

Start-PSUServer -Port 8080 -ExecutablePath (Join-Path $MyPath "Universal.Server.exe")

Chocolatey Package (Windows)

You can login with the "admin" user and any password.

choco install powershelluniversal

Winget (Windows)

You can install PowerShell Universal using Winget. It will run the MSI and install as a service.

winget install ironmansoftware.powershelluniversal

You can also specify the --silent flag to prevent the installer from showing and the web browser from opening at the end of the install.

winget install ironmansoftware.powershelluniversal --silent

ZIP Install

Windows

You can start Universal by unzipping the contents, unblocking the files and then executing Universal.Server.exe.

Expand-Archive -Path .\Universal.zip -DestinationPath .\Universal
Get-ChildItem .\Universal -Recurse | Unblock-File
Start-Process .\Universal\Universal.Server.exe

Linux

On Linux, start the process Universal.Server. You may need to chmod +x the file if it does not start.

Docker

MSI Install (Windows)

The MSI install will create a PowerShell Universal service and open the admin console after installation.

Properties

SUPPRESSBROWSER

Setting the SUPPRESBROWSER MSI property to true will prevent the browser from opening after installation.

Next Steps

At this point, Universal is up and running. Please consult other sections in this documentation for instructions on how to configure, secure, and start using PowerShell Universal. Happy Scripting!

This example uses .

This example uses .

This example uses .

This account users PowerShell Universal and .

Have an example of an API, Dashboard or Script that you think would fit nicely on this page? Feel free to open a pull-request on our .

This example uses .

You can install PowerShell Universal using the . The package runs the MSI install. It will install Universal as a service and open a web browser after the install.

You can also download the ZIP from our if you would like to xcopy deploy the files on Windows or Linux.

See the .

PowerShell Universal Dashboard
Universal Automation
Universal Automation
Dashboard
Automation
Active Directory
Azure
Hyper-V
Monitoring
Network
SQL
documentation repository
PowerShell Universal Dashboard
Chocolatey package
Downloads page
Reset Password
List Locked Accounts
Restore Deleted User
Virtual Machine Creator
Windows Performance Counter Dashboard

About

Universal provides the ability to define REST API endpoints using PowerShell. When the endpoints are executed by a compatible HTTP client, the PowerShell script will execute and return the result to the end user.

This feature is for developing custom APIs run by Universal. It not required for managing Universal. Universal provides a set of management APIs that are included with the platform.

Execution Environment

The REST API execution environment runs in your default PowerShell version. Unlike Automation jobs, which can also be run via the Universal management API, APIs that you define are run in a single PowerShell process. Because the PowerShell process is not started and stopped for each call to the endpoint, the API is much faster.

Set-PSUSetting -ApiEnvironment '7.1'

Performance

Performance is relative to the hardware and network conditions that you are running Universal on. That said, in ideal conditions you can expect the Universal APIs to service about 500 requests per second. This is with an entirely empty endpoint so any script that you add to that endpoint will reduce the throughput. The reduction of throughput will depend on the cmdlets and script executed within the API endpoint.

Variables

There are a set of predefined variables that are available in API endpoints. You'll be able to use these variables in your scripts.

Variable

Description

Type

$Url

URL the client used to call the endpoint

String

$Headers

Headers provided by the client to call the endpoint

Hashtable

$Body

The UTF8 encoded string of the content of the request

String

$Data

Binary byte array for the content of the request

Byte[]

$RemoteIpAddress

The remote IP address used to make the request.

String

$LocalIpAddress

The local IP address used to service the request.

String

$RemotePort

The remote port that was called to make the request.

Integer

$LocalPort

The local port that was used to service the request.

Integer

$Identity

The identity name of the principal accessing the API.

String

Related Cmdlets

PowerShell Protect

Examples integrating with PowerShell Protect.

Display Log Messages in PowerShell Universal

This example configures PowerShell Protect to send log messages to a PowerShell Universal instance. It sends HTTP POST requests to the configured server.

PowerShell Protect Configuration

This configuration checks to see if the user has included the string \\corp\human-resources anywhere in their script. If they do, it sends an HTTP POST to the URL http://localhost:8080/protect

The body of the HTTP request will contain the computer name and user name separated by a comma.

PowerShell Universal Configuration

This PSU configuration defines an endpoint to accept the POST data from PowerShell Protect. It then saves the data to a file. It also defines a dashboard that will read the data and display it in a table. This assumes that you have installed the PowerShell Universal module and server.

You can define the that runs the PowerShell Universal API process by specifying the -ApiEnvironment on Set-PSUSetting. Changing this setting will cause the API process to restart.

Here is an example of the output for the dashboard.

environment
New-PSUEndpoint
Get-PSUEndpoint
Remove-PSUEndpoint
New-PSUApiResponse
Set-UASetting
$Condition = New-PSPCondition -Property "script" -Contains -Value "\\corp\human-resources"
$Block = New-PSPAction -Http -Address "http://localhost:8080/protect" -Format "{computerName},{userName}" -Name 'Universal'
$Rule = New-PSPRule -Action $Block -Condition $Condition -Name "HR Share"
$Config = New-PSPConfiguration -Rule $Rule -Action $Block -License "<License></License>"

Set-PSPConfiguration -Configuration $Config -FileSystem
Start-PSUServer -Port 8080 -Configuration {    
    New-PSUEndpoint -Url "/protect" -Method POST -Endpoint {
       $Data = "$Env:Temp\data.csv"        
       if (-not (Test-Path $Data))        
       {            
          "computer,user" | Out-File $Data        
       }        
       $Body | Out-File $Data    
    }​    
    New-PSUDashboard -Name "Protect" -Content {        
       New-UDDashboard -Title 'Protect' -Content {            
          $Data = Import-Csv -Path "$Env:Temp\data.csv"            
          New-UDTable -Data $Data        
       }    
    }
 }

Endpoints

Endpoint configuration for Universal APIs.

Endpoints are defined by their URI and HTTP method. Calls made to the Universal server that match the API endpoint and method that you define will execute the API endpoint script.

New-PSUEndpoint -Url '/endpoint' -Method 'GET' -Endpoint {
   "Hello, world!"
}

To invoke the above method, you could use Invoke-RestMethod.

Invoke-RestMethod http://localhost:5000/endpoint

Variable URL

URLs can contain variable segments. You can denote a variable segment using a colon (:). For example, the following URL would provide a variable for the ID of the user. The $Id variable will be defined within the endpoint when it is executed. Variables must be unique in the same endpoint URL.

New-PSUEndpoint -Url '/user/:id' -Method 'GET' -Endpoint {
   Get-User -Id $Id
}

To call this API and specify the ID, you would do the following.

Invoke-RestMethod http://localhost:5000/user/123

Query String Parameters

Query string parameters are automatically passed into endpoints as variables that you can then access. For example, if you had an endpoint that expected an $Id variable, it could be provided via the query string.

New-PSUEndpoint -Url '/user' -Method 'GET' -Endpoint {
   Get-User -Id $Id
}

The resulting Invoke-RestMethod call must then include the query string parameter.

Invoke-RestMethod http://localhost:5000/user?Id=123

Body

To access a request body, you will simply access the $Body variable. Universal $Body variable will be a string. If you expect JSON, you should use ConvertFrom-Json.

New-PSUEndpoint -Url '/user' -Method Post -Endpoint {
    $User = ConvertFrom-Json $Body 
    New-User $User
}

To call the above endpoint, you would have to specify the body of Invoke-RestMethod.

Invoke-RestMethod http://localhost:5000/user -Method Post -Body "{'username': 'adam'}"

Form Data

You can pass data to an endpoint as form data. Form data will be passed into your endpoint as parameters.

New-PSUEndpoint -Url '/user' -Method Post -Endpoint {
    param([Parameter(Mandatory)]$userName, $FirstName, $LastName)
     
    New-User $UserName -FirstName $FirstName -LastName $LastName
}

You can then use a hashtable with Invoke-RestMethod to pass form data.

Invoke-RestMethod http://localhost:5000/user -Method Post -Body @{ 
    UserName = "adriscoll"
    FirstName = "Adam"
    LastName = "Driscoll"
}

Param Block

You can use a param block within your script to enforce mandatory parameters and provide default values for optional parameters such as query string parameters. Variables such as $Body, $Headers and $User are provided automatically.

In the below example, the $Name parameter is mandatory and the $Role parameter has a default value of Default.

New-PSUEndpoint -Url '/user/:name' -Endpoint {
    param([Parameter(Mandatory)$Name, $Role = "Default")
}

Returning Data

Data returned from endpoints will be assumed to be JSON data. If you return an object from the endpoint script block, it will be automatically serialized to JSON. If you want to return another type of data, you can return a string formatted however you chose.

Processing Files

Uploading Files

You can process uploaded files by using the $Data parameter to access the byte array of data uploaded to the endpoint.

New-PSUEndpoint -Url '/file' -Method Post -Endpoint {
    $Data
}

PS C:\Users\adamr> iwr http://localhost:5000/file -method post -InFile '.\Desktop\add-dashboard.png'

StatusCode        : 200
StatusDescription : OK
Content           : [137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,2,17,0,0,1,92,8,2,0,0,0,249,210,123,106,0,0,0,1,
                    115,82,71,66,0,174,206,28,233,0,0,0,4,103,65,77,65,0,0,177,143,11,252,97,5,0,0,0,9,112,72,89,115,0,
                    0,…

You could also save the file into a directory.

New-PSUEndpoint -Url '/file' -Method Post -Endpoint {
    [IO.File]::WriteAllBytes("tempfile.dat", $Data)
}

Downloading Files

You can send files down using the New-PSUApiResponse cmdlet.

New-PSUEndpoint -Url '/image' -Endpoint {
    $ImageData = [IO.File]::ReadAllBytes("image.jpeg")
    New-PSUApiResponse -ContentType 'image/jpg' -Data $ImageData
}

Returning Custom Responses

You can return custom responses from endpoints by using the New-PSUApiResponse cmdlet in your endpoint. This cmdlet allows you to set the status code, content type and even specify the byte[] data for the content to be returned.

New-PSUEndpoint -Url '/file' -Method Get -Endpoint {
    New-PSUApiResponse -StatusCode 410
}

You can also return custom body data by using the -Body parameter of New-PSUApiResponse.

New-PSUEndpoint -Url '/file' -Method Get -Endpoint {
    New-PSUApiResponse -Body "Not what you're looking for." -StatusCode 404
}

Invoking the REST method will return the custom error code.

PS C:\Users\adamr\Desktop> invoke-restmethod http://localhost:8080/file

Invoke-RestMethod: Not what you're looking for.

You can control the content type of the data that is returned by using the -ContentType parameter.

New-PSUEndpoint -Url '/file' -Method Get -Endpoint {
    New-PSUApiResponse -Body "<xml><node>1</node><node2>2</node2></xml>" -ContentType 'text/xml'
}

Persistent Runspaces

Persistent runspaces allow you to maintain runspace state between API calls. This is important for users that perform some sort of initialization within their endpoints that they do not want to execute on subsequent API calls.

By default, runspaces will be reset after each execution. This will cause variables, modules and functions defined during the execution of the API to be removed.

New-PSUEnvironment -Name 'Env' -Path 'powershell.exe' -PersistentRunspace

You can then assign the API environment in the settings.ps1 script.

Set-PSUSetting -ApiEnvironment 'Env'

Related Cmdlets

To enable persistent runspaces, you will need to configure an for your API. Set the -PersistentRunspace parameter to enable this feature. This is configured in the environments.ps1 script.

environment
New-PSUEndpoint
Get-PSUEndpoint
Remove-PSUEndpoint
New-PSUApiResponse
Set-UASetting

SQL

SQL examples for PowerShell Universal.

Server-side SQL Table

This example uses Universal Dashboard.

This example takes advantage of a SQL server and the New-UDTable cmdlet to create a table that retrieves data from a database table. The filtering, sorting and paging take place within the database.

This example assumes that we have a database called podcasts running in the local MS SQL Server. It has a table called shows that includes a column called host and a column called name.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUDashboard -Name 'SQL' -BaseUrl "/" -Framework 'UniversalDashboard:Latest' -Content {
        New-UDDashboard -Title 'SQL' -Content {
            New-UDTable -Title 'Shows' -LoadData {
                $TableData = ConvertFrom-Json $Body

                $OrderBy = $TableData.orderBy.field
                if ($OrderBy -eq $null)
                {
                    $OrderBy = "name"
                }

                $OrderDirection = $TableData.OrderDirection
                if ($OrderDirection -eq $null)
                {
                    $OrderDirection = 'asc'
                }

                $Where = ""
                if ($TableData.Filters) 
                {
                    $Where = "WHERE "

                    foreach($filter in $TableData.Filters)
                    {
                        $Where += $filter.column.field + " LIKE '%" + $filter.value + "%' AND "
                    }

                    $Where += " 1 = 1"
                }

                $PageSize = $TableData.PageSize 
                # Calculate the number of rows to skip
                $Offset = $TableData.Page * $PageSize
                $Count = Invoke-DbaQuery -SqlInstance localhost\MSSQLSERVER -Database 'podcasts' -Query "SELECT COUNT(*) as count FROM shows $Where"

                $Data = Invoke-DbaQuery -SqlInstance localhost\MSSQLSERVER -Database 'podcasts' -Query "SELECT * FROM shows $Where ORDER BY $orderBy $orderdirection OFFSET $Offset ROWS FETCH NEXT $PageSize ROWS ONLY" | ForEach-Object {
                    @{ 
                        name = $_.name 
                        host = $_.host
                    }
                } 
                $Data | Out-UDTableData -Page $TableData.page -TotalCount $Count.Count -Properties $TableData.properties
            } -Columns @(
                New-UDTableColumn -Property 'name' -Sort $true -Filter $true
                New-UDTableColumn -Property 'host' -Sort $true -Filter $true
            ) -Sort -Filter
        }
    }
}
Docker page

Docker

This page provides installation and configuration information for Docker.

Installation

docker pull ironmansoftware/universal
docker run --name 'PSU' -it -p 5000:5000 ironmansoftware/universal

Tags

Tag

Platform

1.3.0

linux/amd64

1.3.0-windowsservercore-1909

windows/amd64

Persistent Data

To create a Docker image that can persist the Universal data, you can create a dockerfile like the one below.

This dockerfile exposes port 5000, creates a /data volume, sets configuration environment variables to store the Universal repository and database in the volume and then sets the Universal.Server as the entry point to the container.

Linux

FROM ironmansoftware/universal:latest
LABEL description="Universal - The ultimate platform for building web-based IT Tools" 

EXPOSE 5000
VOLUME ["/data"]
ENV Data__RepositoryPath ./data/Repository
ENV Data__ConnectionString ./data/database.db
ENV UniversalDashboard__AssetsFolder ./data/UniversalDashboard 
ENV Logging__Path ./data/logs/log.txt
ENTRYPOINT ["./home/Universal/Universal.Server"]

Windows

FROM ironmansoftware/universal:1.3.1-windowsservercore-1809
LABEL description="Universal - The ultimate platform for building web-based IT Tools" 

EXPOSE 5000
VOLUME ["C:/data"]
ENV Data__RepositoryPath C:/data/Repository
ENV Data__ConnectionString C:/data/database.db
ENV UniversalDashboard__AssetsFolder C:/data/UniversalDashboard 
ENV Logging__Path C:/data/logs/log.txt
ENTRYPOINT ["C:/ProgramData/Universal/Universal.Server.exe"]

You can run a build with the build command.

docker build . --tag=universal-persistent

You can start the docker container with the run command and make sure to specify the volume to mount.

docker run --name powershelluniversal --mount source=psudata,target=/data --rm -d  -p 5000:5000/tcp universal-persistent:latest

Our docker image is available on . You can start it by pulling and then running with the default port bound.

Docker Hub
Send a Message to Slack
Send a Message to Slack when a Script Fails

Slack

Examples of integrating Slack with PowerShell Universal.

Send Message to Slack

This example uses a custom Slack webhook to send a message from a Universal API.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUEndpoint -Url "/slack" -Method POST -Endpoint {

        $Body = @{
            text = "Hello"
        } | ConvertTo-Json

        Invoke-RestMethod -Uri 'https://hooks.slack.com/services/0000000000/00000000/00000000000000000' -Body $Body -Method POST
    }
}

You can invoke this API by calling Invoke-RestMethod

Invoke-RestMethod http://localhost:8080/slack -Method POST

The following message will show up in Slack.

Send Slack Message on Failed Job

This example takes advantage of triggers to send a message to Slack when a job fails within PowerShell Universal. We define two scripts. The first script simply throws and error and is set to fail by using the -ErrorAction Stop setting. The second script receives the job that failed and sends a message to the team's Slack channel.

Start-PSUServer -Port 8080 -Configuration {

    Set-PSULicense -Key 'license'

    New-PSUScript -Name 'ScriptFailed' -ScriptBlock {
        $Body = @{
            text = "Job $($Job.Id) failed!!"
        } | ConvertTo-Json

        Invoke-RestMethod -Uri 'https://hooks.slack.com/services/00000000/00000000/000000000000000' -Body $Body -Method POST
    }

    New-PSUScript -Name 'FailingScript' -ScriptBlock {
        throw "NoooooO!"
    } -ErrorAction Stop

    New-PSUTrigger -Name 'ScriptFailed' -TriggerScript 'ScriptFailed.ps1' -EventType 'JobFailed'
}

When the failing script is running, it will report failure in the UI.

Due to the failure, the trigger will execute and send a message to Slack.

This example uses .

This following example uses . This example requires a .

Universal API
Universal Automation
license
Convert JPEG to PNG
Convert JPEG to PNG API
Rate Limited API

Image Processing

Image Processing examples

Convert JPEG to PNG

This examples accepts a JPEG file and converts to to a PNG using Universal Dashboard. To implement this example, we need to use published folders and a dashboard that uses UDForm and the UDUpload component. After converting the image, it displays it.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUPublishedFolder -Path 'C:\images' -RequestPath '/images'

    New-PSUDashboard -Name 'Convert' -BaseUrl '/' -Framework 'UniversalDashboard:Latest' -Content {
        New-UDDashboard -Title 'Convert' -Content {
            New-UDForm -Content {
                New-UDUpload -Id 'image' -Text 'Image to Convert'
            } -OnSubmit {
                $bytes = [System.Convert]::FromBase64String($EventData.image.Data)

                $Bitmap = [System.Drawing.Image]::FromStream([System.IO.MemoryStream]::new($bytes))
                $Bitmap.Save("C:\images\$($EventData.Image.Name)".Replace("jpeg", "png"), 'PNG')

                New-UDImage -Url "/images/$($EventData.Image.Name.Replace('jpeg', 'png'))"
            }
        }
    }

}

Convert JPEG to PNG API

This example is similar to the dashboard example but exposes the functionality as an API rather than a webpage. The API accepts a POST request that contains the image as a the body. We use the $Data variable which contains the byte array for the image file and then convert it use the same method. We then take advantage of the New-PSUApiResponse cmdlet to return a custom response.

Start-PSUServer -Port 8080 -Configuration {
    New-PSUEndpoint -Url "/image" -Method POST -Endpoint {
        $Bitmap = [System.Drawing.Image]::FromStream([System.IO.MemoryStream]::new($Data))
        $Bitmap.Save("$Env:Temp\image.png", 'PNG')

        New-PSUApiResponse -Data ([IO.File]::ReadAllBytes("$Env:Temp\image.png")) -ContentType 'application\png'

        Remove-Item "$Env:Temp\image.png"
    }
}

We can invoke the API with Invoke-WebRequest. The below example posts the IMG_2260.jpeg file and converts it to an image.png file.

Invoke-WebRequest -InFile .\IMG_2260.jpeg -Uri http://localhost:8080/image -Method POST -OutFile .\image.png

Rate Limited Conversion API

This example provides the same functionality as the previous example but rate limits the number of requests to 5 per 10 minutes. We can use New-PSURateLimit to set the request limit.

Start-PSUServer -Port 8080 -Configuration {
    Set-PSULicense -Key "key"

    New-PSURateLimit -Endpoint "POST:/image" -Period ([TimeSpan]::FromMinutes(10)) -Limit 5

    New-PSUEndpoint -Url "/image" -Method POST -Endpoint {
        $Bitmap = [System.Drawing.Image]::FromStream([System.IO.MemoryStream]::new($Data))
        $Bitmap.Save("$Env:Temp\image.png", 'PNG')

        New-PSUApiResponse -Data ([IO.File]::ReadAllBytes("$Env:Temp\image.png")) -ContentType 'application\png'

        Remove-Item "$Env:Temp\image.png"
    }
}

Invoking this request most than the specified number of times will result in an error.

PS C:\Users\adamr> invoke-webrequest -InFile .\IMG_2260.jpeg -Uri http://localhost:8080/image -Method POST -OutFile .\image.png
Invoke-WebRequest: API calls quota exceeded! maximum admitted 5 per .

This example uses .

This example uses .

This example uses . This example requires a .

PowerShell Universal Dashboard
PowerShell Universal API
PowerShell Universal API
license

Error Handling

Error handling for Universal API.

By default, endpoints will return a 200 OK message even if there are errors. If an error occurs, you will get a blank response from the endpoint. This document demonstrates different ways to handle errors within APIs.

Automatically Returning Errors

To automatically return errors from APIs, you can change the default behavior by setting the -ErrorAction parameter of New-PSUEndpoint to Stop. Any errors will cause an 500 Internal Server Error to be returned with a list of the errors and stack trace.

Terminating errors will always return a 500 Internal Server Error.

New-PSUEndpoint -Url "/error" -Endpoint { 
   throw "Uh oh!"
} -ErrorAction stop

New-PSUEndpoint -Url /error2 -Endpoint {
    Write-Error "Whoa!"
} -ErrorAction Stop

You will notice different behavior in Windows PowerShell and PowerShell 7 when calling REST APIs that return errors. In Windows PowerShell, you will receive a generic error that doesn't return the error message.

PS C:\Users\adamr> invoke-restmethod http://localhost:5000/error2
invoke-restmethod : The remote server returned an error: (500) Internal Server Error.
At line:1 char:1
+ invoke-restmethod http://localhost:5000/error2
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], Web
   Exception
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

In PowerShell 7, when an error is returned, you will see the error message returned.

PS C:\Users\adamr\Desktop> invoke-restmethod http://localhost:5000/error 

Invoke-RestMethod: Uh oh!
at , : line 2
at , : line 1

PS C:\Users\adamr\Desktop> invoke-restmethod http://localhost:5000/error2

Invoke-RestMethod: Whoa
at , : line 2
at , : line 1

You can retrieve the error message in Windows PowerShell, by using the following syntax.

PS C:\Users\adamr> try { invoke-restmethod http://localhost:5000/error2 } catch { [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream()).ReadToEnd()}
Whoa!
at <ScriptBlock>, <No file>: line 2
at <ScriptBlock>, <No file>: line 1

Manually Returning Errors

To manually return errors, you need to use the New-PSUApiResponse cmdlet. This cmdlet allows you to define the status code and body for the response.

In this example, we are returning a 404 error code from the endpoint.

New-PSUEndpoint -Url /broken -Endpoint {
    New-PSUApiResponse -StatusCode 404 -Body 'Failed!'
}

Similar to the automatic error codes, error codes returned manually will as display better in PowerShell 7. Here's an example of calling the endpoint.

PS C:\Users\adamr\Desktop> invoke-restmethod http://localhost:5000/broken

Invoke-RestMethod: Failed!

If called from Windows PowerShell, you will receive an error similar to the one returned automatically.

PS C:\Users\adamr> invoke-restmethod http://localhost:5000/broken
invoke-restmethod : The remote server returned an error: (404) Not Found.
At line:1 char:1
+ invoke-restmethod http://localhost:5000/broken
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], Web
   Exception
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

You can choose to return error codes if certain conditions are met by using your PowerShell script within the endpoint.

New-PSUEndpoint -Url /user/:name -Endpoint {
    if ($Name -eq 'User')
    {
        @{ UserName = "Adam" }
    }
    else
    {
        New-PSUApiResponse -StatusCode 404 -Body 'Unknown user!'    
    }

}

Related Cmdlets

New-PSUEndpoint
Get-PSUEndpoint
Remove-PSUEndpoint
New-PSUApiResponse
Set-UASetting

Development

Building APIs in VS Code.

Developing APIs

You can add APIs by using the admin console or through the editor in Visual Studio Code.

To add an API in the Admin Console, you can visit http://localhost:5000/admin/apis and click Add Endpoint.

Once an endpoints.ps1 file has been created, you can click the Open Endpoints.ps1 button within the API tree view to view the configuration file for APIs.

The configuration file uses the Universal PowerShell cmdlets to define the endpoints within Universal.

If you created a blank endpoint, it would look something like this.

New-PSUEndpoint -Url "/test" -Endpoint { 
    # Enter your script to process requests.
}

If you edit the endpoints.ps1 file, it will update the API automatically. For example, if I added a new API, it would then appear in the admin console.

New-PSUEndpoint -Url "/test" -Endpoint { 
 "hello"
}

New-PSUEndpoint -Url "/test2" -Endpoint { 
    # Enter your script to process requests.
}

The provides integration for working with APIs. We recommend you also install the .

Visual Studio Code extension for PowerShell Universal
PowerShell extension

Rate Limiting

Rate limiting options for Universal.

PowerShell Universal provides the ability to rate limit requests made to the web server. Rate limiting can be configured on a per endpoint and per period. By default, the client IP address is used to rate limit clients.

Configuration data for rate limits are stored in the ratelimits.ps1 file.

Configuring Rate Limiting

To configure rate limiting, you can visit the APIs / Rate Limiting page. Click the Add button and define a new rate limit rule.

Rate limiting affects all URLs for the server. If you enforce rate limiting that isn't correctly configured, you can negatively affect the management API.

Method

The Method is the HTTP method to for this rule. If you use * , all HTTP methods will be affected by this rule. You can also select a single method by picking it from the drop down.

Endpoint

The endpoint is the URL that you are rate limiting. You can rate limit all URLs by using a *. You can define specific URLs by define the relative path: /api/user.

Limit

The number of request in the time frame before rate limiting kicks in.

Period

The period over which the rate limit is counted. For example, if you select a period of 10 minutes and a limit of 100, then up to 100 requests can be made to the method and endpoint you have selected.

Allow Lists

To disable rate limiting for particular IP Addresses, clients and endpoints you can add them to the rate limiting allow lists. You will find these by clicking the settings button.

Related Cmdlets

Scripts

Scripts are the basic entity within Universal Automation. Scripts are just PowerShell scripts. They are stored on disk and also persisted to a local or remote Git repository.

Script properties are stored in the scripts.ps1 configuration file.

Add a New Script

To add a new script, you can click the New Script button within the Automation / Scripts page. There are various settings you can provide for the script.

Name

Name of the script as shown in Universal Automation. This will also be the name used to persist the script to disk. This setting needs to be unique within the current folder.

Description

A description of the script. This is shown in various places within the UA UI and also returned by the Universal cmdlets.

Disable Manual Invocation

Prevents a script from being run manually. This is enforced in the UI as well as the web server and cmdlets.

Manual Time

This setting is used to track the amount of time saved.

Max Job History

Defaults to 100. It defines the amount of jobs that are stored when running this script. Jobs are also cleaned up based on the server-wide job retention duration setting from within the Settings / General page.

Error Action

Changes how the script reacts when there is an error within the script. By default, terminating and non-terminating errors are ignored and the script will always be successful. You can change this setting to stop to cause scripts to fail immediately when an error is encountered.

PowerShell Version

Allows you to define the required PowerShell version for the script. By default, it uses the server-wide default PowerShell version. PowerShell versions are automatically located the first the Universal Server starts up. You can also add PowerShell Versions on the Settings / General page.

Timeout

The number of minutes before the script will timeout. The default value of 0 means the script will run forever. Once a script reaches it's time out, it will be cancelled.

Concurrent Jobs

Defines the maximum concurrent jobs the script can be run. Defaults to 100.

New-PSUScript -Name Script.ps1 -Path Script.Ps1 -ConcurrentJobs 1

Running a Script

You can run a script in the UI by click the Run button the Automation / Scripts page or by clicking View and then Run. In each case, you will be presented with the Run Dialog that allows you to select various settings for the job.

Running a Script With Parameters

Universal Automation automatically determines the parameters as defined within your scripts. It takes advantage of static code analysis to determine the type, default values and some validation that is then presented within the UI.

For example, you may have a script with the following parameters.

param(
    $Test,
    [DateTime]$Time, 
    [int]$Number,
    [PSCredential]$Credential,
    [System.ConsoleColor]$Color
)

The result is a set of input options that are based on the types of parameters.

Running a Script as Another User

To run as another user, simply add or import a PSCredential variable. From there, you can select the credential from within the run dialog.

Remoting

Note that you can use PowerShell remoting by taking advantage of Invoke-Command . We do not support the use of Enter-PSSession or Import-PSSession.

Related Cmdlets

Security

Authentication and authorization for REST APIs.

REST API authentication requires a Universal API license. Once enabled, you will be able to enforce authentication and authorization on your endpoints.

Defining Secure Endpoints

You can define secure endpoints in the UI by enabling authentication.

You can also define secure endpoints using the .universal/endpoints.ps1 file or the Management API using New-PSUEndpoint.

When authentication is enabled, it will enforce the use of one of the configured authentication methods. APIs support the following methods.

  • JWT App Tokens

  • Windows Authentication

  • Cookie Authentication

Accessing Secure Endpoints

Once you have defined a secure endpoint, you will need to provide authentication and authorization to access the endpoint.

Authenticating with tokens

Note that if you are hosting in IIS and do not have Anonymous Authentication enabled, you will not be able to pass app tokens to the PowerShell Universal server.

To authenticate with tokens, first, you need generate a new app token for use. You can use the Grant-PSUAppToken cmdlet to do so remotely or you can create an app token in the UI using the Settings Security AppTokens tab.

Click Grant App Token to create a new one.

Once you have created your app token, you can now use it to authenticate against the secure endpoint. To do so, pass the Authorization header along with the request.

Authenticating with Windows Authentication

Authenticating with Cookies

To authenticate with cookies, you will first need to call the login API to receive a valid cookie from the system. You can use Invoke-WebRequest to do so. Pass the user name and password as the body. Specify the -SessionVariable parameter to establish a session.

Once you have successfully authenticated, you can use your $mySession variable to call secure endpoints.

Enforcing Roles

In addition to creating endpoints that require authentication, you can also enforce roles by define a role in the New-PSUEndpoint cmdlet or by selecting one in the UI. If a role is selected, it's possess the role.

Windows and Cookie authentication will assign roles based on the Identity of the user and the role policies as they are applied.

JWT app tokens will use the role that was defined when they were generated.

Related Cmdlets

This feature requires a .

You can run scripts as another user by configuring . PowerShell Universal uses the Microsoft Secret Management module to integrate with secret providers. See variables for more information on secrets.

This feature requires a .

To authenticate with , you can use the -UseDefaultCredentials parameter of Invoke-RestMethod and Invoke-WebRequest . This will perform negotiate authentication whether you are running inside IIS or a service.

license
New-PSURateLimit
Set-UASetting
New-PSUScript
Get-UAScript
Remove-UAScript
Set-UAScript
New-PSUEndpoint -Url '/endpoint' -Method 'GET' -Endpoint {
   "Hello, world!"
} -Authentication
Invoke-RestMethod http://localhost:5000/auth -Headers @{ Authorization = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiQWRtaW4iLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9oYXNoIjoiMWUyY2IzNzAtMmMyNS00ZDU5LTk4YzgtMzc5MTFjMDAyZmI5Iiwic3ViIjoiUG93ZXJTaGVsbFVuaXZlcnNhbCIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6IkFkbWluaXN0cmF0b3IiLCJuYmYiOjE2MDU2NjEyNTUsImV4cCI6MTYzNzM2NzI1OCwiaXNzIjoiSXJvbm1hblNvZnR3YXJlIiwiYXVkIjoiUG" }
Invoke-RestMethod http://localhost:5000/auth -UseDefaultCredentials
Invoke-WebRequest http://localhost:5000/api/v1/signin -Body (@{ 
    UserName = "Admin"
    Password = "Any"
} | ConvertTo-Json) -ContentType 'application/json' -SessionVariable mySession -Method POST
 Invoke-WebRequest http://localhost:5000/auth -WebSession $mySession

About

Universal Automation is a lightweight and easy to use automation platform built for PowerShell.

Features

  • Simple Background Jobs - Universal Automation provides the ability to run simple background jobs in Windows PowerShell and PowerShell 7. Jobs can be scheduled to run with simple CRON expressions.

  • Runs anywhere - Built on .NET to support multi-platform, docker, raspberry pi, and just about anything!

  • Persistence - Universal Automation job status is automatically backed by database persistence to allow for easy reporting of job results and data.

  • PowerShell First - Build from the ground up for Administrators/Developers/DevOps professionals familiar with PowerShell. UA integrates with Write-Progress, the pipeline, and user input, like Read-Host, to allow users to interact with scripts via the UA dashboard.

license
New-PSUEndpoint
Get-PSUEndpoint
Remove-PSUEndpoint
New-PSUApiResponse
Set-UASetting

Schedules

Schedules can be assigned to scripts and allow you to define frequency and other parameters for a script such as run as credentials.

Schedules are stored in the schedules.ps1 configuration file.

Scheduling a Job

To schedule a job, you can do so from the Automation / Schedules page and by clicking the New Schedule button. You can also schedule a script by click the Schedule option from the script's page.

Schedules can be defined based on simple selections like Every Minute or Every Hour or you can define CRON expressions yourself for more configurable schedules. You can also run One Time schedules that run once at a later date.

You can also define which user the scheduled job will run under as well as which PowerShell version to use.

Simple Schedules

Simple schedules are really just helpers for various standard CRON schedules. When you select one, it will define a CRON schedule for your.

CRON

One Time

One time schedules will run once in the future. You can select the time and day of when they will run.

Continuous

Continuous schedules will run over and over again. You can define a delay between each scheduled job run.

Parameters

Schedules support setting parameters for scripts. For example, if you have a script that accepts a parameter, you can choose to pass a value to the parameter during the schedule.

param($UserName)

$UserName

Within the modal for defining the schedule, you will have the option to set the parameter value.

When editing schedules from PowerShell, you can define the parameters on the New-PSUSchedule cmdlet. This cmdlet accepts dynamic parameters so that you can pass the values in for your schedule.

New-PSUSchedule -Script "MyScript.ps1" -Cron '* * * * *' -UserName 'adam'

Environments

New-PSUSchedule -Script "MyScript.ps1" -Cron '* * * * *' -Environment '7.1'

Run As

You can define a Run As user in a script by using the -Credential parameter. The value should be the name of the variable that contains your credential.

New-PSUSchedule -Script "MyScript.ps1" -Cron '* * * * *' -Credential 'MyUser'

Variables

Variables allow for the global definition of variables that are available within scripts. You can also import secrets that are also available within scripts or as run as credentials.

Variables are stored in the variables.ps1 configuration file.

Creating a Variable

To create a variable, navigate to the Automation / Variables page. Click Add Variable to define a new variable.

Standard variables are just name \ value pairs of strings. They will be added to your scripts before they are run.

Creating a Secret Variable

Secret management is currently only supported on Windows.

Secret variables are stored within the selected vault. The value of those variables are never stored within Universal. To define a new secret variable, click Add Variable on the variables page and select the Secret tab.

Values for secrets are stored within the current user's Windows Credential Manager instance. If you change users (such as running as a service account), the account will not have access to the previous user's secrets and you will need to add those secrets again.

From this dialog, you'll be able to define string and PSCredentials in the specified vault.

Importing Secret Variables

You can also import pre-existing secrets as variables into Universal. The variable values are not imported but will be looked up during execution. Click the Import Secret button to import secrets.

Related Cmdlets

CRON schedules use CRON expressions to define schedules. You can use a tool like to help define the schedule.

When creating a schedule, you have the option to specify the for your job to run. By default, it will use the default environment. You can define an environment in the UI by using the Environment drop down. You can define an environment using the -Environment parameter in New-PSUSchedule.

You can define which user to run the schedule as by using the Run As selector in the UI. The Run As selector contains a list of PSCredential you have defined. You will need to define a PSCredential variable before the Run As selector is visible. By default, scheduled jobs will run under the credentials of the user that is running PowerShell Universal.

Crontab guru
environment
variables
secret variables
New-UAVariable
Get-UAVariable
Remove-UAVariable
Set-UAVariable

Triggers

Universal Automation triggers.

Triggers allow for automation jobs to be started when certain events happen within PowerShell Universal. For example, this allows you to take action when jobs complete, the server starts or dashboards stop. Triggers are useful for assigning global error handling or sending notifications when certain things happen.

Triggered jobs will not cause additional triggers to start. Triggers are stored in the triggers.ps1.

Trigger Events

The following types of events can be assigned a trigger.

  • Job Started

  • Job Completed

  • Job Requesting Feedback

  • Job Failed

  • Dashboard Started

  • Dashboard Stopped

  • Server Started

  • Server Stopping

Global Triggers

Global triggers will start the assigned script whenever the event type is invoked.

For example, the Script.ps1 will be run whenever any job is run.

New-PSUTrigger -Name 'Trigger' -EventType JobStarted -TriggerScript Script.ps1

Resource Triggers

Resource triggers will start the assigned script when the event takes place on the selected resource.

For example, the Script.ps1 will be run whenever the Dashboard is stopped.

New-PSUTrigger -Name 'Trigger' -EventType DashboardStopped -TriggerScript Script.ps1 -Dashboard 'Dashboard'

Event Metadata

Whenever a job is started from a trigger, it will be provided with metadata about object that caused the event to trigger.

Triggers related to jobs will be provided a $Job parameter.

param($Job)

$Job

Triggers related to dashboards will be provided a $Dashboard parameter.

param($Dashboard)

$Dashboard

Triggers related to the server status will not receive a parameter.

Related Cmdlets

'

This feature requires an .

Automation license
New-PSUTrigger
Remove-PSUTrigger
Set-PSUTrigger
Get-UAScript
Get-PSUDashboard

Migrating From Universal Dashboard 2.9

PowerShell Universal Dashboard v2.9 is a PowerShell module that allows you to create dashboard with PowerShell script. It is the predecessor to PowerShell Universal. The technology the enabled UD has been migrated into PowerShell Universal. You should be able to run the same PowerShell scripts in PowerShell Universal that you would in Universal Dashboard with some minor modifications.

Migrating from Universal dashboard to PowerShell Universal

No need to call Start-UDDashboard

In Universal, all you need to do is return the result of New-UDDashboard from your script. There is no need to call Start-UDDashboard. The configuration of the webserver is taken place using the PSU appsetting.json file.

New-UDDashboard -Title 'My dashboard' -Content {

}

No need to call New-UDEndpointInitialization

This cmdlet has been removed from Universal Dashboard. There is no longer a need to call it.

Scheduled Endpoints

You do not need to pass the value of a scheduled endpoint to anything. You can just call New-UDEndpoint with a endpoint schedule and it will automatically be registered with PSU.

$Schedule = New-UDEndpointSchedule -Every 10 -Minute
$Endpoint = New-UDEndpoint -Schedule $Schedule -Endpoint {}

REST APIs

Authentication and Authorization

Authentication and authorization are now handled by PSU and there is no need to configure UD login pages. Authentication and authorization are configured with the PSU appsettings.json file. Dashboard's themselves can be either authenticated or not authenticated. A license is required to enable authenticated dashboards.

To enable role-based access controls, you can assign roles to pages and use the automatic $Roles variable to check which roles the user is a part of. The $User variable will provide the name of the user.

Authorization Policies

Authorizations policies in Universal work very similar to the ones in Universal Dashboard, you will define them using the New-PSURole cmdlet. When you define the role, you have the option to define a policy that will assign that role automatically to a user.

For example, let's adjust a claims policy from Universal Dashboard for Universal.

Universal Dashboard

$AuthorizationPolicy = New-UDAuthorizationPolicy -Name "Policy" -Endpoint {
    param($User)

    $User.HasClaim("group", "administrator")
}

Universal

New-PSURole -Name 'User' -Policy {
   param($User)

   $User.Claims | Where-Object { $_.Type -eq 'group' -and $_.Value -eq 'administrator' }
}

Enforcing Roles

Much like the Get-UDAuthorizationPolicy cmdlet in Universal Dashboard, you also have access to the assigned roles for users in Universal. Simply check the $Roles variable to see which roles the user has.

PS C:\Users\adamr> $Roles = @('Administrator')
PS C:\Users\adamr> if ($Roles -contains 'Administrator') { $true }

Published Folders

Migrating to Universal Dashboard v3

This section contains migration information for upgrading from UDv2 to UDv3. They are vastly different frameworks and will require rewriting your dashboard. Many of the concepts are the same.

Pages

Pages have a different behavior in v3. All pages are dynamic pages. This means that you don't have to worry about whether a page will be generated at run time or doing start up. Pages are always generated during runtime.

If you have a page such as this one:

New-UDPage -Url "/myPage/:owner" -Endpoint {
    param($owner)
}

You can convert it to a v3 page by changing the syntax to:

New-UDPage -Name 'myPage' -Url "/myPage/:owner" -Content {
    param($owner)
}

New-UDTable (formerly UDGrid and UDTable)

Rather than having two cmdlets for tables (New-UDTable and New-UDGrid). The New-UDTable in v3 provides the ability to display data in a table, filter, page, and sort it. It supports both client and server-side processing.

New-UDDynamic

Unlike in v3, components do not have -Endpoint and -Content parameters. Each component will instead simply have a -Content parameter. To achieve dynamic sections of a page, you can instead use the New-UDDynamic cmdlet. This cmdlets let you define an entire section of a page as dynamic. It also provides auto refresh functionality so you can refresh sections of a page all at once.

New-UDDynamic -Content {
    New-UDTypography -Text (Get-Date)
}

New-UDGrid

New-UDGrid allows you to define a grid layout using the Material UI library. You use this single cmdlet to define rows and columns within your dashboard.

New-UDForm (formerly UDInput)

New-UDInput has been replaced by New-UDForm. The UDForm component allows far more configuration that UDInput did. You will use the standard controls like UDTextbox, UDCheckbox, and UDSelect instead of New-UDInputField. This means that there are a single set of input cmdlets to use for UD.

Navigation

Instead of using New-UDSideNav, you will now use a combination of New-UDAppbar and New-UDDrawer. When New-UDAppBar is used with the default position, it will overlay the AppBar at the top of the page. You can then specify a drawer to customize the navigation experience within your dashboard.

Nivo and Sparklines are now open source

The Nivo and sparklines controls are now open source and on the Universal Dashboard repository. You can now use them without purchasing a license.

Map is now open source

The map control is also open source and on GitHub.

To learn more about APIs, .

to learn more about Published Folders in PowerShell Universal.

You can view examples of the .

You can view examples of the .

All of the input control examples can be .

You can see examples of how to do .

For more examples of Nivo and sparklines controls, .

You can find examples .

click here
Click here
table on GitHub
grid on GitHub
found on GitHub
navigation on GitHub
see GitHub
on GitHub

Building Dashboards

When building dashboards, you will pick one of the two built in dashboard frameworks. The components that are available for that framework will different. You can find examples of each of the frameworks at the below links.

All the documentation on this page will be referencing the v3 framework.

Dashboards can contain one or more pages. The simplest dashboard will contain a single page with some content. You can call any PowerShell cmdlet that is available on your machine to populate your dashboard.

Here's an example of simple dashboard that displays some text.

New-UDDashboard -Title 'My New Dashboard' -Content {
    New-UDTypography -Text 'Hello!'
}

Components

Components are the individual widgets that you can place on you dashboard. There are components for displaying data, taking user input, adding text and images and more. Components can be downloaded as PowerShell modules and added to your dashboard.

Components are be caused using the standard verb-name syntax for any PowerShell cmdlet.

New-UDPage -Content {
    New-UDTextbox
}

Pages

You can specify multiple pages within a dashboard. Each page defines a route. As for v3, all pages are dynamic. PowerShell will execute on each page load to render the new page. Since UD is a single page application, the web browser does not need to refresh the entire web page when navigating between the different dashboard pages.

$Pages = @()
$Pages += New-UDPage -Name 'My Home Page' -Content {}
$Pages += New-UDPage -Name 'Diagnostics' -Content {}
New-UDDashboard -Pages $Pages -Title 'Dashboard'

Built-in Variables

There are several built-in variables that are available in dashboards.

Name

Description

Type

$User

The user name of the logged in user. $Null if authentication is disabled.

String

$Roles

The roles that the user has been granted. $Null if authentication is disabled.

String[]

$RemoteIpAddress

The remote IP address of the connected user. Only available in the nightly build

String

$RmotePort

The remote port of the connected user. Only available in the nightly build

Int

Debugging

When building a dashboard you will likely run into issues with cmdlet calls or syntax. Dashboards will auto reload as you make changes to the dashboard files. If a dashboard fails to start, you can navigate to the admin page, click Dashboards and click the Info button next to your dashboard.

The Log tab will show all the logging coming from the PowerShell execution from within in your dashboard. This should allow you to easily see errors and warnings coming from your dashboard.

You can use Write-Debug to add additional log messages to your dashboard. To enable debug logging, you will have to set the $DebugPreference variable at the top of your dashboard script.

$DebugPreference = 'Continue'

Development

Developing dashboards in VS Code.

Developing a Dashboard with VS Code

To add a new dashboard, visit the admin console and go to Dashboard Dashboards and click the Add Dashboard button.

After adding the dashboard, a dashboard PS1 file will be created and the dashboards.ps1 file will be updated. You can view your dashboard in VS Code underneath the dashboards tree view. It will show the current state of the dashboard and the framework it is using.

If you want to edit your dashboard, click the Open Dashboard File button. This will open the dashboard PS1 file in the editor and import the Universal module and Dashboard framework module so you have IntelliSense.

From here, you can begin editing your dashboard.

Your dashboard should restart automatically when you make changes. You will be able to view the dashboard in the browser by clicking the View button.

If you need to restart your dashboard manually, you can click the Restart button.

Developing a Dashboard with Single-File Configuration

You can use the Universal Dashboard PowerShell module and single-file configuration to build a dashboard directly from PowerShell.

Install the Universal Dashboard PowerShell Module. This will install both the Universal Dashboard framework module and the PowerShell Universal module.

Install the latest version of the Universal server.

Create a PS1 file for your configuration data and start the server.

Navigate to your dashboard.

Changes you make to your PS1 file will cause Universal to automatically reload your dashboard and reflect the changes.

Debugging a Dashboard

Logs

You can view the dashboard logs by right clicking on the Dashboard and clicking View Log. The log should provide information about start up issues or errors when executing sections of your dashboard.

Debugger

This section requires the PowerShell extension.

You can debug individual endpoints within your dashboard by using Wait-Debugger

For example, if I wanted to debug the button on my dashboard, I would add it to the OnClick event handler.

Now, I can right click on my dashboard and click Debug Dashboard Process.

This will issue an Enter-PSHostProcess command in the Integrated Terminal.

Next, you'll want to navigate to your page and click the button. Once the button is clicked, issue a Get-Runspace command in the Integrated Terminal. You'll notice that one of the runspaces is in InBreakpoint availability.

Finally, issue the Debug-Runspace command and VS Code will automatically open your endpoint in the debugger. You'll be able to step through your code, view variables and issue commands against the runspace.

Debug-PSUDashboard

Debug-PSUDashboard can be used instead of Wait-Debugger to more easily debug aspects of your dashboard. Debug-PSUDashboard requires the PowerShell Universal VS Code extension. When placed within a dashboard, this cmdlet will trigger a modal to be show with some information about connecting to the runspace that is currently running the code you are trying to debug.

You can enter the commands listed in any PowerShell host to connect to the runspace that is currently running in the dashboard.

If you have VS Code and the PowerShell Universal extension installed, you can use the Debug with VS Code button to automatically launch VS Code and connect to the runspace. You can see how that works by watching this video.

We recommend installing the . Read more about dashboard development .

Examples of all of the components can be found .

The provides integration for working with dashboards. We recommend you also install the .

PowerShell Universal Visual Studio Code extension
here
Universal Dashboard v2
Universal Dashboard v3
on GitHub
Install-Module UniversalDashboard
Install-PSUServer -LatestVersion
Start-PSUServer -Port 8080 -Configuration {
    New-PSUDashboard -Name 'Dashboard' -BaseUrl '/dashboard' -Framework 'UniversalDashboard:Latest' -Content {
        New-UDDashboard -Title 'Hello, World' -Content {
            New-UDForm -Content {
                New-UDTextbox -Label 'Say Hi' -Id 'textbox'
            } -OnSubmit {
                Show-UDToast -Message $EventData.textbox
            }
        }
    }
}
Start-Process http://localhost:8080/dashboard
New-UDDashboard -Title "Hello, World!" -Content {
    New-UDTypography -Text "Hello, World!"

    New-UDButton -Text "Learn more about Universal Dashboard" -OnClick {
        Wait-Debugger
        Invoke-UDRedirect https://docs.ironmansoftware.com
    }
}
PS C:\Users\adamr\Desktop> Enter-PSHostProcess -Id 15464

[Process:15464]: PS C:\Users\adamr\Documents>
[Process:15464]: PS C:\Users\adamr\Documents> Get-Runspace


 Id Name            ComputerName    Type          State         Availability
 -- ----            ------------    ----          -----         ------------
  1 Runspace1       localhost       Local         Opened        Busy        
  2 Runspace2       localhost       Local         Opened        Available   
  3 RemoteHost      localhost       Local         Opened        Available   
  4 e8be011f-40f8-… localhost       Local         Opened        InBreakpoint
Visual Studio Code extension for PowerShell Universal
PowerShell extension

Development

Developing scripts in VS Code

Developing Scripts

To add scripts to the Universal platform, you can do it via the admin console or the file system. The Visual Studio Code extension also provides integration for managing the scripts.ps1 configuration file.

The Scripts tree view will provide access to each of your scripts, the admin console the scripts.ps1 file.

To add a new script to the Universal platform, you can create the PS1 file on the file system and then add the script to the scripts.ps1. The file name is relative to the repository folder. You can also use fully qualified file paths.

New-PSUScript -Name "Script1.ps1" -Path "Script1.ps1" -InformationAction "Continue"

To edit a script in VS Code, click the Edit Script button.

The script will open in the VS Code editor.

Running Scripts

You can start scripts by clicking the Run Script button. This will start a Universal Automation job. You'll get notifications of the job's progress in VS Code.

Developing Schedules

You can edit schedules for scripts by editing the schedules.ps1 file. A link to the file is available in the configuration tree view.

Schedules are defined using New-PSUSchedule cmdlet.

New-PSUSchedule -Cron "0 */4 * * *" -Script "Script1.ps1" -TimeZone "America/Denver"

Dashboards

Dashboards are individual websites created with Universal Dashboard. You can define settings for a dashboard and start and stop the dashboard from within the Universal administrative interface.

Adding a Dashboard

Dashboards can be added to Universal using the Add Dashboard button from the Dashboard / Dashboards page.

Name

Name is displayed throughout the UI and returned from the Universal cmdlets.

Base URL

The base URL is the URL that you will access to view this dashboard. This URL needs to be unique within this instance. You can specify the / root URL if you wish. You will have to visit /admin to login to the administrative page if you set the dashboard to the root URL.

File Name

The full file name to the dashboard file. This file needs to return a dashboard using New-UDDashboard.

Framework

The framework that the dashboard was designed for. By default, Universal Dashboard v2.9 and v3.0 are supported.

Environment

Auth

Enables authentication for the dashboard.

Role

Defines the role that is required to access the dashboard.

AutoStart

Determines whether the dashboard should start (or restart) when the server starts or changes are made to the dashboard files.

Starting and Stopping Dashboards

Similar to jobs, dashboards run in separate PowerShell processes. You can start and stop a dashboard process by clicking the Start or Stop button from the Dashboards page.

Viewing Diagnostic Information

You can view diagnostic information for a dashboard by clicking the Info button on the Dashboards page. This will show your start information for the dashboard as well as any error that were encountered when starting the dashboard.

Viewing the Dashboard

You can view the dashboard by clicking the View button. This will take you to the Base URL for the dashboard.

Executing Commands with the Dashboard

On the dashboard information page, click on the Console tab to view the UD console. The console allows you to run scripts from within the UD runspace so you can better debug the state of your script. You can evaluate variables and run commands that are available to the dashboard. You will be running in the context of your user in regards to the runspace but the process will be running as the service account user.

Adding Custom Component Libraries

Custom component libraries provide additional components to dashboards. There are three built in component libraries that are not automatically imported into your dashboards.

  • UniversalDashboard.Charts

  • UniversalDashboard.Map

  • UniversalDashboard.CodeEditor

To add these components to your dashboard, you can use the dashboard UI.

Click the info button on the dashboard page.

Next, click the components button in the top right of your dashboard.

Finally, check the component library you'd like added to your dashboard.

New-PSUDashboard -Name 'Dashboard' -BaseUrl '/' -Framework "UniversalDashboard:Latest" -Component @("UniversalDashboard.Charts:1.3.0")

Persistent Runspaces

Persistent runspaces allow you to maintain runspace state within your dashboard endpoints. This is important for users that perform some sort of initialization within their endpoints that they do not want to execute on subsequent calls.

By default, runspaces will be reset after each execution. This will cause variables, modules and functions defined during the execution of an endpoint.

New-PSUEnvironment -Name 'Env' -Path 'powershell.exe' -PersistentRunspace

You will need to ensure that the environment is used by the dashboard.

Automatically Granting App Tokens

You can automatically grant app tokens to users that visit dashboards. This is useful if you want to invoke the management API for PowerShell Universal from within a dashboard. Your dashboard will need to have authentication enabled and you will have to use the -GrantAppToken switch parameter on New-PSUDashboard.

New-PSUDashboard -Name 'Dashboard' -BaseUrl '/' -Framework "UniversalDashboard:Latest" -Authenticated -GrantAppToken

From within your dashboard, you can now invoke the management API without having to worry about app token management. The API will be invoked in the context of the user that is visiting the dashboard.

New-UDDashboard -Title "Hello, World!" -Content {
    New-UDButton -Text 'Job' -OnClick {
        Invoke-UAScript -Name 'Test.ps1'
    }
}

Parameters

Parameters for PowerShell Universal jobs.

Parameters

Jobs support automatically generating forms with parameters based on your script's param block. The type of control will change based on the type you define in the block. Parameters that are mandatory will also be required by the UI.

Basic Parameters

Parameters can be simply defined without any type of parameter attribute and they will show up as text boxes in the UI.

param($Test)

$Test

Type Parameters

UA supports various types of parameters. You can use String, String[], Int, DateTime, Boolean, Switch and Enum types.

String

You can define string parameters by specifying the [String] type of by not specifying a type at all. Strings will generate a textbox.

param(
    [String]$Textbox,
    $Textbox2
)

String Arrays

You can specify string arrays by using the [String[]] type specifier. String arrays will generate a multi-tag select box.

param([String[]]$Array)

Date and Time

You can use the [DateTime] type specifier to create a date and time selector.

param([DateTime]$DateTime)

Boolean

You can use a [Bool] type selector to create a switch.

param([Bool]$Switch)

Integer

You can define a number selector by using the [Int] type specifier.

param([Int]$Number)

Switch Parameter

You can define a switch parameter using the [Switch] type specifier to create a switch.

param([Switch]$Switch)

Enumerations

You can use System.Enum values to create select boxes. For example, you could use the System.DayOrWeek to create a day of the week selection box.

param([System.DayOfWeek]$DayOfWeek)

Help Messages

You can define help messages for your parameters by using the HelpMessage property of the Parameter attribute.

param(
    [Parameter(HelpMessage = "Class you want to enroll in")]
    [string]$Class
)

Required Parameters

You can use the Parameter attribute to define required parameters.

param(
    [Parameter(Mandatory)]
    $RequiredParameter
)

$RequiredParameter

Passing Parameters from PowerShell

You can pass parameters from PowerShell using the Invoke-UAJob cmdlet. This cmdlet supports dynamic parameters. If you have a param block on your script, these parameters will automatically be added to Invoke-UAJob.

For example, I had a script named Script1.ps1 and the contents were are follows.

param($MyParameter)

$MyParameter

I could then invoke that script using this syntax.

Invoke-UAScript -Name 'Script.ps1' -MyParameter "Hello"

The result would be that Hello was output in the job log and pipeline.

Components

A Universal Dashboard website is composed of components. There are two frameworks that provide a set of core components that you can use within your pages. In addition to the core component, you can also extend Universal Dashboard with a large set of community created components.

External components are distributed as PowerShell modules and can be used in a dashboard by using Import-Module.

When building a dashboard, you can simply call the PowerShell cmdlets within your dashboard script to create a new component.

Adding Components to Dashboards

Some components are not included automatically. You can add component modules by clicking the Components button on the Dashboard page and then adding the components. This list will also include components downloaded from the Marketplace.

Dynamic Regions

Dynamic regions allow you control the reload of data within the region.

New-UDDynamic allows you to define a dynamic region. Pages themselves are dynamic in nature. This means that every time a page is loaded, it runs the PowerShell for that page. Sometimes, you may want to reload a section of a page rather than the whole page itself. This is when you will want to use dynamic regions.

Basic Dynamic Region

This dynamic region reloads when the button is clicked.

Auto Refresh

Dynamic regions enable the ability to auto refresh components after a certain amount of time. The entire region's script block will be run when autorefreshing.

If you have multiple related components that use the same data, consider putting them in the same dynamic region to improve performance.

Loading Component

Sometimes refreshing a dynamic component may take some time. For example, if you are querying another service's REST API or a data. Dynamic regions support configuration of the component that shows when the region is reloading. By default, nothing is shown. This can be any Universal Dashboard component.

API

New-UDDynamic

Defines a dynamic region on a page.

The provides integration for working with automation. We recommend you also install the .

The to run the dashboard within.

You can also add component libraries directly to your dashboards.ps1 script within the .unversal folder or when using .

To enable persistent runspaces, you will need to configure an for your API. Set the -PersistentRunspace parameter to enable this feature. This is configured in the environments.ps1 script.

There are two non-framework components that are built in to PSU. These include the Nivo charts library as well as the UDMap component. They will work in either framework. Additional components can be downloaded from the .

Visual Studio Code extension for PowerShell Universal
PowerShell extension
environment
single-file hosting and configuration
environment
New-UDDashboard -Title 'Dashboard' -Content {
    New-UDTypography -Text 'Hello, world!'
}
New-UDDashboard -Title "Hello, World!" -Content {
    New-UDDynamic -Id 'date' -Content {
        New-UDTypography -Text "$(Get-Date)"
    }

    New-UDButton -Text 'Reload Date' -OnClick { Sync-UDElement -Id 'date' }
}
    New-UDDynamic -Id 'date' -Content {
        New-UDTypography -Text "$(Get-Date)" -Variant h3
        New-UDTypography -Text "$(Get-Random)" -Variant h3
    } -AutoRefresh -AutoRefreshInterval 1
    New-UDDynamic -Content {
        Start-Sleep -Seconds 3
        New-UDTypography -Text "Done!"
    } -LoadingComponent {
        New-UDProgress -Circular
    }

Name

Type

Description

Required

Id

string

Unique identifier for this region

false

ArgumentList

object[]

Arguments to pass to the region. Available within the -Content by using $ArgumentList

false

Content

ScriptBlock

The content to load within the dynamic region

true

AutoRefresh

Switch

Whether this dynamic region will refresh on an interval

false

AutoRefreshInterval

int

The number of seconds between auto refreshes.

false

LoadingComponent

ScriptBlock

A component to display when the dynamic is loading

false

Element

Information about UDElements.

The New-UDElement cmdlet allows you to create custom React elements within your dashboard. Similar to New-UDHtml, you can define HTML elements using New-UDElement. Unlike, New-UDHtml, you can update elements, set auto refresh and take advantage of the React component system.

Create an Element

You need to specify the -Tag and -Content when creating an element. The below example creates a div tag.

New-UDElement -Tag 'div' -Content { 'Hello' }

You can nest components within each other to create HTML structures. For example, you could create an unordered list with the following example.

New-UDElement -Tag 'ul' -Content {
    New-UDElement -Tag 'li' -Content { 'First' }
    New-UDElement -Tag 'li' -Content { 'Second' }
    New-UDElement -Tag 'li' -Content { 'Third' }
}

Setting Attributes

You can select attributes of an element (like HTML attributes) by using the -Attributes parameter. This parameter accepts a hashtable of attribute name and values. The below example creates red text.

New-UDElement -Tag 'div' -Content { 'Hello' } -Attributes @{
    style = @{
        color = 'red'
    }
}

Auto Refreshing Elements

You can define the -AutoRefresh, -RefreshInterval and -Endpoint parameters to create an element the refreshes on a certain interval. The below example creates an element that refreshes every second and displays the current time.

New-UDElement -Tag 'div' -Endpoint {
    Get-Date
} -AutoRefresh -RefreshInterval 1

Setting Element Properties Dynamically

You can use the Set-UDElement cmdlet to set element properties and content dynamically. The following example sets the content of the element to the current time.

New-UDElement -Tag 'div' -Id 'myElement' -Content { }

New-UDButton -Text 'Click Me' -OnClick {
    Set-UDElement -Id 'myElement' -Content { Get-Date }
}

You can also set attributes by using the -Properties parameter of Set-UDElement. The following example sets the current time and changes the color to red.

    New-UDElement -Tag 'div' -Id 'myElement' -Content { }

    New-UDButton -Text 'Click Me' -OnClick {
        Set-UDElement -Id 'myElement' -Content { Get-Date } -Properties @{ Attributes = @{ style = @{ color = "red" } } }
    }

Adding Child Elements

You can add child elements using Add-UDElement. The following example adds child list items to an unordered list.

New-UDElement -Tag 'ul' -Content {

} -Id 'myList'

New-UDButton -Text 'Click Me' -OnClick {
    Add-UDElement -ParentId 'myList' -Content {
        New-UDElement -Tag 'li' -Content { Get-Date }
    }
}

Clearing Child Elements

You can clear the child elements of an element by using Clear-UDElement. The following example clears all the list items from an unordered list.

New-UDElement -Tag 'ul' -Content {
    New-UDElement -Tag 'li' -Content { 'First' }
    New-UDElement -Tag 'li' -Content { 'Second' }
    New-UDElement -Tag 'li' -Content { 'Third' }
}  -Id 'myList'

New-UDButton -Text 'Click Me' -OnClick {
    Clear-UDElement -Id 'myList'
}

Forcing an Element to Reload

You can force an element to reload using Sync-UDElement. The following example causes the div to reload with the current date.

New-UDElement -Tag 'div' -Endpoint {
    Get-Date
} -Id 'myDiv'

New-UDButton -Text 'Click Me' -OnClick {
    Sync-UDElement -Id 'myDiv'
}

Removing an Element

You can remove an element by using Remove-UDElement.

New-UDElement -Tag 'div' -Endpoint {
    Get-Date
} -Id 'myDiv'

New-UDButton -Text 'Click Me' -OnClick {
    Remove-UDElement -Id 'myDiv'
}

API

Get-UDElement

Get component state.

Name

Type

Description

Required

Id

string

The ID of the component to receive.

true

Set-UDElement

Set component state.

Name

Type

Description

Required

Id

string

The ID of the component to set.

true

Properties

Hashtable

Properties to set on the component

false

Broadcast

Switch

Set the properties of a component for all users.

false

Content

ScriptBlock

The content of the component to set.

false

Remove-UDElement

Remove a component.

Name

Type

Description

Required

Id

string

The ID of the component to remove.

true

Add-UDElement

Add a child component.

Name

Type

Description

Required

ParentId

string

The ID of the component to add a child to.

true

Content

ScriptBlock

The child content to add.

true

Broadcast

Switch

Whether to add the child component to all users.

false

Clear-UDElement

Clear child components out of a component.

Name

Type

Description

Required

Id

string

The ID of the component to clear.

true

Sync-UDElement

Reload a component

Name

Type

Description

Required

Id

string

The ID of the component to reload.

true

Broadcast

Switch

Whether to reload the component for all users.

false

Select-UDElement

Select a component.

Name

Type

Description

Required

Id

string

The ID of the element to select

true

ScrollToElement

Switch

Whether to scroll the user's window to the element

false

UD Marketplace

About

Universal Dashboard a robust web-based UI library for PowerShell.

Build interactive user interfaces and dashboards with PowerShell script. Integrate with your existing PowerShell modules and functions to bring data in from anywhere.

  • Build tools for your help desk users

  • Report on data in interactive visualizations like charts, calendars, maps and more

  • Provide role-based access controls to pages and even individual components

Jobs

Jobs are the result of running a script. Jobs are retained based on the script and server level settings.

Viewing Jobs

Jobs can be viewed by clicking the Automation / Jobs page. Click the View button to navigate to the job. Jobs in progress can also bee cancelled.

View Job Output

Standard job output is shown on the Output Tab of the job page. This should contain text from various PowerShell streams.

View Job Pipeline Output

Pipeline output for jobs are also stored within UA. Any object that is written to the pipeline is stored as CliXml and available for view within the Pipeline Output tab.

You can expand the tree view to see the objects and properties from the pipeline.

Viewing Errors

Any errors written to the error stream will be available on the Error tab within the job page.

Feedback

Some jobs will require feedback. Any script that contains a Read-Host call will wait until there is user interaction with that job. The job will be in a Waiting for Feedback state and you can respond to that feedback by click the Response to Feedback button on the job page.

Invoking Jobs from PowerShell

Invoke-UAScript -Script 'Script1.ps1' -RequiredParameter 'Hello'

Call Scripts from Scripts

You can also call UA scripts from UA scripts. When running a job in UA, you don't need to define an app token or the computer name manually. These will be defined for you. You can just call Invoke-UAScript within your script to start another script. Both jobs will be shown in the UI. If you want to wait for the script to finish, use Wait-UAJob.

Waiting for a Script to Finished

You can use the Wait-UAJob cmdlet to wait for a job to finish. Pipe the return value of Invoke-UAScript to Wait-UAJob to wait for the job to complete. Wait-UAJob will wait indefinitely unless the -Timeout parameter is specified.

Invoke-UAScript -Script 'Script1.ps1' -RequiredParameter 'Hello' | Wait-UAJob

Return Pipeline Data

You can use the Get-PSUJobPipelineOutput cmdlet to return the pipeline output that was produced by a job. This pipeline output will be deserialized objects that were written to the pipeline during the job. You can access this data from where you have access to the PowerShell Universal Management API.

Get-PSUJobPipelineOutput -JobId 10

Returning the last job's output

It may be required to return the output from a script's last job run. In order to do this, you will need to use a combination of cmdlets to retrieve the script, the last job's ID and then return the pipeline or host output.

$Job = Get-UAScript -Name 'Script.ps1' | Get-UAJob -OrderDirection Descending -First 1
Get-UAJobPipelineOutput -Job $Job
Get-UAJobOutput -Job $Job

Invoke a Script and Wait for Output

The following example invokes a script, stores the job object in a $job variable, waits for the job to complete and then returns the pipeline and host output.

Invoke-UAScript -Script 'Script1.ps1' -RequiredParameter 'Hello' | Tee-Object -Variable job | Wait-UAJob

$Pipeline = Get-UAJobPipelineOutput -Job $Job
$HostOutput = Get-UAJobOutput -Job $Job

Invoking Jobs with REST

You can call jobs over REST using the management API for PowerShell Universal. You will need a valid app token to invoke jobs.

Call Scripts with REST

To call a script, you call an HTTP POST to the script endpoint with the ID of the script you wish to execute.

Invoke-RestMethod http://localhost:5000/api/v1/script/7 -Method POST -Body "" -Headers @{ Authorization = "Bearer appToken" } -ContentType 'application/json'

Providing Parameters

To provide parameters to scripts, you will need to define the parameters are part of the body. Currently the value is required to be a CLIXML string.

$JobContext = @{
    JobParameters = @(
        @{ Name = "parameter1"; Value = '<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
          <S>String</S>
        </Objs>' },
    )
} | ConvertTo-Json -Depth 5

Invoke-RestMethod http://localhost:5000/api/v1/script/7 -Method POST -Body $JobContext -Headers @{ Authorization = "Bearer appToken" } -ContentType 'application/json'

To generate CLIXML, you can use the PSSerializer class in PowerShell. You can pass any object into the serialize method.

If you want to pass a credential you will need to pass in the parameter as a variable. You do not need to serialize the variable name.

$JobContext = @{
    JobParameters = @(
        @{ Name = "parameter1"; Value = "myCredential"; IsVariable = $true },
    )
} | ConvertTo-Json -Depth 5

Invoke-RestMethod http://localhost:5000/api/v1/script/7 -Method POST -Body $JobContext -Headers @{ Authorization = "Bearer appToken" } -ContentType 'application/json'

Setting the Environment

You can set the environment by pass in the environment property to the job context. The property must be the name of an environment defined within your PSU instance.

$JobContext = @{
    Environment = "PowerShell 7"
} | ConvertTo-Json

Invoke-RestMethod http://localhost:5000/api/v1/script/7 -Method POST -Body $JobContext -Headers @{ Authorization = "Bearer appToken" } -ContentType 'application/json'

Setting the Run As account

You can set the run as account by passing in the name of a PSCredential variable to the Credential property.

$JobContext = @{
    Credential = "MyUser"
} | ConvertTo-Json

Invoke-RestMethod http://localhost:5000/api/v1/script/7 -Method POST -Body $JobContext -Headers @{ Authorization = "Bearer appToken" } -ContentType 'application/json'

Variables Defined in Jobs

There are several built-in variables that are defined when a job is run. You can use these variables in your scripts to retrieve information about the current job.

Name

Description

$UAJob

The current job that is running. This will include properties such as the script, the user that started the job and when the job was started.

$UAJobId

The ID of the running job.

$UAScript

The script that is running. This will include properties such as the name of the script and path to the script.

$UAScriptId

The ID of the running script.

$UASchedule

The schedule that was used to start the script.

$UAScheduleId

The ID of the schedule that started the script.

Retrieving the user that started a script

You can retrieve the name of the user that started the script by using the UAJob variable

$UAJob.Identity.Name

Error Boundary

Error boundary component for Universal Dashboard.

The New-UDErrorBoundary component is used for isolating portions of a dashboard to contain components that may throw an error. Many Universal Dashboard components use the error boundary component internally.

If you'd like to isolate a portion of your dashboard to prevent the entire page from failing to load, you can use the following syntax.

If any error is thrown from the content, you will see an error such as thing.

API

New-UDErrorBoundary

Display an error card when an error is thrown in your script.

Pages

Information about Universal Dashboard pages.

A dashboard can consist of one or more pages. A page can have a particular name and URL. You can define a URL that accepts one or more variables in the URL to define a dynamic page.

Basic Page

A basic page can be defined using the New-UDPage cmdlet. You could navigate to this page by visiting the /dashboard URL of your dashboard.

Dashboard with Multiple Pages

Dashboards can have multiple pages and those pages can be defined by passing an array of UDPages to New-UDDashboard

You may want to organize your dashboard into multiple PS1 files. You can do this using pages.

Page with a Custom URL

A page can have a custom URL by using the -Url parameter. You could navigate to this page by visiting the /db URL of your dashboard.

Page with Variables in URL

You can define a page with variables in the URL to create pages that adapt based on that URL.

Query string parameters

Query string parameters are passed to pages and other endpoints as variables.

For example, if you visited a page with the following query string parameter: http://localhost:5000/dashboard/Page1?test=123

You would then have access to a $Test variable that contained the value 123.

Role-Based Access

Navigation

Custom Navigation

Custom navigation can be defined with a list. List items can include children to create drop down sections in the navigation.

Dynamic Navigation

Dynamic navigation can be used to execute scripts during page load to determine which navigation components to show based on variables like the user, IP address or roles.

You can generate dynamic navigation by using the -LoadNavigation parameter. The value of the parameter should be a script block to execute when loading the navigation.

Layouts

The permanent layout creates a static navigation drawer on the left hand side of the page. It cannot be hidden by the user.

The temporary layout creates a navigation drawer that can be opened using a hamburger menu found in the top left corner. This is the default setting.

Logo

You can display a logo in the navigation bar by using the -Logo parameter.

Now, when creating your page, you can specify the path to the logo.

The logo will display in the top left corner.

API

New-UDPage

Creates a new page. Pass the results to New-UDDashboard -Pages

Frameworks

Dashboard Frameworks define the PowerShell scripts and JavaScript components that are used to render the dashboard. Additional frameworks, when available, can be added through the Add Framework button from the Dashboard Frameworks page.

There are two dashboard frameworks built into PSU. Universal Dashboard v2 and Universal Dashboard v3. The intent of Universal Dashboard v2 is to enable users of PowerShell Universal Dashboard to easily run their existing dashboards within PowerShell Universal. Only bug fixes will be going into UDv2. Universal Dashboard v3 is built on a more modern framework and will be receiving feature updates going forward.

Both dashboards are open source so you can contribute to the dashboard in terms of bug fixes or features.

For an example of each framework, click on the appropriate link below.

Building Custom Components

This document outlines how to build custom Universal Dashboard components.

Universal Dashboard is extensible and you can build custom JavaScript components and frameworks. This document will cover how to build custom components that integrate with the Universal Dashboard platform.

Technology Overview

Below is a list of some of the technologies used when building Universal Dashboard components. You will not need to be an expert to produce a component but should be aware of what to search when you encounter a problem.

React

Babel

Webpack

Structure

There are some basic parts to a Universal Dashboard component. You will need to understand the structure in order to successfully build your own.

PowerShell Module

Universal Dashboard custom components are PowerShell modules. They export functions that can be used to create the component when run within a dashboard. The PowerShell module is also responsible for registering the JavaScript assets with Universal Dashboard.

JavaScript Bundle

The JavaScript bundle is produced by the Webpack bundling process. It consists of one or more JS files that you will need to register with UD.

Example Component Module Structure

The most basic structure for a UD component module will include a single JavaScript file, a PSM1 file to export a function and register the JavaScript and a PSD1 module manifest.

Step-By-Step

This following section will take you step-by-step through the different aspects of building a UD component. This assumes you are running PowerShell Universal 1.2 or later and using the PowerShell Universal Dashboard v3 framework.

1. Installing Dependencies

You will need to install the following dependencies before creating your component.

2. Initialize the JavaScript Package

After installing Node, you will have access to the npm command. You will need to initialize the node package to start. This will create a package.json file in your directory.

3. Install JavaScript Packages

You will need several JavaScript packages to build your bundle. You will first want to install the dev dependencies. These are used to build your project.

Next, you'll want to install the universal-dashboard package along with any other packages you wish to use in your component. We are using React95 in this example. We will build a control based on that library.

4. Configure Babel

You will need to create a .babelrc file to configure Babel for React.

5. Configure Webpack

Webpack is extremely customizable and sometimes very hard to get right. Below is a basic webpack.config.js file you can use to configure Webpack. You can safely change the ud95 entry key name and library value to one that matches your library.

6. Component.jsx

Now you can build your first component. You will need to export a single function component from your component.jsx file. We suggest the use of functional React components rather than class-based React components. We need to wrap the component in withComponentFeatures to ensure the component has access to the Universal Dashboard platform features.

7. Index.js

Once your component is completed, you'll need to add it to an index.js file. The entry point for your library is the first place Webpack will look. It will discover all other components from import statements in your code. The index.js file is where you should register your components. You can use the registerComponent function to do so.

8. Bundle JavaScript

To bundle the JavaScript, run the following command to start webpack. This will output a file into the dist folder.

9. PowerShell Script

Now you will need to create a PowerShell script that registers and creates your component.

First, register the JavaScript with Universal Dashboard.

Next, create a function that returns a hashtable that defines which component we are creating and which props to set.

The type property of your hashtable needs to match with the first parameter of registerComponent that you called in your JavaScript.

10. InvokeBuild (optional)

We suggest the use of InvokeBuild to create a build script to run all the steps of packaging and staging your module. The below build script deletes the dist folder, runs an NPM install to install packages, runs an NPM build to bundle the JavaScript and then copies the PS module to the dist folder.

Props

Props are values that are either passed from the PowerShell hashtable provided by the user or by the Universal Dashboard withComponentsFeature high-order function.

Standard

The properties that you set in your hashtable in PowerShell will automatically be sent in as props to React component.

For example, if you set the text property of the hashtable like this.

Then you will have access to that prop in React.

Endpoints

Endpoints are special in the way they are registered and the way that they are passed as props to your component. You will need to call Register on the endpoint in PowerShell and pass in the Id and PSCmdlet variables.

Endpoints are created from ScriptBlocks and are executed when that event happens.

Universal Dashboard will automatically wire up the endpoint to a function within JavaScript. This means that you can use the props to call that endpoint.

Notice the props.onClick function call. This will automatically call the PowerShell script block on the server.

setState

The setState prop is used to set the state of the component. This ensures that the state is tracked and your component will work with Get-UDElement.

For example, with a text field, you'll want to call props.setState and pass in the new text value for the state.

children

The children prop is a standard React prop. If your component supports child items, such as a list or select box, you should use the standard props.children prop to ensure that the cmdlets Add-UDElement , Remove-UDElement and Clear-UDElement function correctly.

Publishing to the Marketplace

To publish to the Marketplace, you simply need to publish to the PowerShell Gallery but include the ud-component tag in your module manifest. The marketplace syncs with the Gallery every hour and your component will be enabled for anyone to find after that.

Custom Variable Scopes

Custom Variable Scopes

Universal Dashboard exposes two custom variable scopes using custom providers. These providers allow you to store your variables in scopes that make sense for a web application. The cache scope is used to store variables that can be used within any endpoint inside a dashboard. The session scope is used to store variables that can be used for a single user's session of the dashboard.

Cache Scope

Cache scope is used to store a variable that will be available in any endpoint. Cache scope is useful for storing data that make be shown in more than one control or may be time consuming to look up. This could be helpful for querying machine performance counters, Active Directory or Azure.

Just like any other scope, cache variables are defined with a prefix and a colon separator.

Once assigned, the $Cache:Computer variable is available within any endpoint.

Session Scope

Session scope is used to store a variable per session. A session is established when a user's browser first visit a dashboard. A cookie is stored in the user's browser that dictates that it is part of the session. Sessions have an idle timeout of 25 minutes.

Just like any other scope, cache variables are defined with a prefix and a colon separator.

Once assigned, the $Session:ShowChart variable is available in dashboard endpoints. Session variables are not available in REST API endpoints or scheduled endpoints.

Once a session is terminated, the session variables are cleared.

HTML

Define static HTML using Universal Dashboard.

You can define static HTML using New-UDHtml. This cmdlet does not create React components but rather allows you to define static HTML. Any valid HTML string is supported.

The following creates an unordered list.

API

New-UDHtml

Write raw HTML to your dashboard.

Adding a component module
Reload on button click
Auto refresh dynamic region
Loading component for dynamic region

You can use Invoke-UAScript to invoke jobs from the command line. You will need a valid to do so. Parameters are defined using dynamic parameters on the Invoke-UAScript cmdlet.

This feature requires a .

You can prevent users from accessing pages based on their role by using the -Role parameter of pages. You can configure roles and role policies on the .

You can customize the navigation of a page using the -Navigation and -NavigationLayout parameters. Navigation is defined using the component. Navigation layouts are either permanent or temporary.

First, setup a to host your logo.

To customize the style of your logo, you can use a and target the ud-logo element ID.

This is an advanced topic and not required if you simply want to use Universal Dashboard. There are a lot of existing custom components available on the .

Look at on how to get started with custom components for full end-to-end example.

Universal Dashboard's client-side application is built using the . React makes it easy to build components that update the DOM only when necessary and has a pretty robust ecosystem of users. It's one of the most popular JavaScript frameworks at the time of this writing.

is a transcompiler for JavaScript. It works well with React and allows you to use modern constructs while compiling for backwards compatibility of browsers. Universal Dashboard uses Babel for it's core component frameworks.

is an asset bundler. It's extremely customizable and is responsible for turning your JSX files into a bundle that can then be distributed with Universal Dashboard components.

For a full example of a component, .

package.json that you can also use as a starting point.

The is an aggregator of the PowerShell Gallery that lists Universal Dashboard components. The UD Marketplace automatically hooks into PowerShell Universal v1.3 or later where you can easily install additional components.

New-UDErrorBoundary -Content {
    throw "Oh no!"
}

Name

Type

Description

Required

Content

ScriptBlock

A script block to prevent from throwing an error to the top of the page.

True

$Pages = @()
$Pages += New-UDPage -Name 'Dashboard' -Content {
    New-UDTypography -Text 'Dashboard'
}

New-UDDashboard -Title 'Pages' -Pages $Pages
$Pages = @()
$Pages += New-UDPage -Name 'Dashboard One' -Content {
    New-UDTypography -Text 'Dashboard Two'
}

$Pages += New-UDPage -Name 'Dashboard Two' -Content {
    New-UDTypography -Text 'Dashboard Two'
}

New-UDDashboard -Title 'Pages' -Pages $Pages
$UDScriptRoot = $PSScriptRoot
$Pages = @()
$Pages += New-UDPage -Name 'Dashboard One' -Content {
    . "$UDScriptRoot\db1.ps1"
}

$Pages += New-UDPage -Name 'Dashboard Two' -Content {
    . "$UDScriptRoot\db2.ps1"
}

New-UDDashboard -Title 'Pages' -Pages $Pages
$Pages = @()
$Pages += New-UDPage -Name 'Dashboard' -Url '/db' -Content {
    New-UDTypography -Text 'Dashboard'
}

New-UDDashboard -Title 'Pages' -Pages $Pages
$Pages = @()
$Pages += New-UDPage -Name 'Dashboard' -Url '/db/:user' -Content {
    New-UDTypography -Text 'Dashboard for user: $User'
}

New-UDDashboard -Title 'Pages' -Pages $Pages
$Pages = @()
$Pages += New-UDPage -Name 'Administrators' -Content {
    New-UDTypography -Text 'Dashboard for user: $User'
} -Role 'Administrator'

$Pages += New-UDPage -Name 'Operators' -Content {
    New-UDTypography -Text 'Dashboard for user: $User'
} -Role 'Operator'

New-UDDashboard -Title 'Pages' -Pages $Pages
$Navigation = @(
    New-UDListItem -Label "Home"
    New-UDListItem -Label "Getting Started" -Children {
        New-UDListItem -Label "Installation" -OnClick { Invoke-UDRedirect '/installation' }
        New-UDListItem -Label "Usage" -OnClick { Invoke-UDRedirect '/usage' }
        New-UDListItem -Label "FAQs" -OnClick { Invoke-UDRedirect '/faqs' }
        New-UDListItem -Label "System Requirements" -OnClick { Invoke-UDRedirect '/requirements' }
        New-UDListItem -Label "Purchasing" -OnClick { Invoke-UDRedirect '/purchasing'}
    }
)

$Pages = @()
$Pages += New-UDPage -Name 'Test' -Content {
 New-UDTypography -Text "Hello"
} -NavigationLayout permanent -Navigation $Navigation

$Pages += New-UDPage -Name 'Test2' -Content {
    New-UDTypography -Text "Hello"
} -NavigationLayout permanent -Navigation $Navigation


New-UDDashboard -Title "Hello, World!" -Pages $Pages
$Navigation = {
    New-UDListItem -Label "Home - $(Get-Date)"
    New-UDListItem -Label "Getting Started" -Children {
        New-UDListItem -Label "Installation" -OnClick { Invoke-UDRedirect '/installation' }
        New-UDListItem -Label "Usage" -OnClick { Invoke-UDRedirect '/usage' }
        New-UDListItem -Label "FAQs" -OnClick { Invoke-UDRedirect '/faqs' }
        New-UDListItem -Label "System Requirements" -OnClick { Invoke-UDRedirect '/requirements' }
        New-UDListItem -Label "Purchasing" -OnClick { Invoke-UDRedirect '/purchasing'}
    }
}

$Pages = @()
$Pages += New-UDPage -Name 'Test' -Content {
 New-UDTypography -Text "Hello"
} -NavigationLayout permanent -LoadNavigation $Navigation

$Pages += New-UDPage -Name 'Test2' -Content {
    New-UDTypography -Text "Hello"
} -NavigationLayout permanent -LoadNavigation $Navigation


New-UDDashboard -Title "Hello, World!" -Pages $Pages
$Pages = @()
$Pages += New-UDPage -Name 'Test' -Content {
 New-UDTypography -Text "Hello"
} -NavigationLayout permanent

$Pages += New-UDPage -Name 'Test2' -Content {
    New-UDTypography -Text "Hello"
} -NavigationLayout permanent


New-UDDashboard -Title "Hello, World!" -Pages $Pages
$Pages = @()
$Pages += New-UDPage -Name 'Test' -Content {
 New-UDTypography -Text "Hello"
} -NavigationLayout temporary

$Pages += New-UDPage -Name 'Test2' -Content {
    New-UDTypography -Text "Hello"
} -NavigationLayout temporary


New-UDDashboard -Title "Hello, World!" -Pages $Pages
New-UDPage -Name 'Home' -Logo '/assets/favicon.png' -Content {
}

Name

Type

Description

Required

Name

string

The name of the page.

true

Content

ScriptBlock

The content of the page.

true

Url

string

The URL for the page. Name is used if no URL is specified.

false

DefaultHomePage

Switch

The page is the default home page.

false

Title

string

The title to display at the top of the page

false

Blank

Switch

Creates a page that has no toolbar.

false

Id

string

The ID for the page. This needs to be unique.

false

OnLoading

ScriptBlock

Return a component to show when the page is loading

false

Role

string[]

Roles that have access to this page.

false

NavigationLayout

string

Whether to popup or pin navigation.

false

Navigation

Hashtable[]

A collection of UDListItems to display for navigation

false

Logo

string

The URL to a logo to display in the toolbar.

false

LoadNavigation

ScriptBlock

Dynamically load navigation when the user loads the page.

false

- UniversalDashboard.95
    - index.23adfdasf.js
    - UniversalDashboard.95.psd1
    - UniversalDashboard.95.psm1
npm init
npm install @babel/core --save-dev
npm install @babel/plugin-proposal-class-properties --save-dev
npm install @babel/plugin-syntax-dynamic-import --save-dev
npm install @babel/polyfill --save-dev
npm install @babel/preset-env --save-dev
npm install @babel/preset-react --save-dev
npm install babel-loader --save-dev
npm install webpack --save-dev
npm install webpack-cli --save-dev
npm install universal-dashboard --save
npm install react95 --save
npm install styled-components --save
{
    "presets": ["@babel/preset-react"]
}
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'dist');

module.exports = (env) => {
  const isDev = env == 'development' || env == 'isolated';

  return {
    entry: {
      'ud95' : __dirname + '/index.js'
    },
    output: {
      library: "UD95",
      libraryTarget: "var",
      path: BUILD_DIR,
      filename: isDev ? '[name].bundle.js' : '[name].[hash].bundle.js',
      sourceMapFilename: '[name].[hash].bundle.map',
      publicPath: "/"
    },
    module : {
      rules : [
        { test: /\.(js|jsx)$/, exclude: [/node_modules/, /public/], loader: 'babel-loader'}
      ]
    },
    externals: {
      UniversalDashboard: 'UniversalDashboard',
      'react': 'react',
      'react-dom': 'reactdom'
    },
    resolve: {
      extensions: ['.json', '.js', '.jsx']
    }
  };
}
import React from 'react';
import { withComponentFeatures } from 'universal-dashboard';
import { Button } from 'react95';

const UD95Button = props => {

    const p = {
        onClick: () => props.onClick()
    }

    return <Button {...p}>{props.text}</Button>
}

export default withComponentFeatures(UD95Button);
import { registerComponent } from 'universal-dashboard'
import UD95Button from './component';

registerComponent("ud95-button", UD95Button);
npm run build
$JsFile = Get-ChildItem "$PSScriptRoot\ud95.*.js"
$AssetId = [UniversalDashboard.Services.AssetService]::Instance.RegisterAsset($JsFile.FullName)
function New-UD95Button {
    param(
        [Parameter()]
        [string]$Id = [Guid]::NewGuid(),
        [Parameter()]
        [string]$Text,
        [Parameter()]
        [Endpoint]$OnClick
    )

    if ($OnClick)
    {
        $OnClick.Register($Id, $PSCmdlet)
    }

    @{
        type = "ud95-button"
        isPlugin = $true 
        assetId = $AssetId

        id = $Id 
        text = $Text 
        onClick = $OnClick
    }
}
task Clean {
    Remove-Item "$PSScriptRoot\dist" -Recurse -Force
}

task NpmInstall {
    & {
        $ErrorActionPreference = 'SilentlyContinue'

        Push-Location $PSScriptRoot
        npm install
        Pop-Location
    }
}

task NpmBuild {
    & {
        $ErrorActionPreference = 'SilentlyContinue'

        Push-Location $PSScriptRoot
        npm run build
        Pop-Location
    }
}

task Stage {
    Copy-Item "$PSScriptRoot\UniversalDashboard.95.*" "$PSScriptRoot\dist"
}

task . Clean, NpmInstall, NpmBuild, Stage
function New-UDText {
    param(
        [Parameter()]
        [string]$Text
    )

    @{
        type = "text"
        isPlugin = $true
        assetId = $AssetId 

        text = $Text
    }
}
import React from 'react';
import { withComponentFeatures } from 'universal-dashboard';

const UDText = props => {
    return <div>{props.text}</div>
}

export default withComponentFeatures(UDText);
function New-UD95Button {
    param(
        [Parameter()]
        [string]$Id = [Guid]::NewGuid(),
        [Parameter()]
        [string]$Text,
        [Parameter()]
        [Endpoint]$OnClick
    )

    if ($OnClick)
    {
        $OnClick.Register($Id, $PSCmdlet)
    }

    @{
        type = "ud95-button"
        isPlugin = $true 
        assetId = $AssetId

        id = $Id 
        text = $Text 
        onClick = $OnClick
    }
}
New-UD95Button -Text 'Hello' -OnClick {
    Show-UDToast -Message 'Test' 
}
import React from 'react';
import { withComponentFeatures } from 'universal-dashboard';
import { Button } from 'react95';

const UD95Button = props => {

    const p = {
        onClick: () => props.onClick()
    }

    return <Button {...p}>{props.text}</Button>
}

export default withComponentFeatures(UD95Button);
const UDTextField = (props) => {
    const onChange = (e) => {
        props.setState({value: e.target.value})
    }

    return <TextField  {...props} onChange={onChange} />
}

export default withComponentFeatures(UDTextField);
$Cache:Computers = Get-ADComputer
New-UDMonitor -Title Computers -Endpoint {
    $Cache:Computers.Length | Out-UDMonitorData
}
New-UDCheckbox -Label "Show chart" -OnChange {
   $Session:ShowChart = $EventData
}
New-UDColumn -Endpoint {
    if ($Session:ShowChart) {
         New-UDChart ...
    }
}
New-UDHtml -Markup "<ul><li>First</li><li>Second</li><li>Third</li></ul>"

Name

Type

Description

Required

Markup

string

The HTML to display.

True

Universal Dashboard Basics
license
published folder
cascading style sheet
Universal Dashboard v2
Universal Dashboard v3
Universal Dashboard Marketplace
our blog post
React framework
Babel
Webpack
click here
NodeJS
InvokeBuild
Here is an example
Universal Dashboard Marketplace

Icon

Icon component for Universal Dashboard

Icon

Create icons by specifying their names. You can use the icon reference below to find icons.

New-UDIcon -Icon 'address_book'

Size

Set the size of the icon. Valid values are: xs, sm, lg, 2x, 3x, 4x, 5x, 6x, 7x, 8x, 9x, 10x

    New-UDIcon -Icon 'address_book' -Size 'sm'
    New-UDIcon -Icon 'address_book' -Size 'lg'
    New-UDIcon -Icon 'address_book' -Size '5x'
    New-UDIcon -Icon 'address_book' -Size '10x'

Rotation

Rotate icons. The value represents the degrees of rotation.

New-UDIcon -Icon 'address_book' -Size '5x' -Rotation 90

Border

Add a border to your icon.

New-UDIcon -Icon 'address_book' -Size '5x' -Border

Style

Apply CSS styles to your icon.

New-UDIcon -Icon 'address_book' -Size '5x' -Style @{
    backgroundColor = "red"
}

Visually Search for Icons

New-UDTextbox -Id 'txtIconSearch' -Label 'Search' 
New-UDButton -Text 'Search' -OnClick {
    Sync-UDElement -Id 'icons'
}

New-UDElement -tag 'p' -Content {}

New-UDDynamic -Id 'icons' -Content {
        $Icons = [Enum]::GetNames([UniversalDashboard.Models.FontAwesomeIcons])
        $IconSearch = (Get-UDElement -Id 'txtIconSearch').value
        if ($null -ne $IconSearch -and $IconSearch -ne '')
        {
        $Icons = $Icons.where({ $_ -match $IconSearch})
    }

    foreach($icon in $icons) {
        New-UDIcon -Icon $icon -Size lg
    }
}

Parameters

New-UDIcon

Name

Type

Description

Required

Id

string

Id of the icon

false

Icon

FontAwesomeIcons

Icon to select

false

FixedWidth

switch

false

Inverse

switch

Whether to inverse the icon

false

Rotation

int

Rotates an icon clockwise based on the degrees specified

false

ClassName

string

false

Transform

string

false

Flip

string

false

Pull

string

false

ListItem

switch

false

Spin

switch

Caues the icon to spin.

false

Border

switch

Adds a border to the icon.

false

Pulse

switch

false

Size

string

The size of the icon

false

Style

hashtable

A CSS style to apply to the icon.

false

Title

string

false

Regular

switch

false

Color

Alert

Alert component for Universal Dashboard.

Alerts provide a simple way to communicate information to a user.

Simple Alerts

Alerts have four different severities and can include text or other content.

Advanced Alerts

Alerts can contain any component and also a title.

API

New-UDAlert

Date and Time

Date and time component for Universal Dashboard.

The New-UDDateTime component is used for formatting dates and times within the client's browser. By using the client's browser, you can format the time based on the local time zone and locale settings for the user.

Basic Formatting

By default, the date and time will be formatted using the LLL localized formatting template.

Resulting output: August 16, 2018 8:02 PM

Custom Formatting

Resulting output: 25/01/2019

API

New-UDDateTime

Chip

Chip component for Universal Dashboard.

Chips are compact elements that represent an input, attribute, or action.

Chips allow users to enter information, make selections, filter content, or trigger actions.

While included here as a standalone component, the most common use will be in some form of input, so some of the behavior demonstrated here is not shown in context.

Basic Chips

Chips with Icons

OnClick

Shows a toast when the chip is clicked.

OnDelete

New-UDChip

Custom navigation
Permanent navigation drawer
Temporary navigation drawer
Published assets folder
Logo

icons to include in your dashboard.

The date and time component uses DayJS. For a full list of custom formatting options, visit the .

You can specify custom formatting strings using the .

FontAwesome
New-UDAlert -Severity 'error' -Text 'This is an error alert — check it out!' 
New-UDAlert -Severity 'warning' -Text 'This is an warning alert — check it out!'
New-UDAlert -Severity 'info' -Text 'This is an error info — check it out!' 
New-UDAlert -Severity 'success' -Text 'This is an success alert — check it out!'
New-UDAlert -Severity 'error' -Content { New-UDHtml 'This is an error alert — <strong>check it out!</strong>' } -Title "Error"
New-UDAlert -Severity 'warning' -Content { New-UDHtml 'This is an warning alert — <strong>check it out!</strong>' } -Title "Warning"
New-UDAlert -Severity 'info' -Content { New-UDHtml 'This is an error info — <strong>check it out!</strong>' } -Title "Info"
New-UDAlert -Severity 'success' -Content { New-UDHtml 'This is an success alert — <strong>check it out!</strong>' } -Title "Success"

Name

Type

Description

Required

Id

string

The ID of this component.

False

Severity

string

The type of alert to display.

False

Content

ScriptBlock

Custom alert content to display.

False

Text

string

Text to display within the alert.

False

Title

string

The title of the alert.

False

New-UDDateTime -InputObject (Get-Date)
New-UDDateTime -InputObject (Get-Date) -Format 'DD/MM/YYYY'

Name

Type

Description

Required

Id

string

ID of this component.

False

InputObject

string

The date and time to format.

True

Format

string

The DayJS format string.

False

LocalizedFormat

string

The DayJS localized formatting string.

False

 New-UDChip -Label 'Basic'
New-UDChip -Label 'Basic' -Icon (New-UDIcon -Icon 'user')
New-UDChip -Label 'OnClick' -OnClick {
    Show-UDToast -Message 'Hello!'
}
New-UDChip -Label 'OnDelete' -OnClick {
    Show-UDToast -Message 'Goodbye!'
}

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Label

String

The label for the chip.

false

OnDelete

Object

A script block to call when the chip is deleted.

false

OnClick

Object

A script block to call when the chip is clicked.

false

Icon

Object

An icon to show within the chip.

false

Style

Hashtable

CSS styles to apply to the chip.

false

Variant

String

The theme variant to apply to the chip.

false

Avatar

String

An avatar to show within the chip.

false

AvatarType

String

The type of avatar to show in the chip.

false

DayJS documentation
DayJS formatting template
List

Tree View

Tree view component for Universal Dashboard.

New-UDTreeView allows you to create a tree of items and, optionally, dynamically expand the list when clicked.

Basic Tree View

Create a basic tree view by using the New-UDTreeNode cmdlet.

New-UDTreeView -Node {
    New-UDTreeNode -Name 'Level 1' -Children {
        New-UDTreeNode -Name 'Level 2 - Item 1' 
        New-UDTreeNode -Name 'Level 2 - Item 2'
        New-UDTreeNode -Name 'Level 2 - Item 3' -Children {
            New-UDTreeNode -Name 'Level 3'
        }
    }
}

Dynamic Tree View

Dynamic tree views allow you to run PowerShell whenever a node is clicked. You can then return a list of nodes that should be rendered underneath the clicked node. You can also take other actions such as opening a modal or showing a toast.

New-UDTreeView -Node { New-UDTreeNode -Name root } -OnNodeClicked {
    New-UDTreeNode -name "$($EventData.Name)child"
}

Typography

Typography component for Universal Dashboard

Use typography to present your design and content as clearly and efficiently as possible.

Too many type sizes and styles at once can spoil any layout. A typographic scale has a limited set of type sizes that work well together along with the layout grid.

All Typography Types

@("h1", "h2", "h3", "h4", "h5", "h6", "subtitle1", "subtitle2", "body1", "body2", 
"caption", "button", "overline", "srOnly", "inherit", 
"display4", "display3", "display2", "display1", "headline", "title", "subheading") | ForEach-Object {
    New-UDTypography -Variant $_ -Text $_ -GutterBottom
    New-UDElement -Tag 'p' -Content {}
}

Colored Text

You can use the -Style parameter to define colors for your text.

New-UDTypography -Text 'My Text' -Style @{ color = 'blue' }

New-UDTypography

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Variant

String

The type of text to display.

false

Text

String

The text to format.

false

Content

ScriptBlock

The content to format.

false

Style

Hashtable

A set of CSS styles to apply to the typography.

false

ClassName

String

A CSS className to apply to the typography.

false

Align

String

How to align the typography.

false

GutterBottom

SwitchParameter

The gutter bottom.

false

NoWrap

SwitchParameter

Disables text wrapping.

false

Paragraph

SwitchParameter

Whether this typography is a paragraph.

false

List

List component for Universal Dashboard.

Lists are continuous, vertical indexes of text or images.

Lists are a continuous group of text or images. They are composed of items containing primary and supplemental actions, which are represented by icons and text.

List

New-UDList -Content {
    New-UDListItem -Label 'Inbox' -Icon (New-UDIcon -Icon envelope -Size 3x) -SubTitle 'New Stuff'
    New-UDListItem -Label 'Drafts' -Icon (New-UDIcon -Icon edit -Size 3x) -SubTitle "Stuff I'm working on "
    New-UDListItem -Label 'Trash' -Icon (New-UDIcon -Icon trash -Size 3x) -SubTitle 'Stuff I deleted'
    New-UDListItem -Label 'Spam' -Icon (New-UDIcon -Icon bug -Size 3x) -SubTitle "Stuff I didn't want"
}

OnClick Event Handler

You can define an action to take when an item is clicked by using the -OnClick parameter of New-UDListItem.

New-UDList -Content {
    New-UDListItem -Label 'Inbox' -Icon (New-UDIcon -Icon envelope -Size 3x) -SubTitle 'New Stuff'
    New-UDListItem -Label 'Drafts' -Icon (New-UDIcon -Icon edit -Size 3x) -SubTitle "Stuff I'm working on "
    New-UDListItem -Label 'Trash' -Icon (New-UDIcon -Icon trash -Size 3x) -SubTitle 'Stuff I deleted'
    New-UDListItem -Label 'Spam' -Icon (New-UDIcon -Icon bug -Size 3x) -SubTitle "Stuff I didn't want" -OnClick {
        Show-UDToast -Message 'Clicked'
    }
}

API

New-UDList

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Children

ScriptBlock

The items in the list.

false

SubHeader

String

Text to show within the sub header.

false

New-UDListItem

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

AvatarType

String

The type of avatar to show within the list item.

false

OnClick

Endpoint

A script block to execute when the list item is clicked.

false

Label

String

The label to show within the list item.

false

Children

ScriptBlock

Nested list items to show underneath this list item.

false

SubTitle

String

The subtitle to show within the list item.

false

Icon

Object

The icon to show within the list item.

false

Source

String

Parameter description

false

SecondaryAction

ScriptBlock

The secondary action to issue with this list item.

false

Table

Table component for Universal Dashboard

Tables display sets of data. They can be fully customized.

Tables display information in a way that’s easy to scan, so that users can look for patterns and insights. They can be embedded in primary content, such as cards.

Simple Table

A simple example with no frills. Table columns are defined from the data.

Table with Custom Columns

Define custom columns for your table.

Table with Custom Column Rendering

Define column rendering. Sorting and exporting still work for the table.

Table Column Width

Column width can be defined using the -Width parameter. You can also decide to truncate columns that extend past that width.

Filters

You can configure custom filters per column. The table supports text, select, fuzzy , slider, range, date , number, and autocomplete filters.

Table with server-side processing

Process data on the server so you can perform paging, filtering, sorting and searching in systems like SQL.

Paging

By default, paging is disable and tables will grow based on how many rows of data you provide. You can enable paging by using the -ShowPagination cmdlet (alias -Paging). You can configure the page size using the -PageSize cmdlet.

Disable Page Size All

By default, the page size selector provides an option to show all rows. If you want to prevent users from doing this, use the -DisablePageSizeAll cmdlet.

Sorting

To enable sorting for a table, use the -ShowSort parameter. When you enable sorting, you will be able to click the table headers to sort the table by clicking the headers. By default, multi-sort is enabled. To multi-hold shift and click a column header.

You can control which columns can be sorted by using New-UDTableColumn and -ShowSort parameter.

Disable Sort Remove

This documentation is for a feature that will be available in a future version of PowerShell Universal.

By default, the sorting of a table has 3 states. Unsorted, ascending and descending. If you would like to disable the unsorted state, use the -DisableSortRemove parameter of New-UDTable.

Selection

Tables support selection of rows. You can create an event handler for the OnRowSelected parameter to receive when a new row is selected or unselected or you can use Get-UDElement to retrieve the current set of selected rows.

The following example creates a table with row selection enabled. A toast is show when clicking the row or when clicking the GET Rows button.

The $EventData variable for the -OnRowSelected event will include all the columns as properties and a selected property as to whether the row was selected or unselected.

For example, the service table data would look like this.

Exporting

Tables support exporting the data within the table. You can export as CSV, XLSX, JSON or PDF. You can define which columns to include in an export and choose to export just the current page or all the data within the table.

Server-Side Exporting

You can control the export functionality with a PowerShell script block. This is useful when exporting from server-side sources like SQL server tables.

In this example, I have a SQL table that contains podcasts. When exporting, you will receive information about the current state of the table to allow you to customize what data is exported.

Customizing Export Options

You can decide which export options to present to your users using the -ExportOption cmdlet. The following example would only show the CSV export option.

Customizing Labels

You can use the -TextOption parameter along with the New-UDTableTextOption cmdlet to set text fields within the table.

Refresh with a button

You can externally refresh a table by putting the table within a dynamic region and using Sync-UDElement.

This example creates a button to refresh the table.

API

New-UDTable

Creates a new table.

New-UDTableColumn

Defines column properties for a table.

Out-UDTableData

Returns data from the -LoadData parameter of New-UDTable.

New-UDTableTextOption

Allows for custom text in the table controls.

Alert Types
Advanced Alerts
Basic Tree View
Dynamic Tree View

For a full example of server-side processing, .

$Data = @(
    @{Dessert = 'Frozen yoghurt'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Ice cream sandwich'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

New-UDTable -Data $Data
$Data = @(
    @{Dessert = 'Frozen yoghurt'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Ice cream sandwich'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

$Columns = @(
    New-UDTableColumn -Property Dessert -Title "A Dessert"
    New-UDTableColumn -Property Calories -Title Calories 
    New-UDTableColumn -Property Fat -Title Fat 
    New-UDTableColumn -Property Carbs -Title Carbs 
    New-UDTableColumn -Property Protein -Title Protein 
)

New-UDTable -Id 'customColumnsTable' -Data $Data -Columns $Columns
$Data = @(
    @{Dessert = 'Frozen yoghurt'; Calories = 1; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Ice cream sandwich'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 200; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

$Columns = @(
    New-UDTableColumn -Property Dessert -Title Dessert -Render { 
        New-UDButton -Id "btn$($EventData.Dessert)" -Text "Click for Dessert!" -OnClick { Show-UDToast -Message $EventData.Dessert } 
    }
    New-UDTableColumn -Property Calories -Title Calories 
    New-UDTableColumn -Property Fat -Title Fat 
    New-UDTableColumn -Property Carbs -Title Carbs 
    New-UDTableColumn -Property Protein -Title Protein 
)

New-UDTable -Data $Data -Columns $Columns -Sort -Export
$Data = @(
    @{Dessert = 'Frozen yoghurt'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Ice cream sandwich'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

$Columns = @(
    New-UDTableColumn -Property Dessert -Title Dessert -Render { 
        New-UDButton -Id "btn$($EventData.Dessert)" -Text "Click for Dessert!" -OnClick { Show-UDToast -Message $EventData.Dessert } 
    }
    New-UDTableColumn -Property Calories -Title Calories -Width 5 -Truncate
    New-UDTableColumn -Property Fat -Title Fat 
    New-UDTableColumn -Property Carbs -Title Carbs 
    New-UDTableColumn -Property Protein -Title Protein 
)

New-UDTable -Data $Data -Columns $Columns -Sort
$Data = @(
    @{Dessert = 'Frozen yoghurt'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Ice cream sandwich'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

$Columns = @(
    New-UDTableColumn -Property Dessert -Title "A Dessert" -Filter -FilterType AutoComplete
    New-UDTableColumn -Property Calories -Title Calories -Filter -FilterType Range
    New-UDTableColumn -Property Fat -Title Fat -Filter -FilterType Range
    New-UDTableColumn -Property Carbs -Title Carbs -Filter -FilterType Range
    New-UDTableColumn -Property Protein -Title Protein -Filter -FilterType Range
)

New-UDTable -Id 'customColumnsTable' -Data $Data -Columns $Columns -ShowFilter
$Columns = @(
    New-UDTableColumn -Property Dessert -Title "A Dessert"
    New-UDTableColumn -Property Calories -Title Calories 
    New-UDTableColumn -Property Fat -Title Fat 
    New-UDTableColumn -Property Carbs -Title Carbs 
    New-UDTableColumn -Property Protein -Title Protein 
)

New-UDTable -Columns $Columns -LoadData {
    $Query = $Body | ConvertFrom-Json

    <# Query will contain
        filters: []
        orderBy: undefined
        orderDirection: ""
        page: 0
        pageSize: 5
        properties: (5) ["dessert", "calories", "fat", "carbs", "protein"]
        search: ""
        totalCount: 0
    #>

    @(
        @{Dessert = 'Frozen yoghurt'; Calories = (Get-Random); Fat = 6.0; Carbs = 24; Protein = 4.0}
        @{Dessert = 'Ice cream sandwich'; Calories = (Get-Random); Fat = 6.0; Carbs = 24; Protein = 4.0}
        @{Dessert = 'Eclair'; Calories = (Get-Random); Fat = 6.0; Carbs = 24; Protein = 4.0}
        @{Dessert = 'Cupcake'; Calories = (Get-Random); Fat = 6.0; Carbs = 24; Protein = 4.0}
        @{Dessert = 'Gingerbread'; Calories = (Get-Random); Fat = 6.0; Carbs = 24; Protein = 4.0}
    ) | Out-UDTableData -Page 0 -TotalCount 5 -Properties $Query.Properties 
}
$Data = @(
    @{Dessert = 'Frozen yoghurt'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Ice cream sandwich'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

New-UDTable -Data $Data -Paging -PageSize 2
$Data = @(
    @{Dessert = 'Frozen yoghurt'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Ice cream sandwich'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

New-UDTable -Data $Data -ShowSort
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

$Columns = @(
    New-UDTableColumn -Property Dessert -Title "A Dessert" -ShowSort
    New-UDTableColumn -Property Calories -Title Calories 
    New-UDTableColumn -Property Fat -Title Fat 
    New-UDTableColumn -Property Carbs -Title Carbs -ShowSort
    New-UDTableColumn -Property Protein -Title Protein -ShowSort
)

New-UDTable -Id 'customColumnsTable' -Data $Data -Columns $Columns
$Data = @(
    @{Dessert = 'Frozen yoghurt'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Ice cream sandwich'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

New-UDTable -Data $Data -ShowSort -DisableSortRemove
$Data = try { get-service -ea Stop | select Name,@{n = "Status";e={ $_.Status.ToString()}},@{n = "StartupType";e={ $_.StartupType.ToString()}},@{n = "StartType";e={ $_.StartType.ToString()}} } catch {}
$Columns = @(
    New-UDTableColumn -Property Name -Title "Service Name" -ShowSort -IncludeInExport -IncludeInSearch -ShowFilter -FilterType text
    New-UDTableColumn -Property Status -Title Status -ShowSort -DefaultSortColumn -IncludeInExport -IncludeInSearch -ShowFilter -FilterType select 
    New-UDTableColumn -Property StartupType -Title StartupType -IncludeInExport -ShowFilter -FilterType select
    New-UDTableColumn -Property StartType -Title StartType -IncludeInExport -ShowFilter -FilterType select 
)
New-UDTable -Id 'service_table' -Data $Data -Columns $Columns -Title 'Services' -ShowSearch -ShowPagination -ShowSelection -Dense -OnRowSelection {
    $Item = $EventData
    Show-UDToast -Message "$($Item | out-string)"
}
New-UDButton -Text "GET Rows" -OnClick {
    $value = Get-UDElement -Id "service_table"
    Show-UDToast -Message "$( $value.selectedRows | Out-String )"
}
@{
   Id = 0
   Name = 'AESMService',
   Status = 'Running'
   StartupType = 'AutomaticDelayedStart'
   StartType = 'Automation'
   selected = $true
}
$Data = try { get-service -ea Stop | select Name,@{n = "Status";e={ $_.Status.ToString()}},@{n = "StartupType";e={ $_.StartupType.ToString()}},@{n = "StartType";e={ $_.StartType.ToString()}} } catch {}
$Columns = @(
    New-UDTableColumn -Property Name -Title "Service Name" -IncludeInExport
    New-UDTableColumn -Property Status -Title Status 
    New-UDTableColumn -Property StartupType
    New-UDTableColumn -Property StartType -IncludeInExport
)
New-UDTable -Id 'service_table' -Data $Data -Columns $Columns -Title 'Services' -ShowSearch -ShowPagination -Dense -Export
New-UDDashboard -Title "Hello, World!" -Content {
    New-UDTable -Title 'Shows' -LoadData {
        $TableData = ConvertFrom-Json $Body

        $OrderBy = $TableData.orderBy.field
        if ($OrderBy -eq $null)
        {
            $OrderBy = "name"
        }

        $OrderDirection = $TableData.OrderDirection
        if ($OrderDirection -eq $null)
        {
            $OrderDirection = 'asc'
        }

        $Where = ""
        if ($TableData.Filters) 
        {
            $Where = "WHERE "

            foreach($filter in $TableData.Filters)
            {
                $Where += $filter.column.field + " LIKE '%" + $filter.value + "%' AND "
            }

            $Where += " 1 = 1"
        }

        $PageSize = $TableData.PageSize 
        # Calculate the number of rows to skip
        $Offset = $TableData.Page * $PageSize
        $Count = Invoke-DbaQuery -SqlInstance localhost\MSSQLSERVER -Database 'podcasts' -Query "SELECT COUNT(*) as count FROM shows $Where"

        $Data = Invoke-DbaQuery -SqlInstance localhost\MSSQLSERVER -Database 'podcasts' -Query "SELECT * FROM shows $Where ORDER BY $orderBy $orderdirection OFFSET $Offset ROWS FETCH NEXT $PageSize ROWS ONLY" | ForEach-Object {
            @{ 
                name = $_.name 
                host = $_.host
            }
        } 
        $Data | Out-UDTableData -Page $TableData.page -TotalCount $Count.Count -Properties $TableData.properties
    } -Columns @(
        New-UDTableColumn -Property 'name' -Sort -Filter -Export
        New-UDTableColumn -Property 'host' -Sort -Filter -Export
    ) -Sort -Filter -Export -OnExport {
        $Query = $Body | ConvertFrom-Json

        <# Query will contain
            filters: []
            orderBy: undefined
            orderDirection: ""
            page: 0
            pageSize: 5
            properties: (5) ["dessert", "calories", "fat", "carbs", "protein"]
            search: ""
            totalCount: 0
            allRows: true
        #>

        Invoke-DbaQuery -SqlInstance localhost\MSSQLSERVER -Database 'podcasts' -Query "SELECT * FROM shows" | ForEach-Object {
            @{ 
                name = $_.name 
                host = $_.host
            }
        } 
    }
}
$Data = try { get-service -ea Stop | select Name,@{n = "Status";e={ $_.Status.ToString()}},@{n = "StartupType";e={ $_.StartupType.ToString()}},@{n = "StartType";e={ $_.StartType.ToString()}} } catch {}
$Columns = @(
    New-UDTableColumn -Property Name -Title "Service Name" -IncludeInExport
    New-UDTableColumn -Property Status -Title Status 
    New-UDTableColumn -Property StartupType
    New-UDTableColumn -Property StartType -IncludeInExport
)
New-UDTable -Id 'service_table' -Data $Data -Columns $Columns -Title 'Services' -ShowSearch -ShowPagination -Dense -Export -ExportOption "csv"
$Data = @(
    @{Dessert = 'Frozen yoghurt'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Ice cream sandwich'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Eclair'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Cupcake'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
    @{Dessert = 'Gingerbread'; Calories = 159; Fat = 6.0; Carbs = 24; Protein = 4.0}
) 

$Option = New-UDTableTextOption -Search "Search all these records"

New-UDTable -Data $Data -TextOption $Option -ShowSearch
New-UDDynamic -Id 'table' -Content {
    $Data = Get-Service
    New-UDTable -Data $Data -Paging
} -LoadingComponent {
    "Loading"
}

New-UDButton -Text 'Refresh Table' -OnClick {
    Sync-UDElement -Id 'table'
}

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Title

String

The title to show at the top of the table's card.

false

Data

Object[]

The data to put into the table.

true

LoadData

Endpoint

When using dynamic tables, this script block is called. The $Body parameter will contain a hashtable the following options: filters: @() orderBy: string orderDirection: string page: int pageSize: int properties: @() search: string totalCount: int You can use these values to perform server-side processing, like SQL queries, to improve the performance of large grids. After processing the data with these values, output the data via Out-UDTableData.

true

Columns

Hashtable[]

Defines the columns to show within the table. Use New-UDTableColumn to define these columns. If this parameter isn't specified, the properties of the data that you pass in will become the columns.

false

Sort

SwitchParameter

Whether sorting is enabled in the table.

false

Filter

SwitchParameter

Whether filtering is enabled in the table.

false

Search

SwitchParameter

Whether search is enabled in the table.

false

Export

SwitchParameter

Whether exporting is enabled within the table.

false

Paging

SwitchParameter

Whether to enable paging.

false

PageSize

int

Number of items to show in a page by default. Defaults to 5.

false

PageSizeOptions

int[]

Page size options to show in the selector. Defaults to @(5, 10, 20)

false

Dense

SwitchParameter

Enables dense padding.

false

DefaultSortDirection

string

Sets the default sort direction for the table.

false

HideToggleAllRowsSelected

SwitchParameter

Disables the toggle all rows when using selection

false

DisableMultiSelect

SwitchParameter

Disables multiple selections

false

DisablePageSizeAll

SwitchParameter

Disables the ability to show all records in a paged table.

false

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Property

String

The property to select from the data for this column

true

Title

String

The title to display at the top of the column. Property name is used if not specified.

false

Render

ScriptBlock

A script block that is called when rendering this column. The $_ variable will contain the current row. Return any control from this scriptblock.

false

ShowSort

Switch

Include this column in sorting.

false

ShowFilter

Switch

Include a filter for this column.

false

FilterType

string

The type of filter to display. text, select, fuzzy, slider, range, date, number, autocomplete

false

Style

Hashtable

A CSS style applied to the column

false

Width

int

The width of the column in pixels

false

IncludeInSearch

Switch

Whether to include this column when searching.

false

IncludeInExport

Switch

Whether to include this column when exporting.

false

DefaultSortColumn

Switch

This column defines the default sorting when the table is loaded.

false

Align

string

The alignment of the data in the table.

false

Truncate

Switch

Whether to truncate the text in the column if it is longer than -Width

false

SortType

string

How to sort the data within the column

false

Name

Type

Description

Required

Data

object

The data to display in the table

true

Page

int

The current page.

true

TotalCount

int

The total count of rows in the entire data set. This is not just what is passed to data.

true

Properties

string[]

Properties included in the data. Use $EventData.Properties.

true

Name

Type

Description

Required

ExportAllCsv

string

Export all as CSV text

false

ExportCurrentViewCsv

string

Export Current View as CSV text

false

ExportAllXLSX

string

Export all as XLSX text

false

ExportCurrentViewXLSX

string

Export Current View as XLSX text

false

ExportAllPDF

string

Export all as PDF text

false

ExportCurrentViewPDF

string

Export Current View as PDF text

false

ExportAllJson

string

Export all as JSON text

false

ExportCurrentViewJson

string

Export Current View as JSON text

false

ExportFileName

string

File Name text

false

Search

string

Search {0} records... text

false

FilterSearch

string

Search {0} records... text

false

Autocomplete

Autocomplete component for Universal Dashboard

The autocomplete is a normal text input enhanced by a panel of suggested options.

Autocomplete with a static list of options

New-UDAutocomplete -Options @('Test', 'Test2', 'Test3', 'Test4')

Autocomplete with a dynamic list of options

New-UDAutocomplete -OnLoadOptions { 
    @('Test', 'Test2', 'Test3', 'Test4') | Where-Object { $_ -match $Body } | ConvertTo-Json
}

Autocomplete with an OnChange script block

New-UDAutocomplete -OnLoadOptions { 
    @('Test', 'Test2', 'Test3', 'Test4') | Where-Object { $_ -match $Body } | ConvertTo-Json
} -OnChange {
    Show-UDToast $Body 
}
see this blog post

Skeleton

A skeleton component for PowerShell Universal Dashboard.

A skeleton is a form of a loading component that can show a placeholder while data is received.

Variants

There are three variants that you can use for a skeleton. You can use a circle, text or a rectangle. You can also define the height and width of the skeleton.

New-UDSkeleton
New-UDSkeleton -Variant circle -Width 40 -Height 40
New-UDSkeleton -Variant rect -Width 210 -Height 118

Animations

Skeletons will use the pulsate animation by default. You can also disable animation or use a wave animation.

New-UDSkeleton
New-UDSkeleton -Animation disabled
New-UDSkeleton -Animation wave

Progress

Progress component for Universal Dashboard

Circular Progress

New-UDProgress -Circular -Color Blue

Linear Indeterminate

New-UDProgress

Linear Determinate

New-UDProgress -PercentComplete 75

New-UDProgress

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

PercentComplete

Object

The percent complete for the progress.

false

BackgroundColor

DashboardColor

The background color.

false

ProgressColor

DashboardColor

The progress bar color.

false

Circular

SwitchParameter

Whether the progress is circular.

false

Color

String

The color of the progress.

false

Size

String

The size of the progress.

false

Map

Map component for Universal Dashboard.

To use maps within your dashboard, you will need to add the UniversalDashboard.Map component.

The UDMap component is a robust control that provides a huge set of features. You can select base layers, configure togglable layers, set markers, define vectors and interact with other Universal Dashboard components.

Basic Map

This basic map defines a simple base layer using the wmflabs.org tile server. You can use your own custom tile server by specifying a URL. The map is position over Hailey, Idaho.

New-UDMap -Endpoint {
    New-UDMapRasterLayer -TileServer 'https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png' 
} -Latitude 43.52107 -Longitude -114.31644 -Zoom 13 -Height '100vh'

Layer Control

You can enable the layer control by using the New-UDMapLayerControl cmdlet. This map defines several layers with components that you can toggle on and off. You can only have one base layer selected as a time. Map overlay layers can toggle on and off.

New-UDMap -Endpoint {
    New-UDMapLayerControl -Content {
        New-UDMapBaseLayer -Name 'Black and White' -Content {
            New-UDMapRasterLayer -TileServer 'https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png' 
        } -Checked
        New-UDMapBaseLayer -Name 'Color' -Content {
            New-UDMapRasterLayer -TileServer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' 
        }
        New-UDMapOverlay -Name 'Marker' -Content {
            New-UDMapMarker -Latitude 51.505 -Longitude -0.09 
        } -Checked
        New-UDMapOverlay -Name 'Marker 2' -Content {
            New-UDMapMarker -Latitude 51.555 -Longitude -0.00 
        } -Checked
    }
} -Latitude 51.505 -Longitude -0.09 -Zoom 13 -Height '100vh'

Heatmaps

Heatmaps can be defined by creating a heatmap layer. The intesity and location of the heatmap clusters can be defined by using the New-UDMapHeatmapLayer cmdlet.

New-UDMap -Endpoint {
    New-UDMapRasterLayer -TileServer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' 
    New-UDMapHeatmapLayer -Points @(
        @(-37.9019339833, 175.3879181167, "625"),
        @(-37.90920365, 175.4053418167, "397"),
        @(-37.9057407667, 175.39478875, "540"),
        @(-37.9243174333, 175.4220341833, "112"),
        @(-37.8992012333, 175.3666729333, "815"),
        @(-37.9110874833, 175.4102195833, "360"),
        @(-37.9027096, 175.3913196333, "591"),
        @(-37.9011183833, 175.38410915, "655"),
        @(-37.9234701333, 175.4155696333, "181"),
        @(-37.90254175, 175.3926162167, "582"),
        @(-37.92450575, 175.4246711167, "90"),
        @(-37.9242924167, 175.4289432833, "47"),
        @(-37.8986079833, 175.3685293333, "801")
    )
} -Height '100vh'

Marker Clusters

Marker clusters group together markers that are close to each other. As you zoom in or out, the clusters will either combine or explode.

New-UDMap -Endpoint {
    New-UDMapRasterLayer -TileServer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' 
    New-UDMapMarkerClusterLayer -Id 'cluster-layer' -Markers @(
        1..100 | ForEach-Object {
            $Random = Get-Random -Minimum 0 -Maximum 100
            $RandomLat = $Random + 400
            New-UDMapMarker -Latitude "51.$RandomLat" -Longitude "-0.$Random"
        }
    )
} -Latitude 51.505 -Longitude -0.09 -Zoom 13 -Height '100vh'

Interactive Maps

Maps provide a series of interactive capabilities for add components to and manipulating the map.

New-UDButton -Text 'Add Circle' -OnClick {
    Add-UDElement -ParentId 'Feature-Group' -Content {
        New-UDMapVectorLayer -Id 'Vectors' -Circle -Latitude 51.505 -Longitude -0.09 -Radius 500 -Color blue -FillColor blue -FillOpacity .5 
    }
}

New-UDButton -Text 'Remove Circle' -OnClick {
    Remove-UDElement -Id 'Vectors' 
}

New-UDButton -Text 'Add Marker' -OnClick {
    Add-UDElement -ParentId 'Feature-Group' -Content {
        New-UDMapMarker -Id 'marker' -Latitude 51.505 -Longitude -0.09 -Popup (
            New-UDMapPopup -Content {
                New-UDCard -Title "Test"
            } -MaxWidth 600
        ) 
    }
}

New-UDButton -Text 'Remove Marker' -OnClick {
    Remove-UDElement -Id 'marker' 
}

New-UDButton -Text 'Add Layer' -OnClick {
    Add-UDElement -ParentId 'layercontrol' -Content {
        New-UDMapOverlay -Id 'MyNewLayer' -Name "MyNewLayer" -Content {
            New-UDMapFeatureGroup -Id 'Feature-Group2' -Content {
                1..100 | % {
                    New-UDMapVectorLayer -Id 'test' -Circle -Latitude "51.$_" -Longitude -0.09 -Radius 50 -Color red -FillColor blue -FillOpacity .5        
                }
            }
        } -Checked

    }
}

New-UDButton -Text 'Remove Layer' -OnClick {
    Remove-UDElement -Id 'MyNewLayer' 
}

New-UDButton -Text 'Move' -OnClick {
    Set-UDElement -Id 'map' -Attributes @{
        latitude = 51.550
        longitude = -0.09
        zoom = 10
    }
}

New-UDButton -Text "Add marker to cluster" -OnClick {
    Add-UDElement -ParentId 'cluster-layer' -Content {
        $Random = Get-Random -Minimum 0 -Maximum 100
        $RandomLat = $Random + 400
        New-UDMapMarker -Latitude "51.$RandomLat" -Longitude "-0.$Random"
    }
}

New-UDButton -Text "Add points to heatmap" -OnClick {
    Add-UDElement -ParentId 'heatmap' -Content {
        @(
            @(51.505, -0.09, "625"),
            @(51.505234, -0.0945654, "625"),
            @(51.50645, -0.098768, "625"),
            @(51.5056575, -0.0945654, "625"),
            @(51.505955, -0.095675, "625"),
            @(51.505575, -0.09657, "625"),
            @(51.505345, -0.099876, "625"),
            @(51.505768, -0.0923432, "625"),
            @(51.505567, -0.02349, "625"),
            @(51.50545654, -0.092342, "625"),
            @(51.5045645, -0.09342, "625")
        )
    }
}

New-UDButton -Text "Clear heatmap" -OnClick {
    Clear-UDElement -Id 'heatmap'
}

New-UDMap -Id 'map' -Endpoint {
    New-UDMapLayerControl -Id 'layercontrol' -Content {
        New-UDMapBaseLayer -Name "Black and White" -Content {
            New-UDMapRasterLayer -TileServer 'https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png' 
        } 

        New-UDMapBaseLayer -Name "Mapnik" -Content {
            New-UDMapRasterLayer -TileServer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' 
        } 

        New-UDMapBaseLayer -Name "Bing" -Content {
            New-UDMapRasterLayer -Bing -ApiKey 'asdf3rwf34afaw-sdfasdfa23feaw-23424dfsdfa' -Type Road
        } -Checked

        New-UDMapOverlay -Name "Markers" -Content {
            New-UDMapFeatureGroup -Id 'Feature-Group' -Content {
                New-UDMapMarker -Id 'marker' -Latitude 51.505 -Longitude -0.09
            } -Popup (
                New-UDMapPopup -Content {
                    New-UDCard -Title "Test123"
                } -MaxWidth 600
            )
        } -Checked

        New-UDMapOverlay -Name 'Vectors' -Content {
            New-UDMapFeatureGroup -Id 'Vectors' -Content {

            }
        } -Checked

        New-UDMapOverlay -Name "Heatmap" -Content {
            New-UDMapHeatmapLayer -Id 'heatmap' -Points @() 
        } -Checked 

        New-UDMapOverlay -Name "Cluster" -Content {
            New-UDMapMarkerClusterLayer -Id 'cluster-layer' -Markers @(
                1..100 | ForEach-Object {
                    $Random = Get-Random -Minimum 0 -Maximum 100
                    $RandomLat = $Random + 400
                    New-UDMapMarker -Latitude "51.$RandomLat" -Longitude "-0.$Random"
                }
            )
        } -Checked

    }

} -Latitude 51.505 -Longitude -0.09 -Zoom 13 -Height '100vh' -Animate

Charts

Charting components for Universal Dashboard.

Universal Dashboard provides several built-in charting solutions to help visualize your data retrieved from PowerShell.

To use charts within your dashboard, you will need to add the UniversalDashboard.Charts component.

ChartJS

Creating a Chart

To create a chart, use New-UDChartJS and New-UDChartJSData. The below chart shows the top ten CPU using processes.

 $Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 
 New-UDChartJS -Type 'bar' -Data $Data -DataProperty CPU -LabelProperty ProcessName

Types

Bar

 $Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 
 New-UDChartJS -Type 'bar' -Data $Data -DataProperty CPU -LabelProperty ProcessName

Stacked Bar

    $GraphPrep = @(
        @{ RAM = "Server1"; AvailableRam = 128; UsedRAM = 10 }
        @{ RAM = "Server2"; AvailableRam = 64; UsedRAM = 63 }
        @{ RAM = "Server3"; AvailableRam = 48; UsedRAM = 40 }
        @{ RAM = "Server4"; AvailableRam = 64;; UsedRAM = 26 }
        @{ RAM = "Server5"; AvailableRam = 128; UsedRAM = 120 }
    )

    $AvailableRamDataSet = New-UDChartJSDataset -DataProperty AvailableRAM -Label 'Available' -BackgroundColor blue
    $UsedRamDataset = New-UDChartJSDataset -DataProperty UsedRAM -Label 'Used' -BackgroundColor red
    $Options = @{
        Type          = 'bar'
        Data          = $GraphPrep
        Dataset       = @($AvailableRamDataSet, $UsedRamDataset)
        LabelProperty = "RAM"
        Options = @{
            scales = @{
                xAxes = @(
                @{
                    stacked = $true
                }
            )
            yAxes = @(
                @{
                    stacked = $true
                }
            )
            }
        }
    } 

    New-UDChartJS @Options

Horizontal Bar

 $Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 
 New-UDChartJS -Type 'horizontalBar' -Data $Data -DataProperty CPU -LabelProperty ProcessName

Line

 $Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 
 New-UDChartJS -Type 'line' -Data $Data -DataProperty CPU -LabelProperty ProcessName

Doughnut

 $Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 
 New-UDChartJS -Type 'doughnut' -Data $Data -DataProperty CPU -LabelProperty ProcessName

Pie

 $Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 
 New-UDChartJS -Type 'pie' -Data $Data -DataProperty CPU -LabelProperty ProcessName

Radar

 $Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 
 New-UDChartJS -Type 'radar' -Data $Data -DataProperty CPU -LabelProperty ProcessName

Colors

Colors can be defined using the various color parameters of New-UDChartJS.

 $Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 

 $Options = @{
   Type = 'bar'
   Data = $Data
   BackgroundColor = 'Red'
   BorderColor = '#c61d4a'
   HoverBackgroundColor = 'Blue'
   HoverBorderColor = '#451dc6'
   DataProperty = 'CPU'
   LabelProperty = 'ProcessName'
 }

 New-UDChartJS @Options

Data Sets

By default, you do not need to define data sets manually. A single data set is created automatically when you use the -DataProperty and -LabelProperty parameters. If you want to define multiple data sets for a single chart, you can use the -Dataset property in conjunction with New-UDChartJSDataset.

$Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 

 $CPUDataset = New-UDChartJSDataset -DataProperty CPU -Label CPU -BackgroundColor '#126f8c'
 $MemoryDataset = New-UDChartJSDataset -DataProperty HandleCount -Label 'Handle Count' -BackgroundColor '#8da322'

 $Options = @{
   Type = 'bar'
   Data = $Data
   Dataset = @($CPUDataset, $MemoryDataset)
   LabelProperty = "ProcessName"
 }

 New-UDChartJS @Options

Click Events

You can take action when a user clicks the chart. This example shows a toast with the contents of the $Body variable. The $Body variable contains a JSON string with information about the elements that were clicked.

 $Data = Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 

  $Options = @{
   Type = 'bar'
   Data = $Data
   DataProperty = 'CPU'
   LabelProperty = "ProcessName"
   OnClick = { 
      Show-UDToast -Message $Body
   }
 }


 New-UDChartJS @Options

Auto refreshing charts

You can use New-UDDynamic to create charts that refresh on an interval.

New-UDDynamic -Content {
    $Data = 1..10 | % { 
        [PSCustomObject]@{ Name = $_; value = get-random }
    }
    New-UDChartJS -Type 'bar' -Data $Data -DataProperty Value -Id 'test' -LabelProperty Name -BackgroundColor Blue
} -AutoRefresh -AutoRefreshInterval 1

Monitors

Monitors are a special kind of chart that tracks data over time. Monitors are good for displaying data such as server performance stats that change frequently. You return a single value from a monitor and it is graphed automatically over time.

New-UDChartJSMonitor -LoadData {
    Get-Random -Max 100 | Out-UDChartJSMonitorData
} -Labels "Random" -ChartBackgroundColor "#297741" -RefreshInterval 1

Nivo Charts

Creating a Chart

All the Nivo charts can be created with New-UDNivoChart. You will specify a switch parameter for the different types of charts. Each chart type will take a well defined data format via the -Data parameter.

$Data = 1..10 | ForEach-Object { 
    $item = Get-Random -Max 1000 
    [PSCustomObject]@{
        Name = "Test$item"
        Value = $item
    }
}
New-UDNivoChart -Id 'autoRefreshingNivoBar' -Bar -Keys "value" -IndexBy 'name' -Data $Data -Height 500 -Width 1000

Patterns

Nivo provides the ability to specify patterns to display over data sets. You can configure these patterns with New-UDNivoPattern and New-UDNivoFill .

$Data = @(
    @{
        country = 'USA'
        burgers = (Get-Random -Minimum 10 -Maximum 100)
        fries = (Get-Random -Minimum 10 -Maximum 100)
        sandwich = (Get-Random -Minimum 10 -Maximum 100)
    }
    @{
        country = 'Germany'
        burgers = (Get-Random -Minimum 10 -Maximum 100)
        fries = (Get-Random -Minimum 10 -Maximum 100)
        sandwich = (Get-Random -Minimum 10 -Maximum 100)
    }
    @{
        country = 'Japan'
        burgers = (Get-Random -Minimum 10 -Maximum 100)
        fries = (Get-Random -Minimum 10 -Maximum 100)
        sandwich = (Get-Random -Minimum 10 -Maximum 100)
    }
)

$Pattern = New-UDNivoPattern -Dots -Id 'dots' -Background "inherit" -Color "#38bcb2" -Size 4 -Padding 1 -Stagger
$Fill = New-UDNivoFill -ElementId "fries" -PatternId 'dots'

New-UDNivoChart -Definitions $Pattern -Fill $Fill -Bar -Data $Data -Height 400 -Width 900 -Keys @('burgers', 'fries', 'sandwich')  -IndexBy 'country'

Responsive Widths

Nivo charts provide responsive widths so they will resize automatically when placed on a page or the browser is resized. A height is required when using responsive widths.

Auto Refreshing Charts

Like many components in Universal Dashboard v3, Nivo charts do not define auto-refresh properties themselves. Instead, you can take advantage of New-UDDynamic to refresh the chart on an interval.

New-UDDynamic -Content {
    $Data = 1..10 | ForEach-Object { 
        $item = Get-Random -Max 1000 
        [PSCustomObject]@{
            Name = "Test$item"
            Value = $item
        }
    }
    New-UDNivoChart -Id 'autoRefreshingNivoBar' -Bar -Keys "Value" -IndexBy 'name' -Data $Data -Height 500 -Width 1000
} -AutoRefresh

OnClick

Nivo charts support OnClick event handlers. You will be provided with information about the data set that was clicked as JSON.

$Data = @(
    @{
        country = 'USA'
        burgers = (Get-Random -Minimum 10 -Maximum 100)
        fries = (Get-Random -Minimum 10 -Maximum 100)
        sandwich = (Get-Random -Minimum 10 -Maximum 100)
    }
    @{
        country = 'Germany'
        burgers = (Get-Random -Minimum 10 -Maximum 100)
        fries = (Get-Random -Minimum 10 -Maximum 100)
        sandwich = (Get-Random -Minimum 10 -Maximum 100)
    }
    @{
        country = 'Japan'
        burgers = (Get-Random -Minimum 10 -Maximum 100)
        fries = (Get-Random -Minimum 10 -Maximum 100)
        sandwich = (Get-Random -Minimum 10 -Maximum 100)
    }
)
New-UDNivoChart -Bar -Data $Data -Height 400 -Width 900 -Keys @('burgers', 'fries', 'sandwich')  -IndexBy 'country' -OnClick {
    Show-UDToast -Message $EventData -Position topLeft
}

Types of Charts

Bar

New-Example -Title 'Bar' -Description '' -Example {
    $Data = 1..10 | ForEach-Object { 
        $item = Get-Random -Max 1000 
        [PSCustomObject]@{
            Name = "Test$item"
            Value = $item
        }
    }
    New-UDNivoChart -Bar -Keys "Value" -IndexBy 'name' -Data $Data -Height 500 -Width 1000
}

Bubble

$TreeData = @{
    Name     = "root"
    children = @(
        @{
            Name  = "first"
            children = @(
                @{
                    Name = "first-first"
                    Count = 7
                }
                @{
                    Name = "first-second"
                    Count = 8
                }
            )
        },
        @{
            Name  = "second"
            Count = 21
        }
    )
}

New-UDNivoChart -Bubble -Data $TreeData -Value "count" -Identity "name" -Height 500 -Width 800

Calendar

$Data = @()
for($i = 365; $i -gt 0; $i--) {
    $Data += @{
        day = (Get-Date).AddDays($i * -1).ToString("yyyy-MM-dd")
        value = Get-Random
    }
}

$From = (Get-Date).AddDays(-365)
$To = Get-Date

New-UDNivoChart -Calendar -Data $Data -From $From -To $To -Height 500 -Width 1000 -MarginTop 50 -MarginRight 130 -MarginBottom 50 -MarginLeft 60

Heatmap

$Data = @(
    @{
        state = "idaho"
        cats = 72307
        dogs = 23429
        moose = 23423
        bears = 784
    }
    @{
        state = "wisconsin"
        cats = 2343342
        dogs = 3453623
        moose = 1
        bears = 23423
    }
    @{
        state = "montana"
        cats = 9234
        dogs = 3973457
        moose = 23472
        bears = 347303
    }
    @{
        state = "colorado"
        cats = 345973789
        dogs = 0237234
        moose = 2302
        bears = 2349772
    }
)
New-UDNivoChart -Heatmap -Data $Data -IndexBy 'state' -keys @('cats', 'dogs', 'moose', 'bears')  -Height 500 -Width 1000 -MarginTop 50 -MarginRight 130 -MarginBottom 50 -MarginLeft 60

Line

[array]$Data = [PSCustomObject]@{
    id = "DataSet"
    data = (1..20 | ForEach-Object {
        $item = Get-Random -Max 500 
        [PSCustomObject]@{
            x = "Test$item"
            y = $item
        }
    })
}
New-UDNivoChart -Line -Data $Data -Height 500 -Width 1000 -LineWidth 1

Stream

$Data = 1..10 | ForEach-Object { 
    @{
        "Adam" = Get-Random 
        "Alon" = Get-Random 
        "Lee" = Get-Random 
        "Frank" = Get-Random 
        "Bill" = Get-Random 
    }
}

New-UDNivoChart -Stream -Data $Data -Height 500 -Width 1000 -Keys @("adam", "alon", "lee", "frank", "bill")

Treemap

$TreeData = @{
    Name     = "root"
    children = @(
        @{
            Name  = "first"
            children = @(
                @{
                    Name = "first-first"
                    Count = 7
                }
                @{
                    Name = "first-second"
                    Count = 8
                }
            )
        },
        @{
            Name  = "second"
            Count = 21
        }
    )
}

New-UDNivoChart -Treemap -Data $TreeData -Value "count" -Identity "name" -Height 500 -Width 800

Modal

Modal component for Universal Dashboard.

Modals inform users about a task and can contain critical information, require decisions, or involve multiple tasks.

Basic

New-UDButton -Text 'Basic' -OnClick {
    Show-UDModal -Content {
        New-UDTypography -Text "Hello"
    }
}

Full Screen

New-UDButton -Text 'Full Screen' -OnClick {
    Show-UDModal -Content {
        New-UDTypography -Text "Hello"
    } -Footer {
        New-UDButton -Text "Close" -OnClick { Hide-UDModal }
    }  -FullScreen
}

Full Width

Full width modals take up the full width as defined by the -MaxWidth parameter.

New-UDButton -Text 'Full Width' -OnClick {
    Show-UDModal -Content {
        New-UDTypography -Text "Hello"
    } -FullWidth -MaxWidth 'md'
}

Persistent

Persistent modals do not close when you click off of them. You will have to close it with Hide-UDModal.

New-UDButton -Text 'Persistent' -OnClick {
    Show-UDModal -Content {
        New-UDTypography -Text "Hello"
    } -Footer {
        New-UDButton -Text "Close" -OnClick { Hide-UDModal }
    } -Persistent
}

Hide a Modal

You can use the Hide-UDModal button to hide a modal that is currently show.

New-UDButton -Text 'Basic' -OnClick {
    Show-UDModal -Content {
        New-UDTypography -Text "Hello"
    }
    Start-Sleep 5
    Hide-UDModal
}

Show-UDModal

Name

Type

Description

Required

FullScreen

switch

Creates a full screen modal

false

Footer

ScriptBlock

Sets the footer content for the modal.

false

Header

ScriptBlock

Sets the header content for the modal.

false

Content

ScriptBlock

Sets the main body content for the modal.

false

Persistent

switch

Creates a persistent modal.

false

FullWidth

switch

Creates a full width modal.

false

MaxWidth

string

Defines the max width of a full width modal.

false

Checkbox

Check component for Universal Dashboard

Checkboxes allow the user to select one or more items from a set.

Checkboxes

Checkboxes can be disabled and checked by default

Checkboxes with custom icon

Create checkboxes that use any icon and style.

Checkboxes with onChange script block

Create checkboxes that fire script blocks when changed.

Checkbox with custom label placement

You can adjust where the label for the checkbox is placed.

Get the value of a Checkbox

You can use Get-UDElement to get the value of the checkbox. Get-UDElement will also return other properties of the checkbox component.

The following example shows a toast message with the value of the checkbox.

New-UDCheckbox

Floating Action Button

Floating action button component for Universal Dashboard

A floating action button (FAB) performs the primary, or most common, action on a screen.

A floating action button appears in front of all screen content, typically as a circular shape with an icon in its center. FABs come in two types: regular, and extended.

Only use a FAB if it is the most suitable way to present a screen’s primary action.

Only one floating action button is recommended per screen to represent the most common action.

Floating Action Button

OnClick

New-UDFloatingActionButton

Button

Button component for Universal Dashboard

Buttons allow users to take actions, and make choices, with a single tap.

Contained Button

Contained buttons are high-emphasis, distinguished by their use of elevation and fill. They contain actions that are primary to your app.

Outlined Button

Outlined buttons are medium-emphasis buttons. They contain actions that are important, but aren’t the primary action in an app.

Control Button Size

You can control the pixel size of a button based on pixel size by using the Style parameter

'''text New-UDButton -Id "Submit" -Text "Submit" -Style @{ Width = "150px" Height = "100px" }

Buttons with icons and label

Sometimes you might want to have icons for certain button to enhance the UX of the application as we recognize logos more easily than plain text. For example, if you have a delete button you can label it with a dustbin icon.

Buttons with event handlers

You can specify a script block to execute when the button is clicked

New-UDButton

Row selection
Skeletons
Animations

Universal Dashboard integrates with .

Universal Dashboard integrates with . Below you will find examples and documentation for using these charts.

ChartJS
Nivo Charts
Learn more about adding custom component libraries
Learn more about adding custom component libraries
New-UDCheckBox
New-UDCheckBox -Disabled
New-UDCheckBox -Checked $true
New-UDCheckBox -Checked $true -Disabled
$Icon = New-UDIcon -Icon angry -Size lg -Regular
$CheckedIcon = New-UDIcon -Icon angry -Size lg
New-UDCheckBox -Icon $Icon -CheckedIcon $CheckedIcon -Style @{color = '#2196f3'}
New-UDCheckBox -OnChange {
    Show-UDToast -Title 'Checkbox' -Message $Body
}
New-UDCheckBox -Label 'Demo' -LabelPlacement start
New-UDCheckBox -Label 'Demo' -LabelPlacement top
New-UDCheckBox -Label 'Demo' -LabelPlacement bottom
New-UDCheckBox -Label 'Demo' -LabelPlacement end
New-UDCheckbox -Id 'MyCheckbox' 

New-UDButton -Text 'Get Value' -OnClick {
    Show-UDToast -Message (Get-UDElement -Id 'MyCheckbox').checked
}

Name

Type

Description

Required

Label

String

The label to show next to the checkbox.

false

Icon

Object

The icon to show instead of the default icon.

false

CheckedIcon

Object

The icon to show instead of the default checked icon.

false

OnChange

Endpoint

Called when the value of the checkbox changes. The $EventData variable will have the current value of the checkbox.

false

Style

Hashtable

A hashtable of styles to apply to the checkbox.

false

Disabled

SwitchParameter

Whether the checkbox is disabled.

false

Checked

Boolean

Whether the checkbox is checked.

false

ClassName

String

A CSS class to assign to the checkbox.

false

LabelPlacement

String

Where to place the label.

false

Id

String

The ID of the component. It defaults to a random GUID.

false

New-UDFloatingActionButton -Icon (New-UDIcon -Icon user) -Size Small
New-UDFloatingActionButton -Icon (New-UDIcon -Icon user) -Size Medium
New-UDFloatingActionButton -Icon (New-UDIcon -Icon user) -Size Large
New-UDFloatingActionButton -Icon (New-UDIcon -Icon user) -OnClick {
    Show-UDToast -Message "Hello!"
}

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Icon

Object

The icon to put within the floating action button.

false

Size

Object

The size of the button.

false

OnClick

Object

A script block to execute when the floating action button is clicked.

false

 New-UDButton -Variant 'contained' -Text 'Default'
New-UDButton -Variant 'outlined' -Text 'Default'
New-UDButton -Icon (New-UDIcon -Icon trash) -Text 'Delete'
New-UDButton -Text 'Message Box' -OnClick {
    Show-UDToast -Message 'Hello, world!'
}

Name

Type

Description

Required

Text

String

The text to show within the button.

false

Icon

Object

An icon to show within the button. Use New-UDIcon to create an icon for this parameter.

false

Variant

String

The variant type for this button.

false

IconAlignment

String

How to align the icon within the button.

false

FullWidth

SwitchParameter

Whether the button takes the full width of the it's container.

false

OnClick

Endpoint

The action to take when the button is clicked.

false

Size

String

The size of the button.

false

Style

Hashtable

Styles to apply to the button.

false

Href

String

A URL that the user should be redirected to when clicking the button.

false

Id

String

The ID of the component. It defaults to a random GUID.

false

Code Editor

Code editor component for Universal Dashboard.

To use a code editor within your dashboard, you will need to add the UniversalDashboard.CodeEditor component.

Creating a Code Editor

You can create a new code editor with the New-UDCodeEditor cmdlet. Specifying the -Language parameter will enable syntax highlighting for that language. You will need to specify a height in pixels.

New-UDCodeEditor -Height '500' -Language 'powershell'

Populating Code

Use the -Code parameter to specify code that will be populated within the code editor when it loads.

New-UDCodeEditor -Height '500' -Language 'powershell' -Code '#Hello, world!'

Retrieving code from another component

You can retrieve code from another component using the Get-UDElement cmdlet and accessing the code property of the hashtable that is returned.

New-UDCodeEditor -Height '500' -Language 'powershell' -Code '#Hello, world!' -Id 'editor'

New-UDButton -Text 'Get Code' -OnClick {
    Show-UDToast -Message (Get-UDElement -id 'editor').Code
}

Setting code from another component

You can set code from another component using the Set-UDElement cmdlet. Specify the code value in a hashtable passed to the -Properties parameter.

New-UDCodeEditor -Height '500' -Language 'powershell' -Code '#Hello, world!' -Id 'editor'

New-UDButton -Text 'Get Code' -OnClick {
    Set-UDElement -Id 'editor' -Properties @{
        code = "# Hello!"
    }
}

Options

The documentation is for an upcoming feature of PowerShell Universal .

The Monaco editor supports a wide range of options. If you wish to use options that aren't available on the New-UDCodeEditor cmdlet, you can use the -Options parameter and pass a hashtable of options instead.

New-UDCodeEditor -Language powershell -Height 100 -Options @{ fontSize = 10 }

Textbox

Textbox component for Universal Dashboard

A textbox lets users enter and edit text.

Textbox

New-UDTextbox -Label 'Standard' -Placeholder 'Textbox'
New-UDTextbox -Label 'Disabled' -Placeholder 'Textbox' -Disabled
New-UDTextbox -Label 'Textbox' -Value 'With value'

Password Textbox

A password textbox will mask the input.

New-UDTextbox -Label 'Password' -Type password

Multiline

You can create a multiline textbox by using the -Multiline parameter. Pressing enter will add a new line. You can define the number of rows and the max number of rows using -Rows and -RowsMax.

New-UDTextbox -Multiline -Rows 4 -RowsMax 10

Interaction

Retrieving a textbox value

You can use Get-UDElement to get the value of a textbox

New-UDTextbox -Id 'txtExample' 
New-UDButton -OnClick {
    $Value = (Get-UDElement -Id 'txtExample').value 
    Show-UDToast -Message $Value
} -Text "Get textbox value"

Setting the textbox value

New-UDTextbox -Id 'txtExample' -Label 'Label' -Value 'Value'

New-UDButton -OnClick {

    Set-UDElement -Id 'txtExample' -Properties @{
        Value = "test123"
    }

} -Text "Get textbox value"

Icons

You can set the icon of a textbox by using the -Icon parameter and the New-UDIcon cmdlet.

New-UDTextbox -Id "ServerGroups" -Icon (New-UDIcon -Icon 'server') -Value "This is my server"

Mask

You can define a text mask with a combination of strings and regular expressions. To specify a regular expression, use the JavaScript syntax in your string to start and finish the expression: /\d/.

This example creates a mask for US based phone numbers.

New-UDTextbox -Mask @('+', '1', ' ', '(', '/[1-9]/', '/\d/', '/\d/', ')', ' ', '/\d/', '/\d/', '/\d/', '-', '/\d/', '/\d/', '/\d/', '/\d/')

New-UDTextbox

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Label

String

A label to show above this textbox.

false

Placeholder

String

A placeholder to place within the text box.

false

Value

Object

The current value of the textbox.

false

Type

String

The type of textbox. This can be values such as text, password or email.

false

Disabled

SwitchParameter

Whether this textbox is disabled.

false

Icon

Object

The icon to show next to the textbox.

false

Autofocus

SwitchParameter

Whether to autofocus this textbox.

false

Multiline

SwitchParameter

Whether the textbox accepts multiple lines.

false

Rows

int

The number of rows in a multiline textbox

false

RowsMax

int

The max number of rows in a multiline textbox

false

Radio

Radio component for Universal Dashboard

Radio buttons allow the user to select one option from a set.

Use radio buttons when the user needs to see all available options. If available options can be collapsed, consider using a dropdown menu because it uses less space.

Radio buttons should have the most commonly used option selected by default.

Simple Radio

New-UDRadioGroup -Label "Day" -Content {
    New-UDRadio -Label Monday -Value 'monday'
    New-UDRadio -Label Tuesday -Value 'tuesday'
    New-UDRadio -Label Wednesday -Value 'wednesday'
    New-UDRadio -Label Thursday -Value 'thursday'
    New-UDRadio -Label Friday  -Value 'friday'
    New-UDRadio -Label Saturday -Value 'saturday'
    New-UDRadio -Label Sunday -Value 'sunday'
}

OnChange

An event handler that is called when the radio group is changed. the $Body variable will contain the current value.

New-UDRadioGroup -Label "Day" -Content {
    New-UDRadio -Label Monday -Value 'monday'
    New-UDRadio -Label Tuesday -Value 'tuesday'
    New-UDRadio -Label Wednesday -Value 'wednesday'
    New-UDRadio -Label Thursday -Value 'thursday'
    New-UDRadio -Label Friday  -Value 'friday'
    New-UDRadio -Label Saturday -Value 'saturday'
    New-UDRadio -Label Sunday -Value 'sunday'
} -OnChange { Show-UDToast -Message $Body }
    }

Default Value

Set the default value of the radio group.

New-UDRadioGroup -Label "Day" -Content {
    New-UDRadio -Label Monday -Value 'monday'
    New-UDRadio -Label Tuesday -Value 'tuesday'
    New-UDRadio -Label Wednesday -Value 'wednesday'
    New-UDRadio -Label Thursday -Value 'thursday'
    New-UDRadio -Label Friday  -Value 'friday'
    New-UDRadio -Label Saturday -Value 'saturday'
    New-UDRadio -Label Sunday -Value 'sunday'
} -Value 'sunday'

Custom Formatting

You can use custom formatting within the radio group. The below example will place the radio buttons next to each other instead of on top of each other.

New-UDRadioGroup -Label "Day" -Content {
    New-UDRow -Columns {
        New-UDColumn -LargeSize 1 -Content {
            New-UDRadio -Label Monday -Value 'monday'        
        }
        New-UDColumn -LargeSize 1 -Content {
            New-UDRadio -Label Sunday -Value 'sunday'
        }
    }
}

New-UDRadio

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Label

String

The label to show next to the radio.

false

Disabled

SwitchParameter

Whether the radio is disabled.

false

Value

String

The value of the radio.

false

LabelPlacement

String

The position to place the label in relation to the radio.

false

Select

Select component for Universal Dashboard

Select components are used for collecting user provided information from a list of options.

Simple Select

Create a simple select with multiple options.

New-UDSelect -Option {
    New-UDSelectOption -Name 'One' -Value 1
    New-UDSelectOption -Name 'Two' -Value 2
    New-UDSelectOption -Name 'Three' -Value 3
}

Grouped Select

Create a select with groups of selections.

New-UDSelect -Option {
    New-UDSelectGroup -Name 'Group One' -Option {
        New-UDSelectOption -Name 'One' -Value 1
        New-UDSelectOption -Name 'Two' -Value 2
        New-UDSelectOption -Name 'Three' -Value 3
    }
    New-UDSelectGroup -Name 'Group Two' -Option {
        New-UDSelectOption -Name 'Four' -Value 4
        New-UDSelectOption -Name 'Five' -Value 5
        New-UDSelectOption -Name 'Size' -Value 6
    }
}

OnChange

Execute a PowerShell event handler when the value of the select is changed.

New-UDSelect -Option {
    New-UDSelectOption -Name 'One' -Value 1
    New-UDSelectOption -Name 'Two' -Value 2
    New-UDSelectOption -Name 'Three' -Value 3
} -OnChange { Show-UDToast -Message $EventData }

Get-UDElement

Retrieve the value of the select from another component.

  New-UDSelect -Option {
      New-UDSelectOption -Name 'One' -Value 1
      New-UDSelectOption -Name 'Two' -Value 2
      New-UDSelectOption -Name 'Three' -Value 3
  } -Id 'select' -DefaultValue 2

  New-UDButton  -Text 'OnBoard' -OnClick {
    $Element = Get-UDElement -Id 'select'
    if ($Element.Value)
    {
      Show-UDToast -Message $Element.Value
    }
    else 
    {
      Show-UDToast -Message $Element.DefaultValue
    }
  }

New-UDSelect

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Option

ScriptBlock

Options to include in this select. This can be either New-UDSelectOption or New-UDSelectGroup.

false

Label

String

The label to show with the select.

false

OnChange

Endpoint

A script block that is executed when the script changes. $EventData will be an array of the selected values.

false

DefaultValue

String

The default selected value.

false

Disabled

SwitchParameter

Whether this select is disabled.

false

Multiple

SwitchParameter

Whether you can select multiple values.

false

Switch

Switch component for Universal Dashboard

Switches toggle the state of a single setting on or off.

Switches are the preferred way to adjust settings on mobile. The option that the switch controls, as well as the state it’s in, should be made clear from the corresponding inline label.

Switch

Create a basic switch.

New-UDSwitch -Checked $true 
New-UDSwitch -Checked $true -Disabled

OnChange Event

Respond to when a switch value is changed. The $EventData variable will include whether or not the switch was checked or unchecked.

New-UDSwitch -OnChange { Show-UDToast -Message $EventData }

Get-UDElement Support

You can retrieve the value of the switch within another component by using Get-UDElement. Use the Checked property to determine whether the switch is checked out not.

New-UDSwitch -Id 'switch' 
New-UDButton -Text 'Click' -OnClick {
    Show-UDToast -Message (Get-UDElement -Id 'switch').checked
}

New-UDSwitch

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Disabled

SwitchParameter

Whether this switch is disabled.

false

OnChange

Endpoint

A script block that is called when this switch changes. The $EventData variable will contain the checked value ($true$false).

false

Checked

Boolean

Whether this switch is checked.

false

Date Picker

Date Picker component for Universal Dashboard

Date pickers pickers provide a simple way to select a single value from a pre-determined set.

New-UDDatePicker

OnChange Event Handler

The OnChange event handler is called when the date changes. You can access the current date by using the $Body variable.

New-UDDatePicker -OnChange {
    Show-UDToast -Message $body
}

Variant

You can customize how the date picker is show. The default is the inline variant that displays the date picker popup inline with the input control. You can also use the dialog variant that pops the date picker up in the middle of the screen. Finally, the static variant displays the date picker without having to click anything.

New-UDDatePicker -Variant static

New-UDDatePicker

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Label

String

The label to show next to the date picker.

false

Variant

String

The theme variant to apply to the date picker.

false

DisableToolbar

SwitchParameter

Disables the date picker toolbar.

false

OnChange

Endpoint

A script block to call with the selected date. The $EventData variable will be the date selected.

false

Format

String

The format of the date when it is selected.

false

Value

DateTime

The current value of the date picker.

false

Form

Form component for Universal Dashboard

Forms provide a way to collect data from users.

Forms can include any type of control you want. This allows you to customize the look and feel and use any input controls.

Data entered via the input controls will be sent back to the the OnSubmit script block when the form is submitted. Within the OnSubmit event handler, you will access to the $EventData variable that will contain properties for each of the fields in the form.

For example, if you have two fields, you will have two properties on $EventData.

New-UDForm -Content {
    New-UDTextbox -Id 'txtTextField'
    New-UDCheckbox -Id 'chkCheckbox'
} -OnSubmit {
    Show-UDToast -Message $EventData.txtTextField
    Show-UDToast -Message $EventData.chkCheckbox
}

Supported Controls

The following input controls automatically integrate with a form. The values that are set within these controls will be sent during validation and in the OnSubmit event handler.

Simple Form

Simple forms can use inputs like text boxes and checkboxes.

New-UDForm -Content {
    New-UDTextbox -Id 'txtTextfield'
    New-UDCheckbox -Id 'chkCheckbox'
} -OnSubmit {
    Show-UDToast -Message $EventData.txtTextfield
    Show-UDToast -Message $EventData.chkCheckbox
}

Formatting a Form

Since forms can use any component, you can use standard formatting components within the form.

New-UDForm -Content {

    New-UDRow -Columns {
        New-UDColumn -SmallSize 6 -LargeSize 6 -Content {
            New-UDTextbox -Id 'txtFirstName' -Label 'First Name' 
        }
        New-UDColumn -SmallSize 6 -LargeSize 6 -Content {
            New-UDTextbox -Id 'txtLastName' -Label 'Last Name'
        }
    }

    New-UDTextbox -Id 'txtAddress' -Label 'Address'

    New-UDRow -Columns {
        New-UDColumn -SmallSize 6 -LargeSize 6  -Content {
            New-UDTextbox -Id 'txtState' -Label 'State'
        }
        New-UDColumn -SmallSize 6 -LargeSize 6  -Content {
            New-UDTextbox -Id 'txtZipCode' -Label 'ZIP Code'
        }
    }

} -OnSubmit {
    Show-UDToast -Message $EventData.txtFirstName
    Show-UDToast -Message $EventData.txtLastName
}

Returning Components

When a form is submitted, you can optionally return another component to replace the form on the page. You can return any Universal Dashboard component. All you need to do is ensure that the component is written to the pipeline within the OnSubmit event handler.

New-UDForm -Content {
    New-UDTextbox -Id 'txtTextfield'
} -OnSubmit {
    New-UDTypography -Text $EventData.txtTextfield
}

Validating a Form

Form validation can be accomplished by using the OnValidate script block parameter

New-UDForm -Content {
    New-UDTextbox -Id 'txtValidateForm'
} -OnValidate {
    $FormContent = $EventData

    if ($FormContent.txtValidateForm -eq $null -or $FormContent.txtValidateForm -eq '') {
        New-UDFormValidationResult -ValidationError "txtValidateForm is required"
    } else {
        New-UDFormValidationResult -Valid
    }
} -OnSubmit {
    Show-UDToast -Message $Body
}

Canceling a Form

You can define an -OnCancel event handler to invoke when the cancel button is pressed. This can be used to take actions like close a modal.

New-UDButton -Text 'On Form' -OnClick {
    Show-UDModal -Content {
        New-UDForm -Content {
            New-UDTextbox -Label 'Hello'
        } -OnSubmit {
            Show-UDToast -Message 'Submitted!'
            Hide-UDModal
        } -OnCancel {
            Hide-UDModal
        }
    }
}

Displaying output without Replacing the form

Although you can return components directly from a form, you may want to retain the form so users can input data again. To do so, you can use Set-UDElement and a placeholder element that you can set the content to.

In this example, we have an empty form that, when submitted, will update the results element with a UDCard.

New-UDForm -Content {

} -OnSubmit {
   Set-UDElement -Id 'results' -Content {
      New-UDCard -Content { "Hello " + (Get-Date) }
   }
}

New-UDElement -Id 'results' -Tag 'div'

New-UDForm

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Children

ScriptBlock

Controls that make up this form. This can be any combination of controls. Input controls will report their state to the form.

true

OnSubmit

Endpoint

A script block that is execute when the form is submitted. You can return controls from this script block and the form will be replaced by the script block. The $EventData variable will contain a hashtable of all the input fields and their values.

true

OnValidate

Endpoint

A script block that validates the form. Return the result of a call to New-UDFormValidationResult.

false

OnProcessing

ScriptBlock

A script block that is called when the form begins processing. The return value of this script block should be a component that displays a loading dialog. The script block will receive the current form data.

false

OnCancel

Endpoint

An endpoint that is called when this form is cancelled. When this parameter is defined a cancel button will appear.

false

New-UDFormValidationResult

Name

Type

Description

Required

Valid

SwitchParameter

Whether the form status is considered valid.

false

ValidationError

String

An error to display if the form is not valid.

false

Time Picker

Time picker component for Universal Dashboard

Time pickers pickers provide a simple way to select a single value from a pre-determined set.

Time Picker

New-UDTimePicker

The code editor component allows you to host the editor within your dashboards.

For a full list of options, check the interface.

Date pickers can be used in and .

Microsoft Monaco
IEditorConsturctionOptions
Forms
Steppers
Autocomplete
Checkbox
Date Picker
Radio
Select
Slider
Switch
Textbox
Time Picker
Upload
Learn more about adding custom component libraries
New-UDTimePicker

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Label

String

The label to show with the time picker.

false

OnChange

Endpoint

A script block to call when the time is changed. The $EventData variable contains the currently selected time.

false

Value

String

The current value of the time picker.

false

Drawer

Drawer component for Universal Dashboard

Permanent Drawer

A permanent drawer will be shown at all times. By default, it is show on the left side of the screen.

New-UDDrawer -Variant 'permanent' -Content {
  New-UDList -Children {
        New-UDListItem -Label "Home"
        New-UDListItem -Label "Getting Started" -Children {
            New-UDListItem -Label "Installation" -OnClick {}
            New-UDListItem -Label "Usage" -OnClick {}
            New-UDListItem -Label "FAQs" -OnClick {}
            New-UDListItem -Label "System Requirements" -OnClick {}
            New-UDListItem -Label "Purchasing" -OnClick {}
        }
    }
}

Slider

Slider component for Universal Dashboard.

Sliders allow users to make selections from a range of values.

Sliders reflect a range of values along a bar, from which users may select a single value. They are ideal for adjusting settings such as volume, brightness, or applying image filters.

Slider

New-UDSlider -Value 1

Slider with minimum and maximum values

New-UDSlider -Min 10 -Max 1000

Disabled Slider

New-UDSlider -Disabled

Slider with custom step size

New-UDSlider -Min 10 -Max 1000 -Step 100

Slider with marks

New-UDSlider -Marks

Range based slider

New-UDSlider -Value @(1, 10)

OnChange event for slider

New-UDSlider -OnChange {
    Show-UDToast -Message $Body 
    Set-TestData $Body
}

New-UDSlider

Name

Type

Description

Required

Id

string

false

Value

int[]

false

Minimum

int

false

Maximum

int

false

Disabled

switch

false

Marks

switch

false

OnChange

Endpoint

false

Orientation

string

false

Step

int

false

ValueLabelDisplay

string

false

Transitions

Transition component for Universal Dashboard.

Transitions allow you to transition components in and out of view within your dashboard using various animations. You can take advantage of interactive cmdlets like Set-UDElement to change the transition state and cause an element to move in.

In the following example, we have a card that transitions in via a Fade. Clicking the switch the toggle the card in and out.

New-UDTransition -Id 'test' -Content {
    New-UDCard -Text "Hey"
} -In -Fade -Timeout 1000

New-UDSwitch -OnChange {
    Set-UDElement -Id 'test' -Properties @{
        in = $EventData -eq 'True'
    }
} -Checked $true

The resulting effect looks like this.

Collapse

The collapse transition will collapse a section in and out. You can specify a collapse height to only collapse a portion of the section.

New-UDTransition -Id 'test' -Content {
    New-UDCard -Text "Hey"
} -In -Collapse -CollapseHeight 100 -Timeout 1000

New-UDSwitch -OnChange {
    Set-UDElement -Id 'test' -Properties @{
        in = $EventData -eq 'True'
    }
} -Checked $true

Fade

A fade transition fades a component in and out as seen in the previous example. You can configure the timeout value to specify the number of seconds it takes to complete the transition.

New-UDTransition -Id 'test' -Content {
    New-UDCard -Text "Hey"
} -In -Fade -Timeout 1000

New-UDSwitch -OnChange {
    Set-UDElement -Id 'test' -Properties @{
        in = $EventData -eq 'True'
    }
} -Checked $true

Slide

The slide transition moves a component into position. You can determine the position of the slide by specifying the -SlideDirection parameter.

New-UDTransition -Id 'test' -Content {
    New-UDCard -Text "Hey"
} -In -Slide -SlideDirection 'left' -Timeout 1000

New-UDSwitch -OnChange {
    Set-UDElement -Id 'test' -Properties @{
        in = $EventData -eq 'True'
    }
} -Checked $true

Grow

The grow transition will fade and grow a component into place.

New-UDTransition -Id 'test' -Content {
    New-UDCard -Text "Hey"
} -In -Grow -Timeout 1000

New-UDSwitch -OnChange {
    Set-UDElement -Id 'test' -Properties @{
        in = $EventData -eq 'True'
    }
} -Checked $true

Zoom

The zoom transition will zoom a component into place.

New-UDTransition -Id 'test' -Content {
    New-UDCard -Text "Hey"
} -In -Zoom -Timeout 1000

New-UDSwitch -OnChange {
    Set-UDElement -Id 'test' -Properties @{
        in = $EventData -eq 'True'
    }
} -Checked $true

Grid Layout

Drag and drop layout designer.

Grid Layout

This component is available on the Universal Dashboard Marketplace

The Grid Layout component is useful for defining layouts in a visual manner. You can drag and drop components using the web interface to automatically define the layout as JSON.

Installation

Install-Module UniversalDashboard.GridLayout

Designing Layouts

You can employ the -Design parameter to configure the layout of yourr page. This allows dynamic drag and drop of components that you place within the content of the grid layout. As you drag and resize components, the layout will be copied to your clipboard. Note: All components must possess a statid -Id

New-UDGridLayout -Content { 1..10 | ForEach-Object { New-UDPaper -Id "Paper$" -Content { New-UDTypography -Text $ } -Elevation 5 } } -Design

Using Layouts

Once you have configured the layout to fit your needs, you can paste the JSON into your script and assign it with the -Layout parameter. Remove the -Design parameter to lock elements in place.

$Layout = '{"lg":[{"w":7,"h":7,"x":5,"y":0,"i":"grid-element-Paper1","moved":false,"static":false},{"w":7,"h":5,"x":5,"y":7,"i":"grid-element-Paper2","moved":false,"static":false},{"w":1,"h":1,"x":0,"y":0,"i":"grid-element-Paper3","moved":false,"static":false},{"w":1,"h":1,"x":0,"y":1,"i":"grid-element-Paper4","moved":false,"static":false},{"w":1,"h":1,"x":0,"y":2,"i":"grid-element-Paper5","moved":false,"static":false},{"w":1,"h":1,"x":0,"y":3,"i":"grid-element-Paper6","moved":false,"static":false},{"w":1,"h":1,"x":0,"y":4,"i":"grid-element-Paper7","moved":false,"static":false},{"w":1,"h":1,"x":0,"y":5,"i":"grid-element-Paper8","moved":false,"static":false},{"w":1,"h":1,"x":0,"y":6,"i":"grid-element-Paper9","moved":false,"static":false},{"w":1,"h":1,"x":0,"y":7,"i":"grid-element-Paper10","moved":false,"static":false}]}' 
New-UDGridLayout -Content { 1..10 | ForEach-Object { New-UDPaper -Id "Paper$" -Content { New-UDTypography -Text $ } -Elevation 5 } } -Layout $Layout

Allowing Users to Modify Layouts

You can allow your users to dynamically modify layouts by using the -Draggable, -Resizable and -Persist parameters. The layout changes are stored locally so the next time each user visits a page, it will be loaded with their chosen layout.

New-UDGridLayout -Content { 1..10 | ForEach-Object { New-UDPaper -Id "Paper$" -Content { New-UDTypography -Text $ } -Elevation 5 } } -Draggable -Resizable -Persist

Upload

Component for uploading files in Universal Dashboard.

The UDUpload component is used to upload files to Universal Dashboard. You can process files the user uploads. You will receive the data for the file, a file name and the type of file if it can be determined by the web browser.

Uploading a File

Uploads a file and shows the contents via a toast.

New-UDUpload -OnUpload {
    Show-UDToast $Body
}

The body of the OnUpload script block is a JSON string with the following format.

{
  data: "base64 encoded string of data",
  name: "file name of the file uploaded",
  type: "file type as determined by the browser"
}

Uploading a File with a Form

Uploads a file as part of a UDForm.

New-UDForm -Content {
    New-UDUpload -Id 'myFile' 
} -OnSubmit {
    Show-UDToast $Body 
}

The body of the OnSubmit script block is the same one you will see with any form and the file will be contains as one of the fields within the form.

Example: Uploading a file and save to it the temp directory

This example allows a user to upload a file. Once the file is uploaded, it will be saved to the temporary directory.

New-UDUpload -Text 'Upload Image' -OnUpload {
    $Data = $Body | ConvertFrom-Json 
    $bytes = [System.Convert]::FromBase64String($Data.Data)
    [System.IO.File]::WriteAllBytes("$env:temp\$($Data.Name)", $bytes)
}

New-UDUpload

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Accept

String

The type of files to accept. By default, this component accepts all files.

false

OnUpload

Endpoint

A script block to call when the file is uploaded.

false

Text

String

The text to display in the upload button.

false

Variant

String

The type of button to show for the upload button.

false

Color

String

The color to use for the upload button.

false

Backdrop

Backdrop component for Universal Dashboard.

This component will be available in a future version of Universal Dashboard.

The backdrop component places an overlay over the drop of the entire page. It's useful for displaying loading states.

Basic Backdrop

To create a basic backdrop, you can use the New-UDBackdrop cmdlet and include content to show within the backdrop. The content will be centered on the page. To show the backdrop, use the -Open switch parameter.

OnClick Handler

The backdrop provides an -OnClick handler that you can use to close the backdrop when clicked. You can use Set-UDElement to open and close the backdrop.

Tabs

Tab component for Universal Dashboard

Tabs make it easy to explore and switch between different views.

Tabs organize and allow navigation between groups of content that are related and at the same level of hierarchy.

Tabs

Vertical Tabs

Dynamic Tabs

Dynamic tabs will refresh their content when they are selected. You will need to include the -RenderOnActive parameter to prevent all the tabs from rendering even if they are not shown.

New-UDTabs

New-UDTab

Permanent Drawer
Transition a card
Collapse Transition
Slide Transition
Grow Transition
Zoom Transition

This component works with and .

UDForm
UDStepper
New-UDBackdrop -Content {
    New-UDTypography -Text "Loading..." -Variant h2
} -Open
New-UDBackdrop -Id 'backdrop' -Content {
    New-UDTypography -Text "Loading..." -Variant h2
} -Open -OnClick {
    Set-UDElement -Id 'backdrop' -Properties @{
        open = $false
    }
}
New-UDTabs -Tabs {
    New-UDTab -Text 'Item One' -Content { New-UDTypography -Text 'Item One' -Variant 'h2' }
    New-UDTab -Text 'Item Two' -Content { New-UDTypography -Text 'Item Two' -Variant 'h2' }
    New-UDTab -Text 'Item Three' -Content { New-UDTypography -Text 'Item Three' -Variant 'h2' }
}
New-UDTabs -Tabs {
    New-UDTab -Text 'Item One' -Content { New-UDTypography -Text 'Item One' -Variant 'h2' }
    New-UDTab -Text 'Item Two' -Content { New-UDTypography -Text 'Item Two' -Variant 'h2' }
    New-UDTab -Text 'Item Three' -Content { New-UDTypography -Text 'Item Three' -Variant 'h2' }
} -Orientation vertical
New-UDTabs -Tabs {
    New-UDTab -Text 'Item One' -Content { Get-Date } -Dynamic
    New-UDTab -Text 'Item Two' -Content { Get-Date } -Dynamic
    New-UDTab -Text 'Item Three' -Content { Get-Date } -Dynamic
} -RenderOnActive

Name

Type

Description

Required

Tabs

ScriptBlock

The tabs to put within this container.

true

Id

String

The ID of the component. It defaults to a random GUID.

false

RenderOnActive

SwitchParameter

Whether to render the tabs when they are clicked. Is this value isn't present, all the tabs are rendered, even if they are not shown.

false

Orientation

String

The orientation of the tabs.

false

Name

Type

Description

Required

Text

string

The text to display in the header.

false

Content

scriptblock

The content of the tab.

true

Id

string

The ID of the tab.

false

Dynamic

switch

A dynamic tab will reload every time it is selected.

false

Icon

Object

false

Stacked

switch

false

Stepper

Stepper component for Universal Dashboard

Steppers convey progress through numbered steps. It provides a wizard-like workflow.

Steppers display progress through a sequence of logical and numbered steps. They may also be used for navigation. Steppers may display a transient feedback message after a step is saved. The stepper supports storing input data in the stepper context. It supports the following controls.

Stepper

New-UDStepper -Steps {
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 1" }
        New-UDTextbox -Id 'txtStep1' -Value $EventData.Context.txtStep1
    } -Label "Step 1"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 2" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep2' -Value $EventData.Context.txtStep2
    } -Label "Step 2"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 3" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep3' -Value $EventData.Context.txtStep3
    } -Label "Step 3"
} -OnFinish {
    New-UDTypography -Text 'Nice! You did it!' -Variant h3
    New-UDElement -Tag 'div' -Id 'result' -Content {$Body}
}

The $Body variable will contain a JSON string that contains the current state of the stepper. You will receive information about the fields that have been defined within the stepper and info about the current step that has been completed. The $Body JSON string will have the following format.

{
    context: {
        txtStep1: "value1",
        txtStep2: "value2",
        txtStep3: "value3"
    },
    currentStep: 0
}

Validating a Step

You can validate a step in a stepper by specifying the OnValidateStep parameter. The script block will receive a $Body variable with JSON that provides information about the current state of the stepper. You will need to return a validation result using New-UDValidationResult to specify whether the current step state is valid.

The JSON payload will have the following format. Note that steps are 0 indexed. If you want to validate the first step, check to make sure the step is 0.

{
    context: {
        field1: "value1" 
    },
    currentStep: 0
}

You will have to convert the JSON string to an object to work with in PowerShell and then return the validation result.

New-UDStepper -Steps {
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 1" }
        New-UDTextbox -Id 'txtStep1' -Value $EventData.Context.txtStep1
    } -Label "Step 1"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 2" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep2' -Value $EventData.Context.txtStep2
    } -Label "Step 2"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 3" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep3' -Value $EventData.Context.txtStep3
    } -Label "Step 3"
} -OnFinish {
    New-UDTypography -Text 'Nice! You did it!' -Variant h3
    New-UDElement -Tag 'div' -Id 'result' -Content {$Body}
} -OnValidateStep {
    $Context = $EventData
    if ($Context.CurrentStep -eq 0 -and $Context.Context.txtStep1 -eq 'bad')
    {
        New-UDValidationResult 
    }
    else
    {
        New-UDValidationResult -Valid 
    }
}

Skipping Steps

You can direct the user to a particular step in the OnValidateStep event handler. Use the New-UDValidationResult -ActiveStep parameter to move the user to any step after clicking next. Step indices are 0 based.

This example moves the user to the last step after completing the first step.

New-UDStepper -Steps {
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 1" }
        New-UDTextbox -Id 'txtStep1' -Value $EventData.Context.txtStep1
    } -Label "Step 1"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 2" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep2' -Value $EventData.Context.txtStep2
    } -Label "Step 2"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 3" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep3' -Value $EventData.Context.txtStep3
    } -Label "Step 3"
} -OnFinish {
    New-UDTypography -Text 'Nice! You did it!' -Variant h3
    New-UDElement -Tag 'div' -Id 'result' -Content {$Body}
} -OnValidateStep {
    $Context = $EventData
    if ($Context.CurrentStep -eq 0 -and $Context.Context.txtStep1 -eq 'bad')
    {
        New-UDValidationResult 
    }
    else
    {
        New-UDValidationResult -Valid -ActiveStep 2
    }
}

Disable Previous Button

You can disable the previous button by using the -DisablePrevious parameter of New-UDValidationResult .

This example disables the previous step whenever the user moves forward in the stepper.

New-UDStepper -Steps {
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 1" }
        New-UDTextbox -Id 'txtStep1' -Value $EventData.Context.txtStep1
    } -Label "Step 1"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 2" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep2' -Value $EventData.Context.txtStep2
    } -Label "Step 2"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 3" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep3' -Value $EventData.Context.txtStep3
    } -Label "Step 3"
} -OnFinish {
    New-UDTypography -Text 'Nice! You did it!' -Variant h3
    New-UDElement -Tag 'div' -Id 'result' -Content {$Body}
} -OnValidateStep {
    New-UDValidationResult -Valid -DisablePrevious
}

Vertical Steppers

You can create a vertical stepper by setting the -Orientation parameter to vertical.

New-UDStepper -Steps {
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 1" }
        New-UDTextbox -Id 'txtStep1' -Value $EventData.Context.txtStep1
    } -Label "Step 1"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 2" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep2' -Value $EventData.Context.txtStep2
    } -Label "Step 2"
    New-UDStep -OnLoad {
        New-UDElement -tag 'div' -Content { "Step 3" }
        New-UDElement -tag 'div' -Content { "Previous data: $Body" }
        New-UDTextbox -Id 'txtStep3' -Value $EventData.Context.txtStep3
    } -Label "Step 3"
} -OnFinish {
    New-UDTypography -Text 'Nice! You did it!' -Variant h3
    New-UDElement -Tag 'div' -Id 'result' -Content {$Body}
} -Orientation 'vertical'

New-UDStepper

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

ActiveStep

Int32

Sets the active step. This should be the index of the step.

false

Steps

ScriptBlock

The steps for this stepper. Use New-UDStep to create new steps.

true

NonLinear

SwitchParameter

Allows the user to progress to steps out of order.

false

AlternativeLabel

SwitchParameter

Places the step label under the step number.

false

OnFinish

Endpoint

A script block that is executed when the stepper is finished.

true

OnValidateStep

Endpoint

A script block that is executed when validating each step.

false

Orientation

string

Vertical or Horizontal

false

New-UDStep

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

OnLoad

Endpoint

The script block that is executed when the step is loaded. The script block will receive the $Body parameter which contains JSON for the current state of the stepper. If you are using form controls, their data will be availalble in the $Body.Context property.

true

Label

String

A label for this step.

false

Optional

SwitchParameter

Whether this step is optional.

false

Paper

Paper component for Universal Dashboard

In Material Design, the physical properties of paper are translated to the screen.

The background of an application resembles the flat, opaque texture of a sheet of paper, and an application’s behavior mimics paper’s ability to be re-sized, shuffled, and bound together in multiple sheets.

Paper

New-UDPaper -Elevation 0 -Content {} 
New-UDPaper -Elevation 1 -Content {} 
New-UDPaper -Elevation 3 -Content {}

Square Paper

By default, paper will have rounded edges. You can reduce the rounding by using a square paper.

New-UDPaper -Square -Content {}

Colored Paper

The -Style parameter can be used to color paper. Any valid CSS can be included in the hashtable for a style.

The following example creates paper with a red background.

New-UDPaper  -Content { } -Style @{ 
     backgroundColor = 'red'
}

New-UDPaper

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Children

ScriptBlock

The content of this paper element.

false

Width

String

The width of this paper.

false

Height

String

The height of this paper.

false

Square

SwitchParameter

Whether this paper is square.

false

Style

Hashtable

The CSS style to apply to this paper.

false

Elevation

Int32

The elevation of this paper.

false

Grid

Grid layout component for Universal Dashboard.

The responsive layout grid adapts to screen size and orientation, ensuring consistency across layouts.

The grid creates visual consistency between layouts while allowing flexibility across a wide variety of designs. Material Design’s responsive UI is based on a 12-column grid layout.

Basic Layout

New-UDGrid -Container -Content {
    New-UDGrid -Item -ExtraSmallSize 12 -Content {
        New-UDPaper -Content { "xs-12" } -Elevation 2
    }
    New-UDGrid -Item -ExtraSmallSize 6 -Content {
        New-UDPaper -Content { "xs-6" } -Elevation 2
    }
    New-UDGrid -Item -ExtraSmallSize 6 -Content {
        New-UDPaper -Content { "xs-6" } -Elevation 2
    }
    New-UDGrid -Item -ExtraSmallSize 3 -Content {
        New-UDPaper -Content { "xs-3" } -Elevation 2
    }
    New-UDGrid -Item -ExtraSmallSize 3 -Content {
        New-UDPaper -Content { "xs-3" } -Elevation 2
    }
    New-UDGrid -Item -ExtraSmallSize 3 -Content {
        New-UDPaper -Content { "xs-3" } -Elevation 2
    }
    New-UDGrid -Item -ExtraSmallSize 3 -Content {
        New-UDPaper -Content { "xs-3" } -Elevation 2
    }
}

Spacing

Adjust the spacing between items in the grid

New-UDDynamic -Id 'spacingGrid' -Content {
    $Spacing = (Get-UDElement -Id 'spacingSelect').value

    New-UDGrid -Spacing $Spacing -Container -Content {
        New-UDGrid -Item -ExtraSmallSize 3 -Content {
            New-UDPaper -Content { "xs-3" } -Elevation 2
        }
        New-UDGrid -Item -ExtraSmallSize 3 -Content {
            New-UDPaper -Content { "xs-3" } -Elevation 2
        }
        New-UDGrid -Item -ExtraSmallSize 3 -Content {
            New-UDPaper -Content { "xs-3" } -Elevation 2
        }
        New-UDGrid -Item -ExtraSmallSize 3 -Content {
            New-UDPaper -Content { "xs-3" } -Elevation 2
        }
    }
}

New-UDSelect -Id 'spacingSelect' -Label Spacing -Option {
    for($i = 0; $i -lt 10; $i++)
    {
        New-UDSelectOption -Name $i -Value $i
    }
} -OnChange { Sync-UDElement -Id 'spacingGrid' } -DefaultValue 3

Row and Columns

You can also use the New-UDRow and New-UDColumn functions when working with the grid.

New-UDRow -Columns {
    New-UDColumn -SmallSize 12 -Content {
        New-UDPaper -Content { "xs-12" } -Elevation 2
    }
    New-UDColumn -SmallSize 12 -Content {
        New-UDPaper -Content { "xs-12" } -Elevation 2
    }
}

New-UDGrid

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

ExtraSmallSize

Int32

The size (1-12) for extra small devices.

false

SmallSize

Int32

The size (1-12) for small devices.

false

MediumSize

Int32

The size (1-12) for medium devices.

false

LargeSize

Int32

The size (1-12) for large devices.

false

ExtraLargeSize

Int32

The size (1-12) for extra large devices.

false

Container

SwitchParameter

Whether this is a container. A container can be best described as a row.

false

Spacing

Int32

Spacing between the items.

false

Item

SwitchParameter

Whether this is an item in a container.

false

Children

ScriptBlock

Components included in this grid item.

false

Published Folders

Serve files from PowerShell Universal

Published folders allow you to share a local folder through your Universal website. Any file within the published folder will be accessible via a web request. This can be helpful for storing images or other files that you may want to provide via your Universal Dashboard.

Publishing a Folder

From the Dashboard / Published Folders page, you can click Add Published Folder. You will need to enter the local path as well as the request path. The local path is the folder that you wish to publish. The request path is the path that the end user will request to download the files from the folder.

You can choose to turn on authentication and authorization for the folder.

Once the folder has been published, it will be listed in the published folders table.

Download Files

You can now download files that are found in the published folder by visit the request path. In the example above, I could visit the following URL to download the test.txt file.

You'll notice that unauthenticated requests will not be able to access the file.

Default Documents

Default documents allow you to load files when a user specifies the folder and not the document within a folder. This can be handy when a user visits /docs but does not specify /docs/index.html. Instead of returning a 404, you can return the index.html when the user specifies /docs.

To configure default documents, set the -DefaultDocument parameter on New-PSUPublishedFolder.

API

New-PSUPublishedFolder

Create a published folder. Can be used in the publishedFolders.ps1 file or via the management REST API.

Themes

Here's an example of changing the theme's main color.

Setting the default theme

You can set the default theme to either Light or Dark using the -DefaultTheme parameter.

Changing the background color

You can change the page background color by setting the background default color. To adjust the header background color, set the primary main color.

Supporting dark and light palettes

To support dark and light palettes, you can define a dark and light sections in your hashtable. They have the same properties as a theme.

Changing the font size

To change the font size, set the typography fontSize property.

Changing default button colors

Cascading Style Sheets

Use cascading style sheets with Universal Dashboard.

You can use a cascading style sheet (CSS) by add a .css file to a published folder and then passing it to the -Stylesheets parameter for New-UDDashboard.

For example, the dashboard.ps1 file would look like this.

You could then setup a published folder to provide the assets route. This is what the contents of publishedFolders.ps1 will look like.

Within the C:\assets folder, you can place any assets you'd like to access on the /assets route.

You can then create a style sheet to manipulate whatever portion of the dashboard you'd like.

This produces a dashboard with a background image of Austin the dog sleeping in a pile of dirt.

Determining the Correct Class Names

Every Material UI component has a series of global class names that you can use to apply styles throughout your dashboard. To determine the correct class names, you can view the a particular component's API documentation. There is a list of the global class names that apply to that component.

Within your CSS file, you can use these class names to override styles throughout your dashboard. If you wanted to set all success alerts to have a red background, you could create a CSS file like this.

Expansion Panel

Expansion Panel component for Universal Dashboard

Expansion panels contain creation flows and allow lightweight editing of an element.

An expansion panel is a lightweight container that may either stand alone or be connected to a larger surface, such as a card.

Simple Expansion Panel

New-UDExpansionPanel

Card

Card component for Universal Dashboard

Cards contain content and actions about a single subject.

Cards are surfaces that display content and actions on a single topic. They should be easy to scan for relevant and actionable information. Elements, like text and images, should be placed on them in a way that clearly indicates hierarchy.

Simple Card

Although cards can support multiple actions, UI controls, and an overflow menu, use restraint and remember that cards are entry points to more complex and detailed information.

Advanced Card

You can use the body, header, footer and expand cmdlets to create advanced cards. The below example creates a card with various features based on a Hyper-V VM.

New-UDCard

Hidden

Quickly and responsively toggle the visibility value of components and more with the hidden utilities.

How it works

Hidden works with a range of breakpoints e.g. xsUp or mdDown, or one or more breakpoints e.g. -Only 'sm' or -Only @('md', 'xl'). Ranges and individual breakpoints can be used simultaneously to achieve very customized behavior. The ranges are inclusive of the specified breakpoints.

Up

Using any breakpoint -Up parameter, the given children will be hidden at or above the breakpoint.

Down

Using any breakpoint -Down parameter, the given children will be hidden at or below the breakpoint.

Only

Using the breakpoint -Only parameter, the given children will be hidden at the specified breakpoint(s).

The -Only parameter can be used in two ways:

  • list a single breakpoint

  • list an array of breakpoints

AppBar

AppBar component for Universal Dashboard

The App Bar displays information and actions relating to the current screen.

The top App Bar provides content and actions related to the current screen. It's used for branding, screen titles, navigation, and actions.

AppBar with Custom Drawer

Footer

To create an app bar that is pinned to the bottom of the page, you can use the -Footer parameter.

New-UDAppBar

Backdrop component

Universal Dashboard v3 is built on Material UI. Material UI provides a that UD now takes advantage of. You can utilize this theme system by providing a hashtable of options to the New-UDDashboard 's -Theme parameter.

For a full list of options available for the theme system, you can look at the .

For example, here is the .

Autocomplete
Checkbox
Date Picker
Radio
Select
Slider
Switch
Textbox
Time Picker
Upload
http://localhost:5000/src/test.txt
PS C:\src\universal\src> invoke-webrequest http://localhost:5000/src/test.txt
Invoke-WebRequest: Response status code does not indicate success: 401 (Unauthorized).
New-PSUPublishedFolder -Path C:\website -RequestPath /docs -DefaultDocument @("index.hml")

Name

Type

Description

Required

RequestPath

string

The relative path to server documents from.

true

Path

string

The absolute file system path to server files from.

true

Authentication

Switch

Whether authentication is required to access this folder.

false

Role

string[]

Roles that can access this folder. Leave blank for any role.

false

DefaultDocument

string[]

Default documents to server with out specifying the file name.

false

ComputerName

string

The URL to the PSU management API.

false

AppToken

string

The AppToken used to access the PSU management API

false

UseDefaultCredentials

Switch

Whether to use the current user's credentials to access the PSU management API

false

$Theme = @{
    palette = @{
        primary = @{
            main = '#111111'
        }
    }
}
New-UDDashboard -Theme $Theme -Title 'Hello' -Content {
    New-UDButton -Text "Test " -OnClick {
        Show-UDToast -Message 'HEllo'
    }
}
New-UDDashboard -Title 'Hello' -Content {
    New-UDButton -Text "Test " -OnClick {
        Show-UDToast -Message 'HEllo'
    }
} -DefaultTheme dark
$Theme = @{
    palette = @{
        primary = @{
            main = '#876a38'
        }
        background = @{
            default = '#876a38'
        }
    }
#    typography = @{
#        fontSize = 20
#    }
}
New-UDDashboard -Theme $Theme -Title 'Hello' -Content {
    New-UDButton -Text 'Hello' 
}
$Theme = @{
    light = @{
        palette = @{
            primary = @{
                main = "#fff"
            }
        }
    }
    dark = @{
        palette = @{
            primary = @{
                main = "#333"
            }
        }
    }
}
New-UDDashboard -Theme $Theme -Title 'Hello' -Content {
    New-UDButton -Text 'Hello' 
}
$Theme = @{
    typography = @{
        fontSize = 20
    }
}
New-UDDashboard -Theme $Theme -Title 'Hello' -Content {
    New-UDButton -Text 'Hello' 
}
$Theme = @{
    palette = @{
        grey = @{
            '300' = '#000'
        }
    }
}
New-UDDashboard -Theme $Theme -Title 'Hello' -Content {
    New-UDButton -Text 'Small Button'
}
New-UDDashboard -Title "Server Monitor" -Content {


} -Stylesheets @("/assets/theme.css")
New-PSUPublishedFolder -RequestPath "/assets" -Path "C:\assets"
.ud-dashboard > div {
    background-image: url("/assets/image.jpeg");
}
.MuiAlert-standardSuccess { background-color: red !important;  }
New-UDExpansionPanelGroup -Children {
    New-UDExpansionPanel -Title "Hello" -Children {}

    New-UDExpansionPanel -Title "Hello" -Id 'expContent' -Children {
        New-UDElement -Tag 'div' -Content { "Hello" }
    }
}

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Title

String

The title show within the header of the expansion panel.

false

Icon

FontAwesomeIcons

An icon to show within the header of the expansion panel.

false

Children

ScriptBlock

Children components to put within the expansion panel.

false

Active

SwitchParameter

Whether the expansion panel is currently active (open).

false

New-UDCard -Title 'Simple Card' -Content {
    "This is some content"
}
$VM = Get-VM -Name $VMName @ConnectionInfo

$Header = New-UDCardHeader -Title $VM.Name

$Footer = New-UDCardFooter -Content {
    if ($VM.State -eq 'Running')
    {
        New-UDButton -Variant text -Text 'Stop' -OnClick {
            Show-UDToast -Message 'Stopping VM...' -Duration 5000
            Stop-VM -VMName $VM.name @ConnectionInfo 
            Sync-UDElement -Id "$($VMName)_card"
        }
    } else {
        New-UDButton -Variant text -Text 'Start' -OnClick {
            Show-UDToast -Message 'Starting VM...' -Duration 5000
            Start-VM -VMName $VM.name @ConnectionInfo 
            Sync-UDElement -Id "$($VMName)_card"
        }
    }

}

$Body = New-UDCardBody -Content {
    New-UDTable -Data ($VM | Select-Object Name, State, CPUUsage, MemoryAssigned, Uptime)  -Dense 
}

$Expand = New-UDCardExpand -Content {
    New-UDElement -Tag 'div' -Content {
        New-UDTable -Data ($VM.DvdDrives | Select-Object Name, DvdMediaType, Path) -Title 'DVD Drives' -Dense
    } 

    $Drives = Get-VMHardDiskDrive -VMName $VM.Name @ConnectionInfo | Select-Object Name, Path
    New-UDTable -Data $Drives -Title 'Hard Disk Drives' -Dense

    New-UDTable -Data ($VM.NetworkAdapters | Select-Object 'SwitchName', 'MacAddress' ) -Dense -Title 'Network Adapters' 
}

New-UDStyle -Style '.ud-mu-cardexpand { display: block !important }' -Content {
    New-UDCard -Body $Body -Header $Header -Footer $Footer -Expand $Expand
}

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

ClassName

String

A CSS class to assign to this card.

false

ShowToolBar

SwitchParameter

Whether to show the toolbar for this card.

false

ToolBar

Object

The toolbar for this card. Use New-UDCardToolbar to create a toolbar.

false

Header

Object

The header for this card. The header typically contains a title for the card. Use New-UDCardHeader to create a header.

false

Body

Object

The body for this card. This is the main content for the card. Use New-UDCardHeader to create a body.

false

Expand

Object

Th expand content for this card. Expand content is show when the user clicks the expansion button. Use New-UDCardExpand to create an expand.

false

Footer

Object

The footer for this card. Footer contents typically contain actions that are relavent to the card. Use New-UDCardFooter to create a footer.

false

Style

Hashtable

Styles to apply to the card.

false

Elevation

Int32

The amount of elevation to provide the card. The more elevation, the more it will appear the card is floating off the page.

false

Title

String

A title for the card.

false

TitleAlignment

String

The alignment for the title.

false

Content

ScriptBlock

The content of the card.

false

Image

String

An image to show in the card.

false

innerWidth  |xs      sm       md       lg       xl
            |--------|--------|--------|--------|-------->
width       |   xs   |   sm   |   md   |   lg   |   xl

smUp        |   show | hide
mdDown      |                     hide | show
New-UDHidden -Up xl -Content {
    New-UDTypography 'xl'
}
New-UDHidden -Down xs -Content {
    New-UDTypography 'xs'
}
New-UDHidden -Only 'sm' -Content {
    New-UDTypography 'sm'
}
New-UDHidden -Only @('sm', 'xl') -Content {
    New-UDTypography 'sm,xl'
}
$Drawer = New-UDDrawer -Children {
    New-UDList -Children {
        New-UDListItem -Label "Home"
        New-UDListItem -Label "Getting Started" -Children {
            New-UDListItem -Label "Installation" -OnClick {}
            New-UDListItem -Label "Usage" -OnClick {}
            New-UDListItem -Label "FAQs" -OnClick {}
            New-UDListItem -Label "System Requirements" -OnClick {}
            New-UDListItem -Label "Purchasing" -OnClick {}
        }
    }
}

New-UDAppBar -Position relative -Children { New-UDElement -Tag 'div' -Content { "Title" } } -Drawer $Drawer
New-UDAppBar -Children { "Hello" } -Footer

Name

Type

Description

Required

Id

String

The ID of the component. It defaults to a random GUID.

false

Drawer

Hashtable

A drawer that can be opened from this AppBar. Use New-UDDrawer to create a drawer to pass to this parameter.

false

Children

ScriptBlock

Children of this AppBar. The children of an AppBar are commonly text and buttons.

false

Position

String

The position of this AppBar. A fixed position will override the default AppBar.

false

Footer

Switch

Creates an app bar pinned to the bottom of the page.

false

built-in theme system
default theme for Material UI
CSS documentation for the Alert component

Interaction

Interaction features of Universal Dashboard

Universal Dashboard enables the ability to create interactive websites with PowerShell. There are several cmdlets that have been implemented to provide feedback to the user, update components and read the state of components.

Clipboard

You can set string data into the user's clipboard with Set-UDClipboard.

New-UDButton -Text 'Clipboard' -OnClick {
    Set-UDClipboard -Data 'Hello, there!'
}

API

Set-UDClipboard

Name

Type

Description

Required

Data

string

The content to set to the clipboard

true

ToastOnSuccess

Switch

Shows a toast if the data was successfully set in the clipboard

false

ToastOnError

Switch

Shows as toast if the data was unsuccessfully set in the clipboard

false

JavaScript

You can invoke JavaScript from PowerShell by using the Invoke-UDJavaScript cmdlet.

New-UDButton -Text 'Alert Me' -OnClick {
    Invoke-UDJavaScript -JavaScript 'alert("Hello!")'
}

API

Invoke-UDJavaScript

Name

Type

Description

Required

JavaScript

string

The JavaScript to invoke.

true

Toast

Show a toast

You can use the Show-UDToast cmdlet to create a toast message that will appear on the end user's webpage. It happens over a websocket and will show the toast immediately as it is called.

Show-UDToast -Message 'Hello, World!'

Hide a toast

Hides a toast based on the specified ID.

Show-UDToast -Message 'Hello, World!' -Id 'Toast' -Duration 30000

New-UDButton -Text 'Click' -OnClick {
    Hide-UDToast -Id 'Toast'
}

API

Show-UDToast

Name

Type

Description

Required

Message

string

The message to display

true

MessageColor

DashboardColor

The color of the message to display

false

MessageSize

string

The size of the message to display

false

Duration

int

The number of milliseconds to display the message. Defaults to 1000

false

Title

string

A title to display above the message.

false

TitleColor

DashboardColor

The color of the title.

false

TitleSize

string

The size of the title.

false

Id

string

The ID of this toast.

false

BackgroundColor

DashboardColor

The background color of the toast.

false

Theme

string

Light or dark theme.

false

Position

string

The position of the toast.

false

HideCloseButton

Switch

Hide the close button to prevent the user from hiding the toast.

false

CloseOnClick

Switch

Close the toast when it is clicked.

false

CloseOnEscape

Switch

Close the toast when escape is pressed.

false

ReplaceToast

Switch

Replace an existing toast if one is already shown. Otherwise, show both.

false

Balloon

Switch

Balloon style toast.

false

Overlay

Switch

Display an overlay behind the toast

false

OverlayClose

Switch

Allow the user to close the overlay

false

OverlayColor

DashboardColor

The color of the overlay.

false

TransitionIn

string

The transition to use when the toast is appearing.

false

TransitionOut

string

The transition to use when the toast is disappearing.

false

Broadcast

Switch

Show the toast to all users.

false

Hide-UDToast

Name

Type

Description

Required

Id

string

The ID of the toast to hide.

true

Redirect

You can redirect users to different pages using the Invoke-UDRedirect cmdlet. It happens over a websocket and will redirect as soon as the cmdlet is called.

Invoke-UDRedirect http://www.ironmansoftware.com

API

Invoke-UDRedirect

Name

Type

Description

Required

Url

string

The URL to redirect the user to.

true

OpenInNewWindow

Switch

Open the URL in a new window or tab.

false

Modal

You can open a modal using the Show-UDModal cmdlet. It will open as soon as you call it. You can include whatever components you like within the modal.

Managing Component State

You can manage component state dynamically by using the UDElement commands.

Getting Component State

You can receive the state of an element using Get-UDElement . The state will be returned as a hashtable. This is primarily useful for input components.

$Value = (Get-UDElement -Id 'txtExample').value

API

Get-UDElement

Name

Type

Description

Required

Id

string

The ID of the component to receive.

true

Setting Component State

Alternatively, you can set component state using Set-UDElement . You will need to specify an ID and a hashtable of properties to set on the component. All built in components support Set-UDElement.

New-UDTextbox -Id 'textbox'

New-UDButton -Text 'Click' -OnClick {
    Set-UDElement -Id 'textbox' -Properties @{
        Value = 'My Value'
    }
}

API

Set-UDElement

Name

Type

Description

Required

Id

string

The ID of the component to set.

true

Properties

Hashtable

Properties to set on the component

false

Broadcast

Switch

Set the properties of a component for all users.

false

Content

ScriptBlock

The content of the component to set.

false

Removing a Component

You can remove components from the page using Remove-UDElement . The component will no longer appear on the page.

Remove-UDComponent -Id 'txtExample'

API

Remove-UDElement

Name

Type

Description

Required

Id

string

The ID of the component to remove.

true

Adding a component

Add a child component to an existing parent component.

New-UDElement -Id 'myDiv' -Tag div

New-UDButton -Text 'Click' -OnClick {
    Add-UDElement -ParentId 'myDiv' -Content {
        New-UDTypography -Text 'Hi'
    }
}

API

Add-UDElement

Name

Type

Description

Required

ParentId

string

The ID of the component to add a child to.

true

Content

ScriptBlock

The child content to add.

true

Broadcast

Switch

Whether to add the child component to all users.

false

Clear a component

You can remove all the children components from an component by using Clear-UDElement.

New-UDElement -Id 'myDiv' -Tag div

New-UDButton -Text 'Click' -OnClick {
    Add-UDElement -ParentId 'myDiv' -Content {
        New-UDTypography -Text 'Hi'
    }
    Add-UDElement -ParentId 'myDiv' -Content {
        New-UDTypography -Text 'Hi'
    }
    Add-UDElement -ParentId 'myDiv' -Content {
        New-UDTypography -Text 'Hi'
    }
}

New-UDButton -Text 'Clear' -OnClick {
    Clear-UDElement -Id 'myDiv'
}

API

Clear-UDElement

Name

Type

Description

Required

Id

string

The ID of the component to clear.

true

Reloading a Component

Some components support reloading. You can trigger a reload of a component using Sync-UDElement.

New-UDDynamic -Id 'reloadMe' -Content {
    Get-Date
}

New-UDButton -Text 'Reload' -OnClick {
    Sync-UDElement -Id 'reloadMe'
}

API

Sync-UDElement

Name

Type

Description

Required

Id

string

The ID of the component to reload.

true

Broadcast

Switch

Whether to reload the component for all users.

false

Select a component

You can select a component with Select-UDElement.

New-UDElement -Id 'txt' -Tag input -Properties @{ type = text }

New-UDButton -Text 'Select' -OnClick {
    Select-UDElement -Id 'txt' -ScrollToElement
}

API

Select-UDElement

Name

Type

Description

Required

Id

string

The ID of the element to select

true

ScrollToElement

Switch

Whether to scroll the user's window to the element

false

Assets folder
Expandable Card

Read more about .

Modals here
configuration settings.
Windows Authentication
App Token
Security page