Unable to create SharePoint online list items using Power shell - powershell

I want to add list items inside a SharePoint online list, so i run this command:-
$SiteUrl = "https://***.sharepoint.com/sites/t"
$ListName= "Child2"
Connect-PnPOnline -Url $SiteUrl -UseWebLogin
$Ctx = Get-PnPContext
#Get the list Item
$List=$Ctx.Web.Lists.GetByTitle($ListName)
$Import = Import-Csv -Path "C:\CSV\finaldelta3.csv"
for ($counter=0; $counter -lt $Import.Length; $counter++){
$ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$ListItem = $List.AddItem($ListItemInfo)
#Set Column Values
$ListItem["Title"] = "Hello World!"
#Apply changes to list
$ListItem.Update()
$Ctx.ExecuteQuery()
}
now on one tenant, i will not get any error, but the list item will not get created, while on another tenant i got this exception and also the item will not get created as well:-
Cannot convert argument "parameters", with value:
"Microsoft.SharePoint.Client.ListItemCreationInformation", for
"AddItem" to type
"Microsoft.SharePoint.Client.ListItemCreationInformation": "Cannot
convert the "Microsoft.SharePoint.Client.ListItemCreationInformation"
value of type
"Microsoft.SharePoint.Client.ListItemCreationInformation" to type
"Microsoft.SharePoint.Client.ListItemCreationInformation"." At line:4
char:1 + $ListItem = $List.AddItem($ListItemInfo) +
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Cannot index into a null array. At line:7 char:1 + $ListItem["Title"] = "Hello World!"#$Import[$counter].'Caller Info' #
... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
You cannot call a method on a null-valued expression. At line:10 char:1 + $ListItem.Update() + ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
so any idea what is going on?
Thanks

Have you tried updating your SPO Management Shell:
https://www.microsoft.com/en-in/download/details.aspx?id=35588
And/or the SPO Client Component SDK:
https://www.microsoft.com/en-us/download/details.aspx?id=42038
I'm not sure if it is required by PnPOnline, but with SPOServices you need to load the assembly as well:
Add-Type -Path "$Env:ProgramFiles\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "$Env:ProgramFiles\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "$Env:ProgramFiles\SharePoint Client Components\16.0\Assemblies\Microsoft.Online.SharePoint.Client.Tenant.dll"
Or alternatively:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Online.SharePoint.Client.Tenant") | Out-Null
Personally, I start my script with
#Requires -Module Microsoft.Online.SharePoint.PowerShell

Related

Upload file to SharePoint

