Upload file to SharePoint

Product: PowerShell Universal
Version: 2.3.1

I am trying to change my code from a v2 dashboard to allow me to upload a file to SharePoint. Here is a snippet of my code:

param ( $DocType, $File, $Description, $ProjectManagement )

$fileStream = [IO.File]::Create($File.FileName)
$stream = $File.OpenReadStream()
$stream.CopyTo($fileStream)
$fileStream.Dispose()
$stream.Dispose()
$FileName = $File.FileName
#using custom connect to SharePoint
Connect-O365Service -SharePointPNP “https://tenant.sharepoint.com/sites/THQCentral
$Upload = Add-PnPFile -Path $($File.FileName) -Folder “Application Inventory/$DocType” -Values @{ VendorName = “$VendorName”; Description = “$Description”; Title = $($file.FIleName); Editor = $Session:EndUserUPN; Author = $Session:EndUserUPN; }

I’m not sure what I need to do to get the file stream and then upload it using Add-PNPFile. Any recommendations for me?

In v3, the file is provided as a base64 encoded string of data.

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)
$Upload = Add-PnPFile -Path "$env:temp\$($Data.Name)" -Folder “Application Inventory/$DocType” -Values @{ VendorName = “$VendorName”; Description = “$Description”; Title = $($file.FIleName); Editor = $Session:EndUserUPN; Author = $Session:EndUserUPN;
}

In 2.4 (out next week), we’ve enhanced this so it all that won’t be necessary. You’ll be able to do something like this.

New-UDUpload -Text 'Upload Image' -OnUpload {
     $Upload = Add-PnPFile -Path $EventData.FileName -Folder “Application Inventory/$DocType” -Values @{ VendorName = “$VendorName”; Description = “$Description”; Title = $($file.FIleName); Editor = $Session:EndUserUPN; Author = $Session:EndUserUPN;
}

Thanks for the work on this. I’m looking forward to trying out 2.4 next.

1 Like