Sharepoint update metadata with Powershell problem with syntax? - powershell

I am unable to update the date and capital letters on my sharepoint via powershella script. All the others work, only this one doesn't work.
Can you help me? I have been tired for several hours.
My sharepoint metadata:
My script for update metadata in Sharepoint.
Thank you so much for help

I tested DATA_AUDYTU as Date field, NAZWA_SIECI as Single Line Text field in my side with the sample code snippet below, it's working as expected:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll"
#Set parameter values
$SiteURL="https://Tenant.sharepoint.com"
$FileRelativeUrl="/doc2/test.txt"
Try {
#Get Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
$File = $Ctx.web.GetFileByServerRelativeUrl($FileRelativeUrl)
$Ctx.Load($File)
$Ctx.Load($File.ListItemAllFields)
$Ctx.ExecuteQuery()
#Set Metadata of the File
$ListItem = $File.ListItemAllFields
$Listitem["NAZWA_SIECI"] = "TEST"
$Listitem["DATA_AUDYTU"]="12/24/2020"
$ListItem.Update()
$Ctx.ExecuteQuery()
Write-host -f Green "File's Metadata has been Updated Successfully!"
}
Catch {
write-host -f Red "Error Updating Metadata of the File!" $_.Exception.Message
}
Column details:

Related

How to download two different files in powershell