I would like to create a program in PowerShell to upload files to Sharepoint on schedule (using Task Scheduler)
I was looking for solution and I found this interesting article.
Based on this I wrote this script below:
Import-Module Microsoft.Online.Sharepoint.Powershell -DisableNameChecking;
(System.Reflection.Assembly)::LoadWithPartialName("System.IO.MemoryStream")
Clear-Host
$cred = Get-Credential "emailaddress#domain.com"
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($cred.Username, $cred.Password)
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext("https://")
$clientCOntext.Credentials = $credentials
if (!$clientContext.ServerObjectIsNull.Value) {Write-host "Connected to site" -ForegroundColor Green}
Function UploadFileToLibrary(){
$docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
$clientContext.Load($docLib);
$clientContext.ExecuteQuery();
$rootFolder = $docLib.RootFolder
$Folder = "\\10.x.x.x\xpbuild$\IT\Level0\scresult\Upload";
$FilesInRoot = Get-ChildItem - Path $Folder | ? {$_.psIsContainer -eq $False}
Foreach ($File in ($FilesInRoot))
{
$startDTM = (Get-Date)
}Write-Host "Uploading File" $File.Name "to" $docLib.Title -ForegroundColor Blue
UploadFile $rootFolder $File $false
$endDTM = (Get-Date)
Write-Host "Total Elapsed Time : $(($endDTM-$startDTM).totalseconds) seconds"
}
Function UploadFile ($SPListFolder, $File, $CheckInRequired){
$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
$UploadedFile = $SPListFolder.Files.Add($FileCreationInfo)
If($CheckInRequired){
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
If($uploadedFile.CheckOutType -ne "none"){
$UploadedFile.CheckIn("Checked in by Administrator", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
}
}
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
}
UploadFileToLibrary
When I tried to execute this I see that connection is active but I got an error:
Method invocation failed because [Microsoft.SharePoint.Client.List] does not contain a method named 'op_Subtraction'.
At C:\PowerShell\UploadSharepoint.ps1:11 char:1
+ $docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Subtraction:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Cannot find an overload for "Load" and the argument count: "1".
At C:\PowerShell\UploadSharepoint.ps1:12 char:1
+ $clientContext.Load($docLib);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Exception calling "ExecuteQuery" with "0" argument(s): "List 'IT Documents' does not exist at site with URL 'https://'."
At C:\PowerShell\UploadSharepoint.ps1:13 char:1
+ $clientContext.ExecuteQuery();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ServerException
I cannot tell if any new problem occur once you fix that one, but given that the 2nd and 3rd error is caused by incorrect assignment of $docLib variable, changing - to =should resolve these three:
HERE |
$docLib = $clientContext.Web.Lists.GetByTitle("IT Documents");
# Below uses $docLib so it cannot be executed properly unless $docLib is assigned correct value
$clientContext.Load($docLib);
# And below fails as the above is not executed successfully
$clientContext.ExecuteQuery();

Recursively Changing File extensions from .docx and .pdf to .txt

$findPDF = Get-ChildItem -Path "$fileDrive" -Filter *.pdf -r
$findDOCX = Get-ChildItem -Path "$fileDrive" -Filter *.docx -r
$pullFiles += $findPDF
$pullFiles += $findDOCX
#[array]$pullFiles
#$pullFiles.length
$holdPath = #()
for($i = 0; $i -lt $pullFiles.length; $i++){
#get the full path of each document
$fullPath = Resolve-Path $pullFiles.fullname[$i]
#stores the information in a global array
$holdPath += $fullPath.path
}
#$holdPath
<#
.DESCRIPTION Uses the word.APPLICATION object to open and convert the word documents into .txt.
#>
#https://stackoverflow.com/questions/13402898/how-can-i-use-powershell-to-save-as-a-different-file-extension
#wdFormatDOSTextLineBreaks 5 Microsoft DOS text with line breaks preserved.
foreach($fi in $holdPath){
$Doc = $word.Documents.Open($fi.name)
$NameDOCX = ($Doc.name).replace("docx","txt")
$Doc.saveas([ref] $NameDOCX, [ref] 5)
$NamePDF = ($Doc.name).replace("pdf","txt")
$Doc.saveas([ref] $NamePDF, [ref] 5)
$Doc.close()
}
The problem Statement
The program needs to get any pdf and doc/x file and convert it to a .txt file. Now, I am able to recursively search and pull all .docx and .pdf documents from the file system. Now, I just need to convert them.
The Error
You cannot call a method on a null-valued expression.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:38 char:2
+ $Doc = $word.Documents.Open($fi.name)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:40 char:2
+ $NameDOCX = ($Doc.name).replace("docx","txt")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
[ref] cannot be applied to a variable that does not exist.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:41 char:2
+ $Doc.saveas([ref] $NameDOCX, [ref] 5)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (NameDOCX:VariablePath) [], RuntimeException
+ FullyQualifiedErrorId : NonExistingVariableReference
You cannot call a method on a null-valued expression.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:43 char:2
+ $NamePDF = ($Doc.name).replace("pdf","txt")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
[ref] cannot be applied to a variable that does not exist.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:44 char:2
+ $Doc.saveas([ref] $NamePDF, [ref] 5)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (NamePDF:VariablePath) [], RuntimeException
+ FullyQualifiedErrorId : NonExistingVariableReference
You cannot call a method on a null-valued expression.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:46 char:2
+ $Doc.close()
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
$word variable are not initialized, and your are complicated for Nothing (without offense you). Modify all your script like this :
$fileDrive ="C:\temp"
$word = new-object -ComObject Word.Application
Get-ChildItem -Path $fileDrive -file -r -Include "*.docx", "*.pdf" | %{
$Doc = $word.Documents.Open($_.FullName)
$NameDOC = $_.FullName.replace(".docx",".txt").replace(".pdf",".txt")
$Doc.saveas([ref] $NameDOC, [ref] 5)
$Doc.close()
}
$word.Quit()
But i have doubt on convert pdf to .txt with Word application like this... I think you should use itextsharp libray like here

connecting to sharepoint oniline using Powershell : Cannot find an appropriate constructor for type Microsoft.SharePoint.Client.ClientContext

Hi I am trying to connect to sharepoint online and publish calender using the data from a SQL Table and I am getting the following exception , please advise.The same code works fine with slight modification on a on prem sharepoint server I have added sharepointonline for the authentication but it is failing with the error.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
$username = "XXXXXX"
$url = "XXXXXX"
$pass= cat C:\text.txt | ConvertTo-SecureString
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username,$Pass)
$Context.Credentials = $Creds
$web = $Context.Web
$Context.Load($web)
$Context.Load($splist)
$splist = $Context.web.Lists.GetByTitle("XXXX")
$ItemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
####Some Data coming from SQL Server DB into $table########
$table = $result.Tables[0];
foreach ($row in $table)
{
Write-Host $row.Item("changetitle") $row.Item("status");
$Item1 = $splist.AddItem($ItemCreateInfo)
$Item1["Title"] = "test"
Write-host $date
$Item1.Update()
$Context.ExecuteQuery()
}
Exception
New-Object : A constructor was not found. Cannot find an appropriate
constructor for type Microsoft.SharePoint.Client.ClientContext. At
C:\MOSSLibrary\testingpublish.ps1:15 char:12 + $Context = New-Object
Microsoft.SharePoint.Client.ClientContext($site ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'Credentials' cannot be found on this object. Verify
that the property exists and can be set. At
C:\MOSSLibrary\testingpublish.ps1:17 char:1 + $Context.Credentials =
$Creds + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:20 char:1 + $Context.Load($web) +
~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:21 char:1 + $Context.Load($splist)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:22 char:1 + $splist =
$Context.web.Lists.GetByTitle("XXXXXXX") +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It seems Assemblies are not loading correctly.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
Instead of above, try following
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll"
PS: Make sure that C:\MOSSLibrary\ contains following two .dll's
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll

Powershell 3: Convert Word to PDF

I'm fairly new to Powershell and found the following script on the web: (I've modified it for my project)
# Acquire a list of DOC files in a folder
$Word = New-Object -ComObject word.application
$formats = "Microsoft.Office.Interop.Word.WdSaveFormat" -as [type]
$Word.visible = $false
$fileTypes = "*.docx","*doc"
$complyDocPath = "i:\2014\COMPLY\DOC\"
$complyPDFPath = "i:\2014\COMPLY\PDF\"
$Files=GET-CHILDITEM $complyDocPath -include $fileTypes
Foreach ($File in $Files) {
# open a Word document, filename from the directory
#$Doc=$Word.Documents.Open($File.fullname)
$Doc=$Word.Documents.Open($File)
# Swap out .DOCX/.DOC with 5.PDF in the Filename
$fileName = [system.io.path]::GetFileNameWithoutExtension($File)
$destPath = Join-Path -path $complyPDFPath -childpath ($fileName +"5.PDF")
Add-Type -AssemblyName "Microsoft.Office.Interop.Word"
"Converting $File to pdf ... $destPath"
# Save this File as a PDF in Word 2010/2013
$Doc.SaveAs($destPath, $formats::wdFormatPDF)
$Doc.Close($false)
}
$Word.Quit()
I get the following errors:
Argument: '2' should be a System.Management.Automation.PSReference. Use [ref].
At line:25 char:5
+ $Doc.SaveAs($destPath, $formats::wdFormatPDF)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : NonRefArgumentToRefParameterMsg
Argument: '1' should be a System.Management.Automation.PSReference. Use [ref].
At line:26 char:5
+ $Doc.Close($false)
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : NonRefArgumentToRefParameterMsg
Exception calling "Open" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At line:14 char:5
+ $Doc=$Word.Documents.Open($File)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
For the 1st error, I changed my code to include [ref], like these variations (but to no success):
$Doc.SaveAs([ref] $destPath, $formats::wdFormatPDF)
$Doc.SaveAs($destPath, [ref] $formats::wdFormatPDF)
$Doc.SaveAs([ref] $destPath, [ref] 17)
[Update] FYI: Files in the source directory are named like this:
I:\2014\Comply\DOC\IBM=US.DOC
I:\2014\Comply\DOC\CTC.A=CA.DOC
How can I generate a PDF from Word doc?
The above code works if the source & destination paths were the same. Since I didn't get any responses, I've decided to go the C#.Net route and implemented the code that I found in:
How do I convert Word files to PDF programmatically?

