Uploading documents to Sharepoint with Powershell - - powershell

The script exports to a CSV and the files need to be uploaded to SharePoint online.
The export works perfectly
Document is renamed to exclude "#mycompany.com"
The error I get is :
Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (403) Forbidden."
At line:46 char:9
+ $Context.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Get-ChildItem 'c:\users\xxxx\downloads' -Filter *.csv | % {
$eachFile =Get-ChildItem $Outputfile -Filter *.csv
$eachFile | ForEach-Object{
#Upload Variables - Admin Heidi
[string]$AdminName = "hxxn#xxx.onmicrosoft.com"
[string]$AdminPassword = "Cxx1"
#Upload Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $AdminPassword -AsPlainText -Force
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $AdminName, $(convertto-securestring $AdminPassword -asplaintext -force)
$AdminSiteURL="https://nrcl.sharepoint.com"
#Site report will be stored on SharePoint
$SiteURL="https://xxx.sharepoint.com/sites/nrg/"
$LibraryName="Audit History"
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Context.Credentials = $Credentials
#Get the Library
$Library = $Context.Web.Lists.GetByTitle($LibraryName)
#Get the file from c:/
$FileStream = ([System.IO.FileInfo] (Get-Item $OutputFile)).OpenRead()
#Get File Name from source file path
$SourceFileName = Split-path $eachFile -leaf
#sharepoint online upload file powershell
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $SourceFileName
$FileUploaded = $Library.RootFolder.Files.Add($FileCreationInfo)
#powershell upload single file to sharepoint online
$Context.Load($FileUploaded)
#######--------fails after this line ---------------#####
$Context.ExecuteQuery()
#Close file stream
$FileStream.Close()
write-host "File has been uploaded!"
}

Related

Powershell uploading files to SharePoint : Exception calling "ExecuteQuery" with "0" argument(s) error

I want to upload all .csv files from a C:/ to SharePoint. The script runs up to $Ctx.ExecuteQuery() and returns this error. I am able to run other PowerShell scripts on the site, and am the site owner, I suspect it is something other than access privileges.
Where do I start looking ?
Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (403) Forbidden."
+ $Ctx.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Get-ChildItem "c:\users\xxx\downloads" -Filter *.csv | % {
$eachFile =Get-ChildItem "c:\users\xxxx\downloads\" -Filter *.csv
$eachFile | ForEach-Object{
#parameters
$SiteURL = "https://xxx.sharepoint.com/sites/nrg"
$LibraryName="Audit History"
$UserName = "xxxx#x.onmicrosoft.com"
$Password = "xx"
$SecurePassword= $Password | ConvertTo-SecureString -AsPlainText -Force
#Setup the Context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
$Ctx.Credentials = $Credentials
#Get the Library
$Library = $Ctx.Web.Lists.GetByTitle($LibraryName)
#Get the file from disk
$FileStream = ([System.IO.FileInfo] (Get-Item $OutputFile)).OpenRead()
#Get File Name from source file path
$SourceFileName = Split-path $eachFile -leaf
#sharepoint online upload file powershell
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $SourceFileName
$FileUploaded = $Library.RootFolder.Files.Add($FileCreationInfo)
#powershell upload single file to sharepoint online
$Ctx.Load($FileUploaded)
$Ctx.ExecuteQuery()
#Close file stream
$FileStream.Close()
write-host "File has been uploaded!"
}
}
Solution was to remove the Credentials to before the ForEach-Object.

Getting below error on running PowerShell script

I am using one PowerShell script to download content (a zip file) from a website which requires credentials to get authenticated for the website. Also, have used proxy and proxy credentials since it is an authenticated proxy. I am getting an error which I have pasted below.
I have tried giving the proxy and proxy credentials but no luck.
I have bypassed the execution policy using Powershell -ExecutionPolicy Bypass.
When I try accessing the website from my browser then I am able to access the zip file.
Please find the code snippet below:
#Path to Save data
$tipath = "C:\Somepath"
$localpath = "\somefile.zip"
$timepath = "\Zip_file.txt"
$unzippath = "\Someotherpath"
$storepath = $tipath + $localpath
$remotefilepath = $tipath + $timepath
$unzipfolder = $tipath + $unzippath
# Create Folder If Not Exists #
$FolderToCreate = $tipath
if (!(Test-Path $FolderToCreate -PathType Container)) {
New-Item -ItemType Directory -Force -Path $FolderToCreate
}
#Downloading File #
$username = "username"
$password = "Password" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $password)
$secPasswd = "password123" | ConvertTo-SecureString -AsPlainText -Force
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential("domain\user", $secPasswd)
# get remote file info
Invoke-WebRequest -Proxy "http://x.x.x.x:8080" -ProxyCredential $myCreds -Uri "https://somewebsite/checksum.txt" -OutFile $remotefilepath -Credential $cred
$remotefile = Get-Content -Path $remotefilepath
Write-Host Remote File Hash : $remotefile
# if the file exists already
if (Test-Path $storepath) {
# get local file info
$localfile = (Get-FileHash $storepath -Algorithm SHA256).Hash
Write-Host Local File Hash : $localfile
# if the remote file is newer than the local file
if ($remotefile -ne $localfile) {
Invoke-WebRequest -Proxy "http://x.x.x.x:8080" -ProxyCredential $myCreds -Uri "https://somewebsite/checksum.txt" -OutFile $remotefilepath -Credential $cred
Invoke-WebRequest -Proxy "http://x.x.x.x:8080" -ProxyCredential $myCreds -Uri "https://somewebsite/somezipfile.zip" -OutFile $storepath -Credential $cred
This code should check the hash and download directly download the zip file from the website and unzip it.
If it can download in the zip file then the later part I can troubleshoot.
PS C:\Users\Administrator\Desktop> powershell -ExecutionPolicy ByPass -File C:\Users\Administrator\Desktop\mypowershell.ps1
powershell : Invoke-WebRequest : .?? ??? ?????? ???????? ??? ????? ?????
At line:1 char:1
+ powershell -ExecutionPolicy ByPass -File C:\Users\Administrator\Desktop\mypowershell.p ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Invoke-WebReque...??? ????? ?????:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
The site you are trying to access contains content that is prohibited.
If you believe the website you are trying to access does not contain any such
content, please click here.
Above is the error I am getting.

Getting Error while running Powershell Script to add Site Content Link

$adminUPN="xxxxx#Home500.onmicrosoft.com"
$orgName="xxxxxx"
$userCredential = Get-Credential -UserName $adminUPN -Message "Type the password."
Connect-SPOService -Url https://$orgName-admin.sharepoint.com -Credential $userCredential
# Begin the process
$loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
$loadInfo3 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")
#Add SharePoint PowerShell SnapIn if not already added
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell" -EA SilentlyContinue
}
CLS
$StartTime = $(get-date -f F)
$timeStamp = Get-Date -format "MM_dd_yy_hh_mm"
#Get Current folder file path
$invocation = (Get-Variable MyInvocation).Value
$currentPath = Split-Path $invocation.MyCommand.Path
$currentPath = $currentPath + "\"
#Config File Path
#$configPath = $currentPath + "Config.xml"
$configPath = "C:\Users\EMXBG\Downloads\Script_AddSiteContent\Script_AddSiteContent\Config.xml"
#fetching details from config.xml
[xml]$configXML = Get-Content $configPath
$inputFileName = [string]$configXML.Config.Constants.InputFileName
$errorFileName = [string]$configXML.Config.Constants.ErrorFileName
$outFilePath = [string]$configXML.Config.Constants.OutputFileName
#Source File path containing list of WebApplications in a farm.
$webApplFilePath = $currentPath + $inputFileName
#Output File path of the exported AD Security Groups with Site collection and Group Name details.
$sitesFilePath = $currentPath + $outFilePath
#File path of the file which will capture all the errors while running the script.
$errorPath = $currentPath + $errorFileName + $timeStamp + ".csv"
# Creating object to write logging into the error and output file
$sitesFile = New-Object System.IO.StreamWriter $sitesFilePath
$errorfile = New-Object System.IO.StreamWriter $errorPath
# Fetching SharePoint WebApplications list from a CSV file
$CSVData = Import-CSV -path $webApplFilePath
$sitesFile.WriteLine("SiteCollectionName"+","+"SiteURL")
$errorfile.WriteLine("SiteURL"+"`t"+"ExceptionLevel"+"`t"+"ExceptionMsg");
addSiteContentLink $CSVData
$sitesFile.Close()
$errorfile.Close()
# Function to add Site Content link in thes where it does not exists
function addSiteContentLink($CSVData)
{
try
{
$compareText = "Site contents"
foreach ($row in $CSVData)
{
$webUrl = $row.webUrl
#$username = $row.username
#$password = $row.password
#Get Web Application and credentials
#$securePass = ConvertTo-SecureString $password -AsPlainText -Force
#$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl)
#$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePass)
# Get the collection of navigation nodes from the quick launch bar
#$web = $ctx.Web
$quickLaunch = $webUrl.Navigation.QuickLaunch
try
{
#Iterate through each iten in Quick launch menu
foreach($quickLaunch in $web)
{
if ($quickLaunch -contains $compareText)
{
Write-Host "Site Content link Exists!"
}
else
{
# Add a new navigation node
$navNode = New-Object Microsoft.SharePoint.Client.NavigationNodeCreationInformation
$navNode.AsLastNode = $true
$navNode.Title = "Site Contents"
$navNode.Url = $web.Url + "_layouts/15/viewlsts.aspx"
$navNode.IsExternal = $false
$ctx.Load($quickLaunchColl.Add($navNode))
$ctx.ExecuteQuery()
}
}
}
catch
{
Write-Host("Exception at Site Collection Url :" + $currentSite.Url)
$errorfile.WriteLine($currentSite.Url+"`t"+"`t"+$_.Exception.Message)
}
}
#Export Data to CSV
$sitesCollection | export-csv $sitesFile -notypeinformation
$site.Dispose()
}
catch
{
Write-Host("Exception at Site Collection Url :" +$currentSite.Url)
$errorfile.WriteLine($currentSite.Url+"`t"+"SiteCollection"+"`t"+$_.Exception.Message)
}
}
Below is the Error I am getting
Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null.
At C:\Users\EMXBG\Downloads\Script_AddSiteContent\Script_AddSiteContent\ScriptForSiteContentLinkQuickLaunch - Copy.ps1:126 char:29
+ $sitesCollection | export-csv $sitesFile -notypeinformation
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand
This error is probably because $sitesCollection is empty/null. I can't see anything in your code that assigns it a value.

Uploading to SharepointOnline subfolder using Powershell

it seems like I can upload a file to SPO's Site Collection URL but not the subfolder. For example, I can upload to "https://xyz.sharepoint.com/sites/Reporting", but not "https://xyz.sharepoint.com/sites/Reporting/Sales". Here's the working code's relevant bit:
$Username = "me#domain.com"
$Password = "Password"
$SiteCollectionUrl = "https://xyz.sharepoint.com/sites/Reporting"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$DocLibName = "Sales"
$Folder="C:\MySalesFolder"
Function Get-SPOCredentials([string]$UserName,[string]$Password)
{
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
return New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
}
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteCollectionUrl)
$Context.Credentials = Get-SPOCredentials -UserName $UserName -Password $Password
#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List)
$Context.ExecuteQuery()
#Upload file
Foreach ($File in (dir $Folder -File))
{
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
$Upload = $List.RootFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
I tried to hardcode "/Sales" subfolder but no luck. Anyone can point me in the right direction?
According to Trying to upload files to subfolder in Sharepoint Online via Powershell You will need to amend the FileCreationURL:
$FileCreationInfo.URL = $List.RootFolder.ServerRelativeUrl + "/" + $FolderName + "/" + $File.Name
I believe you just need to prepend $File.Name with the Folder path to your root directory.
Web.GetFolderByServerRelativeUrl Method:
Alternatively to attempting to Upload via List.RootFolder..., you can use the "GetFolderByServerRelativeUrl" method to get your Target Folder
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List.RootFolder)
$Context.ExecuteQuery()
$FolderName = "Sales"
$TargetFolder = $Context.Web.GetFolderByServerRelativeUrl($List.RootFolder.ServerRelativeUrl + "/" + $FolderName);
Then for upload you would use
$FileCreationInfo.URL = $File.Name
$UploadFile = $TargetFolder.Files.Add($FileCreationInfo)
$Context.Load($UploadFile)
$Context.ExecuteQuery()