I have this simple script that is working and I'm able to download a csv file From my SharePoint site but I'm just wondering how can I modify it so that I can download another file that is located in another path and save it in the same local folder as soon as the first one is complete downloading?.
Basically this is what I'm trying to do
Download this first
$SourceFile="/sites/msteams/ReportsFull/OneDrive.csv"
Download this second, save in the same folder with the first one
$SourceFile="/sites/msteams/Shared%20Documents/OneDriveInventory/ActiveLitHoldWithOneDrive.csv"
\#Set parameter values
$SiteURL="https://companyName.sharepoint.com"
$SourceFile="/sites/msteams/ReportsFull/OneDrive.csv"
$TargetFile="C:\\Users\\AS\\Downloads\\New folder\\LegalDoc.docx"
Function Download-FileFromLibrary()
{
param
(
\[Parameter(Mandatory=$true)\] \[string\] $SiteURL,
\[Parameter(Mandatory=$true)\] \[string\] $SourceFile,
\[Parameter(Mandatory=$true)\] \[string\] $TargetFile
)
Try {
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Global:adminUPN, $Global:adminPwd)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
#sharepoint online powershell download file from library
$FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx,$SourceFile)
$WriteStream = [System.IO.File]::Open($TargetFile,[System.IO.FileMode]::Create)
$FileInfo.Stream.CopyTo($WriteStream)
$WriteStream.Close()
Write-host -f Green "File '$SourceFile' Downloaded to '$TargetFile' Successfully!" $_.Exception.Message
}
Catch {
write-host -f Red "Error Downloading File!" $\_.Exception.Message
}
}
\#Call the function to download file
Download-FileFromLibrary -SiteURL $SiteURL -SourceFile $SourceFile -TargetFile $TargetFile
You've got the right code, just need to call the function twice
$sourceFile1 = '/sites/msteams/ReportsFull/OneDrive.csv'
$targetFile1 = 'C:\\Users\\AS\\Downloads\\New folder\\LegalDoc.docx'
Download-FileFromLibrary -SiteURL $SiteURL -SourceFile $SourceFile1 -TargetFile $TargetFile1
$sourceFile2 = '/sites/msteams/Shared%20Documents/OneDriveInventory/ActiveLitHoldWithOneDrive.csv'
$targetFile2 = 'C:\\Users\\AS\\Downloads\\New Folder\\NewFile2.docx'
Download-FileFromLibrary -SiteURL $siteUrl -SourceFile $sourceFile2 -TargetFile $targetFile2```

SharePoint Online Sign in and password does not match issue in PowerShell

I'm trying to connect to SharePoint Online but I'm getting this error and not 100% sure why so I would be really appreciated if I can get any help or suggestion why it might be.
I believe it might have to do with my tenant using MFA so just wondering how can I connect/login using MFA?.
#Variables
$SiteURL = "https://companyName-my.sharepoint.com/personal/yzqpsn_nam_corp_m_com"
$ServerRelativeUrl= "documents/Testing"
Try {
#Get Credentials to connect
$Cred= Get-Credential
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get the web from URL
$Web = $Ctx.web
$Ctx.Load($Web)
$Ctx.executeQuery()
#Get the Folder object by Server Relative URL
$Folder = $Web.GetFolderByServerRelativeUrl($ServerRelativeUrl)
$Ctx.Load($Folder)
$Ctx.ExecuteQuery()
#Call the function to empty Folder
Empty-SPOFolder $Folder
#Delete the given Folder itself
Write-host -f Green "Deleting Folder:"$Folder.ServerRelativeUrl
$Folder.Recycle() | Out-Null
$Ctx.ExecuteQuery()
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}

Recursively Upload Large Files Via PNP-Powershell to Sharepoint Online Using Large Chunks

I have some files that I need to keep in sync with my SharePoint Document Library. The problem is some of the files are over the 250mb limit the code I currently have works but only for files under that 250mb limit. I cannot figure out how to upload the same recursive files I need to SharePoint using the same code and large chunks? It seems that what I need to integrate is option 3 of this page -> LARGE FILE HANDLING - OPTION 3 (StartUpload, ContinueUpload and FinishUpload) also it seems that if (Test-Path($topSPOFolder+"\"+$aFileName.FullName)) is not checking the target directory if a file exists to skip and move on. Any help is always appreciated.
$password = ConvertTo-SecureString "test123" -AsPlainText -Force
$username = "abc#def.com"
$cred = New-Object System.Management.Automation.PSCredential ($username, $password)
$makeUrl ="https://helloworld.sharepoint.com/sites/helloworld"
$sourcePath = "\\1.2.3.4\e$\MSI\packages\*\*.msi";
$topSPOFolder = "Shared Documents\packages\test";
# install pnp powershell..?
#Install-Module SharePointPnPPowerShellOnline
# connect to spo online
Connect-PnPOnline -Url $makeUrl -Credentials $cred
$fileNames = Get-ChildItem -Path $sourcePath -Recurse ;
foreach($aFileName in $fileNames)
{
if($aFileName.GetType().Name -ne "DirectoryInfo")
{
if (Test-Path($topSPOFolder+"\"+$aFileName.FullName))
{
Write-Host 'Skipping file, already downloaded' -ForegroundColor Yellow
return
} else {
$fn=$topSPOFolder;
Add-PnPFile -Path $aFileName.FullName -Folder $fn;
$fn=$null
}
}
}

Update Sharepoint wiki page's aspx using powershell

I have been trying to take a manual step out of a process where I clone a wiki page in sharepoint (done via powershell) and then manually go to the aspx in sharepoint designer and update the textpart's default value:
EX:
<WpNs0:SPSlicerTextWebPart runat="server" MaximumCharacters="255" DefaultValue="REPLACETHISVALUE" RequireSelection="False" FilterMainControlWidthPixels="0" FilterName="Text Filter" Title="Text Filter" FrameType="BorderOnly" SuppressWebPartChrome="False" Description="Filters the contents of Web Parts by allowing users to enter a text value." ...
I'm using the following function for building the context for my copy, and I'm wondering if there is a way to pass the final ASPX site URL and manipulate the content:
function Get-SharepointContext
{
Param(
[Parameter(Mandatory=$true)]
$siteUrl,
[Parameter(Mandatory=$false)]
$cred)
If(!$cred){$cred = get-credential -UserName "$ENV:Username#$env:USERDNSDOMAIN" -Message "Login"}
[string]$username = $cred.UserName
$securePassword = $cred.Password
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$ctx.RequestTimeOut = 1000 * 60 * 10;
$ctx.AuthenticationMode =[Microsoft.SharePoint.Client.ClientAuthenticationMode]::Default
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$ctx.Credentials = $credentials
$ctx.Load($ctx.Web)
$ctx.Load($ctx.Site)
$ctx.ExecuteQuery()
Return $ctx
}
Has anyone attempted this before or know of how I can actually do this?
We can change the web part properties using PnP PowerShell or CSOM code.
PnP:
#Get Current Context Site (Root)
$siteurl = "https://abc.sharepoint.com"
Connect-SPOnline -Url $siteurl
$ctx = Get-SPOContext
#Get Web Part ID
webpart = Get-SPOWebPart -ServerRelativePageUrl "/Pages/PnPPage.aspx" -Identity "Text Filter"
$webpartId = $webpart.Id
# Update WebPart
Set-SPOWebPartProperty -ServerRelativePageUrl "/Pages/PnPPage.aspx" -Identity $webpartId -Key Height -Value 500
CSOM:
function Change-WebPart {
#variables that needs to be set before starting the script
$siteURL = "https://spfire.sharepoint.com"
$userName = "mpadmin#spfire.onmicrosoft.com"
$webURL = "https://spfire.sharepoint.com"
$relativePageUrl = "/SitePages/Home.aspx"
# Let the user fill in their password in the PowerShell window
$password = Read-Host "Please enter the password for $($userName)" -AsSecureString
# set SharePoint Online credentials
$SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
# Creating client context object
$context = New-Object Microsoft.SharePoint.Client.ClientContext($webURL)
$context.credentials = $SPOCredentials
#get Page file
$page = $context.web.getFileByServerRelativeUrl($relativePageUrl)
$context.load($page)
#send the request containing all operations to the server
try{
$context.executeQuery()
}
catch{
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
#use the WebPartManger to load the webparts on a certain page
$webPartManager = $page.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$context.load($webPartManager.webparts)
#send the request containing all operations to the server
try{
$context.executeQuery()
}
catch{
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
#loop through all WebParts to get the correct one and change its property
foreach($webPartDefinition in $webpartmanager.webparts){
$context.Load($webPartDefinition.WebPart.Properties)
#send the request containing all operations to the server
try{
$context.executeQuery()
}
catch{
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
#Only change the webpart with a certain title
if ($webPartDefinition.WebPart.Properties.FieldValues.Title -eq "Documents")
{
$webPartDefinition.webpart.properties["Title"] = "My Documents"
$webPartDefinition.SaveWebPartChanges()
}
}
}
Change-WebPart
Reference:
Update/Delete WebParts On SharePoint Pages Using PnP PowerShell
Editing Web Part properties with PowerShell CSOM in SharePoint

How to use PowerShell to download files from SharePoint?

I've used the following sites to help me get this far and to troubleshoot.
Download file from SharePoint
How to download newest file from SharePoint using PowerShell
Mike Smith's Tech Training Notes SharePoint, PowerShell and .Net!
Upload file to a SharePoint doc library via PowerShell
Download latest file from SharePoint Document Library
How to iterate each folders in each of the SharePoint websites using PowerShell
PowerShell's Get-ChildItem on SharePoint Library
I am trying to download random files from SharePoint folder, and I have it working for when I actually know the file name and extension.
Working code with name and extension:
$SharePoint = "https://Share.MyCompany.com/MyCustomer/WorkLoad.docx"
$Path = "$ScriptPath\$($CustomerName)_WorkLoad.docx"
#Get User Information
$user = Read-Host "Enter your username"
$username = "$user#MyCompany"
$password = Read-Host "Enter your password" -AsSecureString
#Download Files
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($UserName, $Password)
$WebClient.DownloadFile($SharePoint, $Path)
However, I don't seem to be able to figure out how to do it with multiple files of unknown names or extensions.
I have tried mapping a drive, only to end up with "drive mapping failed" & "The network path was not found." errors:
$SharePoint = Read-Host 'Enter the full path to Delivery Site'
$LocalDrive = 'P:'
$Credentials = Get-Credential
if (!(Test-Path $LocalDrive -PathType Container)) {
$retrycount = 0; $completed = $false
while (-not $completed) {
Try {
if (!(Test-Path $LocalDrive -PathType Container)) {
(New-Object -ComObject WScript.Network).MapNetworkDrive($LocalDrive,$SharePoint,$false,$($Credentials.username),$($Credentials.GetNetworkCredential().password))
}
$Completed = $true
}
Catch {
if ($retrycount -ge '5') {
Write-Verbose "Mapping SharePoint drive failed the maximum number of times"
throw "SharePoint drive mapping failed for '$($SharePoint)': $($Global:Error[0].Exception.Message)"
} else {
Write-Verbose "Mapping SharePoint drive failed, retrying in 5 seconds."
Start-Sleep '5'
$retrycount++
}
}
}
}
I've also used the following code with similar results or no results at all.
#Get User Information
$user = Read-Host "Enter your username"
$username = "$user#MyCompany"
$password = Read-Host "Enter your password" -AsSecureString
#Gathering the location of the Card Formats and Destination folder
$Customer = "$SharePoint\MyCustomer"
$Products = "$Path\$($CustomerName)\Products\"
#Get Documents from SharePoint
$credential = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-PSDrive -Credential $credential -Name "A" -PSProvider "FileSystem" -Root "$SharePoint"
net use $spPath #$password /USER:$user#corporate
#Get PMDeliverables file objects recursively
Get-ChildItem -Path "$Customer" | Where-Object { $_.name -like 'MS*' } | Copy-Item -Destination $Products -Force -Verbose
Without defined "input parameters", it's not exactly clear the full solution you need so I'll provide a few snippets of PowerShell that should be of use based on what you've described.
I'll spare you the basics of the various OOTB functions (i.e. Get-SPWeb, etc) though can provide those details as well if needed. I've also been overly explicit in the scripting, though know some of these lines could be chained, piped, etc to be made shorter & more efficient.
This example will iterate over the contents of a SharePoint Library and download them to your local machine:
$Destination = "C:\YourDestinationFolder\ForFilesFromSP"
$Web = Get-SPWeb "https://YourServerRoot/sites/YourSiteCollection/YourSPWebURL"
$DocLib = $Web.Lists["Your Doc Library Name"]
$DocLibItems = $DocLib.Items
foreach ($DocLibItem in $DocLibItems) {
if($DocLibItem.Url -Like "*.docx") {
$File = $Web.GetFile($DocLibItem.Url)
$Binary = $File.OpenBinary()
$Stream = New-Object System.IO.FileStream($Destination + "\" + $File.Name), Create
$Writer = New-Object System.IO.BinaryWriter($Stream)
$Writer.write($Binary)
$Writer.Close()
}
}
This is pretty basic; the variables up top are where on your local machine you wish to store the download files ($Destination), the URL of your SharePoint Site/Web ($Web) and the name of the Document Library (Your Doc Library Name).
The script then iterates through the items in the Library (foreach ($DocLibItem in $DocLibItems) {}), optionally filters for say items with a .docx file extension and downloads each to your local machine.
You could customize this further by targeting a specific sub-folder within the Doc Library, filter by metadata or properties of the Docs or even iterate over multiple Sites, Webs and/or Libraries in one script, optionally filtering those based on similar properties.