ACL Error when assigning AD Rights

I have a powershell script that can create multiple Active Directory users in one run. My issue is assigning ACL rights to the home directory. It seems to always work if there is only one user to create. When there are multiple, however, any account after the first may fail or may work. It's a very intermittent issue, although they seem to fail more than work.
Here is the code generating the ACL's:
Function CreateHomeDirectory{
$global:samAccountName = "myaccount"
$global:homeDirectory = "\\path\to\myaccount"
New-Item -Path $global:homeDirectory -Type Directory -Force
$Rights = [System.Security.AccessControl.FileSystemRights]::Read -bor [System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::Modify -bor [System.Security.AccessControl.FileSystemRights]::FullControl
$Inherit = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
$Propogation = [System.Security.AccessControl.PropagationFlags]::None
$Access = [System.Security.AccessControl.AccessControlType]::Allow
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($global:samAccountName,$Rights,$Inherit,$Propogation,$Access)
$ACL = Get-Acl $global:homeDirectory
$ACL.AddAccessRule($AccessRule)
$Account = new-object system.security.principal.NTAccount($global:samAccountName)
$ACL.setowner($Account)
$ACL.SetAccessRule($AccessRule)
Set-Acl $global:homeDirectory $ACL
Return
Here are the errors I am currently getting. They seem to change up from time to time, but I'd say these are pretty consistant:
Exception calling "AddAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At H:\Scripts\Create.ps1:274 char:10
+ $ACL.AddAccessRule($AccessRule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
Exception calling "SetOwner" with "1" argument(s): "Some or all identity references could not be translated."
At H:\Scripts\Create.ps1:276 char:10
+ $ACL.setowner($Account)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At H:\Scripts\Create.ps1:277 char:10
+ $ACL.SetAccessRule($AccessRule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
Spent hours on this and have gotten nowhere. Any suggestions would be appreciated.
According to the error "Some or all identity references could not be translated.", it looks like the user with such still not exist in the Directory (or in the Directory the computer is connected to) when you try to use it.
I would try to first look for the user in the directory before trying to use it. Check the value of $Account before using it.