Having trouble include all child items when moving files from local machine to fileserver using Powershell

I want to upload these local files from system to the fileserver but if i try to use Get-ChildItem I get this message:
Cannot convert argument "address", with value: "System.Object[]", for
"Downl convert the "System.Object[]" value of type "System.Object[]"
to type "Syste At C:\Users\Administrator\Desktop\MOVEFILES2.ps1:23
char:1
+ $WebClient.DownloadFile($Source, $Dest)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Here is the working script. I want to modify so that it pulls from that path and not having to specify the file name.
#UPLOAD FILES FROM SOURCE TO File server
# Specify the path to the documents you want to upload from the local machine...
$Source = "C:\Users\Administrator\Desktop\SourceFolder\Goober.docx"
$Dest = "\\10.112.4.111\xx\xxxxx\xxxx xxxxx\xxxx\Goober.docx"
# Specify Username and Password
$Username = "domain\user"
$Password = "xxxxxxxxxxx"
# Generate System.Net.WebClient object
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$WebClient.DownloadFile($Source, $Dest)
I am unable to test this because of the credential thing, but i think this is a simplified version of what you're trying to achieve.
It should Copy all the items in the Sourcefolder to the Destination, Bassicly it maps a drive and then copies it all and then removes the Drive.
$sourceFolder = "C:\Users\Administrator\Desktop\SourceFolder"
$Destination = "\\10.112.4.111\xx\xxxxx\xxxx xxxxx\xxxx"
$secpw = ConvertTo-SecureString "Password" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential("Username",$secpw)
New-PSDrive -Name "Dest" -PSProvider FileSystem -Root $dest -Credential $creds
Copy-Item $sourceFolder "Dest:\" -Recurse
Remove-PSDrive -Name "Dest"