Upload files to PowerShell Universal

Image Description

Daily PowerShell #54

Daily PowerShell PowerShell Universal

December 8, 2021

quote Discuss this Article

In this post, we’ll look at how to upload files to PowerShell Universal.

Upload Files to an API

Files can be uploaded directly to APIs and the contents of the file can be accessed via the $Data variable. The $Data variable contains a byte array of the contents of the file.

The following endpoint accepts an upload, writes the file to the temp directory and returns the file name to the client.

New-PSUEndpoint -Url '/file' -Method Post -Endpoint {
    $TempFile = [IO.Path]::GetTempFileName()
    [IO.File]::WriteAllBytes($TempFile, $Data)

This endpoint can be called like this.

"Hello, World!" | Out-File .\helloWorld.txt
Invoke-WebRequest 'http://localhost:5000/file' -Method POST -InFile .\helloWorld.txt

Upload Files with New-UDUpload

You can use the New-UDUpload component to upload and process files in a dashboard. Within a dashboard, specify the -Text and -OnUpload parameters of New-UDUpload.

The following example accepts a CSV upload, imports the CSV data and displays it in a table. The $Body parameter contains properties such as the RawData, Name, FileName and ContentType.

New-UDDashboard -Title 'Upload' -Content {
  New-UDUpload -Text 'Upload CSV' -OnUpload {
      $Session:CSV = Import-CSV $Body.FileName
      Sync-UDElement -Id 'CSV'

  New-UDDynamic -Id 'CSV' -Content {
      if ($Session:CSV) {
        New-UDTable -Data $Session:CSV

The below image was generated by a CSV of service names and statuses.

Get-Service | Select-Object name, Status | Export-Csv .\services.csv

After uploading the services.csv, the file is imported and used to populate the table.

Upload Files in a Form

You can also use the New-UDUpload component within New-UDForm. The uploaded file will be included as part of the form data.

New-UDDashboard -Title 'Upload' -Content {
    New-UDForm -Content {
        New-UDTextbox -Id 'Description' -Label 'Description'
        New-UDUpload -Id 'File' -Text 'Upload CSV'
    } -OnSubmit {
        Show-UDToast "You uploaded file $($EventData.File.Name) with the description $($EventData.Description)."

The form will contain a textbox and an upload button. Submitting the form will include the file name and description entered into the form.