In my CAML query for a SharePoint Power-shell script, the changes made in the CAML query is not taken effect.
May I know what am I doing wrong in my code snippet below?
cls
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Set config variables
$baseUrl="http://test.com/"
$RDlistName ="RecordsDocument/Forms/TestReport"
#Get Web and List Objects
$web = Get-SPWeb $baseUrl
$RDlist = $web.Lists[$RDlistName]
#Define the CAML Query
$RDquery = New-Object Microsoft.SharePoint.SPQuery
$RDquery.Query = "#
<Where>
<Eq>
<FieldRef Name='ContentType' />
<Value Type='Text'>Folder Content Type</Value>
#changes to above filter with an incorrect value still returns result *****
</Eq>
</Where>"
#Get List Items matching the query
$RDitems = $RDlist.GetItems($RDquery)
$RDcount = 1
Write-host "Total Number of Folders in RecordsDocument:"$RDitems.count
Write-host ""
#Loop through Each Item
ForEach($RDitem in $RDitems)
{
#Do something
Write-host $RDcount"." $RDitem["Title"] "|" $RDitem["ContentType"]
foreach($RDroleAssignment in $RDitem.RoleAssignments)
{
Write-Host - $RDroleAssignment.Member.Name
}
$RDcount +=1
}
EDIT: In addition, the following error was observed..
You cannot call a method on a null-valued expression. At
D:\User\test.ps1:25 char:1
$RDitems = $RDlist.GetItems($RDquery)
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
My test script(hope it helps):
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
#Set config variables
$baseUrl="http://site/"
$RDlistName ="MyDoc"
#Get Web and List Objects
$web = Get-SPWeb $baseUrl
$RDlist = $web.Lists[$RDlistName]
#Define the CAML Query
$RDquery = New-Object Microsoft.SharePoint.SPQuery
$RDquery.Query = "#
<Where>
<Eq>
<FieldRef Name='ContentType' />
<Value Type='Computed'>Folder</Value>
</Eq>
</Where>"
#Get List Items matching the query
$RDitems = $RDlist.GetItems($RDquery)
$RDcount = 1
Write-host "Total Number of Folders in RecordsDocument:"$RDitems.count
Write-host ""
#Loop through Each Item
ForEach($RDitem in $RDitems)
{
#Do something
Write-host $RDcount"." $RDitem["Title"] "|" $RDitem["ContentType"]
foreach($RDroleAssignment in $RDitem.RoleAssignments)
{
Write-Host - $RDroleAssignment.Member.Name
}
$RDcount +=1
}
Related
I am creating a LIST in SharePoint using PowerShell via a CSV file. I am able to create the list as well as add items successfully, although I need to validate that the item (row) that I add to the list does not already exist in the list, prior to updating the list.
In the code I am not able to get $ItemExist correctly. It always returns a Null value. ($MaxItems currently has a value of 2 as there are 2 items in the list "list_DLs").
(I have already checked all other posts on the site for the same issue and did not find a fix)
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
$Path_SpFiles = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI"
Add-Type -path "$Path_SpFiles\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -path "$Path_SpFiles\Microsoft.SharePoint.Client.dll"
# ------- Connect to SharePoint Site and fetch List Items ----------------
[Net.ServicePointManager]::SecurityProtocol = 'TLS11','TLS12','ssl3'
$site = "https://xyz.sharepoint.com/sites/mco"
$context = New-Object Microsoft.SharePoint.Client.ClientContext($site)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminName, $Pass)
$context.Credentials = $credentials
$ListName="list_DLs"
$list = $context.Web.Lists.GetByTitle($ListName)
$query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(5000)
$items = $list.GetItems($query)
$context.Load($items)
$context.ExecuteQuery()
$MaxItems = $items.count
$SourceFile = "C:\Temp\list_DLs.csv"
$CSVData = Import-CSV -path $SourceFile
foreach ($row in $CSVData)
{
#----------------------------------------------
#Check if the item has previously been added
if ($MaxItems -ne 0)
{
$ItemExist = $items | where{$_.Title -eq $row.PrimarySmtpAddress}
if($ItemExist -ne $null) {Continue}
}
#----------------------------------------------
$ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$Item = $list.AddItem($ListItemInfo)
$Item["Title"] = $row.PrimarySmtpAddress
$Item.Update()
$Context.ExecuteQuery()
Break
}
I know that the $items in being returned correctly, because if I run this snippet of code to iterate through the items I am able to see them correctly. I am just not able to get $ItemExist to work correctly
ForEach ($item in $items)
{
$b = $item["Title"]
$b
Break
}
You can use a CAML query to check if the item is already in the list.
CAML query:
$caml="
<View>
<Query>
<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>1</Value></Eq></Where>
</Query>
</View>
"
$ItemExist = Get-PnPListItem -List $targetList -Query $caml
My test result:
* EDIT: *
Managed to fetch the reccuring events.
How do I overcome the year limit?
<Value Type='DateTime'>
<Year/>
</Value>
I want to get all items, even 5 years ahead.
-------- Original ----------
I am trying to run a PowerShell script to export all events from a SharePoint-2010 calendar including recurring events.
I got references from
https://github.com/CompartiMOSS/SharePoint-PowerShell/blob/master/SharePoint/Administration/PS_HowToDoCAMLQuery.ps1
Expand Recurring Events from a Sharepoint Calendar over WebServices?
The script is running, but the recurring events are not showing.
What am I missing?
If ((Get-PSSnapIn -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{ Add-PSSnapIn -Name Microsoft.SharePoint.PowerShell }
$host.Runspace.ThreadOptions = "ReuseThread"
#Definition of the function that allows to do the CAML query
function DoCAMLQuery
{
param ($sSiteCollection,$sListName)
try
{
$spSite=Get-SPSite -Identity $sSiteCollection
$spwWeb=$spSite.OpenWeb()
$splList = $spwWeb.Lists.TryGetList($sListName)
if ($splList)
{
$spqQuery = New-Object Microsoft.SharePoint.SPQuery
$spqQuery.Query =
"<GetListItems
xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
<listName>'Event Calendar'</listName>
<query>
<Query>
<Where>
<DateRangesOverlap>
<FieldRef Name='EventDate' />
<FieldRef Name='EndDate' />
<FieldRef Name='RecurrenceID' />
<FieldRef Name='fRecurrence' />
<FieldRef Name='RecurrenceData' />
<Value Type='DateTime'><Year/>
</Value>
</DateRangesOverlap>
</Where>
</Query>
</query>
<queryOptions>
<QueryOptions>
<ExpandRecurrence>TRUE</ExpandRecurrence>
</QueryOptions>
</queryOptions>
</GetListItems>"
$spqQuery.ExpandRecurrence = $true
$splListItems = $splList.GetItems($spqQuery)
$iNumber=1
foreach ($splListItem in $splListItems)
{
write-host "File # $iNumber - Name: " $splListItem.Name " ," "Title:" $splListItem["ows_LinkTitle"] -ForegroundColor Green
$iNumber+=1
}
}
$spSite.Dispose()
}
catch [System.Exception]
{
write-host -f red $_.Exception.ToString()
}
}
Start-SPAssignment –Global
#Calling the function
$sSiteCollection="http://sharepoint/"
$sListName="Compliance Events"
DoCamlQuery -sSiteCollection $sSiteCollection -sListName $sListName
Stop-SPAssignment –Global
Remove-PSSnapin Microsoft.SharePoint.PowerShell
Thanks!
S
Below sample script will return events from Now() till next two years.
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$siteURL="http://sp"
$site = Get-SPSite $siteURL
$web = $site.OpenWeb()
$splList = $web.Lists.TryGetList("MyCalendar")
$spqQuery = New-Object Microsoft.SharePoint.SPQuery
$spqQuery.Query = "<Where><DateRangesOverlap><FieldRef Name='EventDate' /><FieldRef Name='EndDate' /><FieldRef Name='RecurrenceID' /><Value Type='DateTime'><Now /></Value></DateRangesOverlap></Where>";
$spqQuery.ExpandRecurrence = $true
$splListItems = $splList.GetItems($spqQuery)
Write-Host $splListItems.Count
One thread for your reference
I want to get the author(who created) a folder in a Sharepoint Online using PnP PowerShell. The time last modified I can get it, but the field author I cannot get it. I know that can be two different fields, author and modifier, but I cannot get any from this.
For the folders:
$folder = Get-PnPFolderItem -FolderSiteRelativeUrl $folderPath -ItemName $subfolderName
Write-Host "URL : " $folder.ServerRelativeUrl
Write-Host "Name : " $folder.Name
Write-Host "Modified : " $folder.TimeLastModified
# above are ok, but $folder has no author property
# same next line fails, Author it does not exist
$folder= Get-PnPFolder -Url "$folderPath/$subfolderName" -Includes ListItemAllFields.Author
For the files, is easy I use:
Get-PnPFile -ServerRelativeUrl $file.ServerRelativeUrl -Path $destinationfolder -FileName $file.Name -AsFile
$f = Get-PnPFile -Url "$($folderUrl)/$($file.Name)" -AsListItem
$fileDetails = #{
File = "$($destinationFolder)/$($file.Name)"
Author = $f["Author"].Email
Created = $f["Created"]
}
I just find the solution, if anyone need:
context = Get-PnPContext
$context.load($context.Web)
$context.ExecuteQuery()
$list = $context.Web.Lists.GetByTitle("Documente")
$context.Load($list)
$context.ExecuteQuery()
$camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
$camlQuery.ViewXml ="<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FileRef' /><Value Type='Text'>/server/folder/relativepath</Value></Eq></Where></Query></View>";
$allItems=$list.GetItems($camlQuery)
$context.Load($allItems)
$context.ExecuteQuery()
foreach($item in $allItems){
Write-Host "##############"
Write-Host $item["FileRef"]
$item["Author"].Email
$item["Modified"]
}
I am creating views for multiple libraries in SharePoint. I am able to create view from below code successfully for one library. But I am stuck when I run the code in a loop. Below is my code
Code
Add-PSSnapin "Microsoft.SharePoint.Powershell" -EA SilentlyContinue
$subSiteURL = #("http://test.test.com/departments/Collections", "http://test.test.com/departments/Events")
$listName = #("Collections","Events")
for ($i=0; $i -lt $subSiteURL.length; $i++) {
$SPWeb = Get-SPWeb $subSiteURL[$i]
$ListName = $listName[$i]
$List = $SPWeb.Lists[$ListName]
$ViewTitle = "WebPart View"
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("DocIcon")
$viewFields.Add("LinkFilenameNoMenu")
$viewQuery = "<GroupBy Collapse='FALSE' GroupLimit='100'> <FieldRef Name='Category' Ascending='True'/> <FieldRef Name='Sub_x002d_Category' Ascending='True'/> </GroupBy> <OrderBy> <FieldRef Name='FileLeafRef' /></OrderBy> <Where><Or><Leq><FieldRef Name='Start_x0020_Date' /><Value Type='DateTime'>[Today]</Value></Leq><And><Geq><FieldRef Name='Expiry_x0020_Date' /><Value Type='DateTime'>[Today]</Value></Geq><Eq><FieldRef Name='Always_x0020_Display' /><Value Type='Boolean'>Yes</Value></Eq></And></Or></Where>"
$viewRowLimit = 999
$viewPaged = $false
$viewDefaultView = $false
$newView = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
$newView.TabularView = $False
$newView.Scope = "Recursive"
$newView.Update()
}
Error
You cannot call a method on a null-valued expression.
At D:\\CreateDocLibrariesViews.ps1:24 char:28
+ $newView = $list.Views.Add <<<< ($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Try below script:
Add-PSSnapin "Microsoft.SharePoint.Powershell" -EA SilentlyContinue
$subSiteURL = #("http://sp", "http://sp:12001")
$listNames = #("MyDoc")
for ($i=0; $i -lt $subSiteURL.length; $i++) {
Write-Host $subSiteURL[$i]
$SPWeb = Get-SPWeb $subSiteURL[$i]
for ($j=0; $j -lt $listNames.length; $j++) {
$ListName = $listNames[$j]
Write-Host $ListName
$List = $SPWeb.Lists[$ListName]
$ViewTitle = "WebPart View"
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("DocIcon")
$viewFields.Add("LinkFilenameNoMenu")
$viewQuery = "<GroupBy Collapse='FALSE' GroupLimit='100'> <FieldRef Name='Category' Ascending='True'/></GroupBy> <OrderBy> <FieldRef Name='FileLeafRef' /></OrderBy>"
$viewRowLimit = 999
$viewPaged = $false
$viewDefaultView = $false
$newView = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
$newView.TabularView = $False
$newView.Scope = "Recursive"
$newView.Update()
}
}
Write-Host "done"
I have a script that queries something in Sharpeoint, then with each document id, it executes a webservice, I am familiar with the measure-command cmdlet and works pretty fine.
However I would like to modify the below script, in order to get the minimum, maximum, and average time the request takes
The code correctly shows me the total execution time of the entire script, but I want to know the total,average, min and max execution time of the TRY block, also
I tried to put measure-command inside, but it prompts for an expression, so apparently 2 measure commands one nested after the other is not possible
function Failure {
$global:helpme = $body
$global:helpmoref = $moref
$global:result = $_.Exception.Response.GetResponseStream()
$global:reader = New-Object System.IO.StreamReader($global:result)
$global:responseBody = $global:reader.ReadToEnd();
Write-Host -BackgroundColor:Black -ForegroundColor:Red "Status: A system exception was caught."
Write-Host -BackgroundColor:Black -ForegroundColor:Red $global:responsebody
Write-Host -BackgroundColor:Black -ForegroundColor:Red "The request body has been saved to `$global:helpme"
break
}
Measure-command {
If ((Get-PSSnapIn -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{ Add-PSSnapIn -Name Microsoft.SharePoint.PowerShell }
$StartDate=(GET-DATE)
$CutOffDate=(Get-date).AddDays(-540)
$SPAssignment = Start-SPAssignment
$SPWeb = Get-SPWeb https://oursite/sites/billing -AssignmentCollection $spAssignment
# Next step is to get the list:
$SPList = $SPWeb.Lists["Bill Cycles"]
$spqQuery = New-Object Microsoft.SharePoint.SPQuery
$spqQuery.Query =
" <Where>
<And>
<Eq>
<FieldRef Name='Bill_x0020_Preparation_x0020_Status' />
<Value Type='Text'>COMPLETED</Value>
</Eq>
<Leq>
<FieldRef Name='Bill_x0020_to_x0020_date' />
<Value Type='DateTime'>
<Today OffsetDays='540' />
</Value>
</Leq>
</And>
</Where>"
$spqQuery.ViewFields = "<FieldRef Name='Bill_x0020_Preparation_x0020_Status' /><FieldRef Name='Title' /><FieldRef Name='Bill_x0020_to_x0020_date' /><FieldRef Name='ContentType'/><FieldRef Name='ID'/>"
$spqQuery.ViewFieldsOnly = $true
$splListItems = $SPList.GetItems($spqQuery)
$iNumber=1
$iNumberOfContentTypes=1
$iNumberOfBillCyclesArchived=0
$iNumberOfBillCyclesArchivedFailed=0
$cred = Get-Credential
foreach ($splListItem in ($splListItems | Select-Object -First 10) )
{
$iNumber+=1
if( $splListItem["ContentType"] -eq "Bill Cycle"){
try {
#Start-Sleep -s 65
$Url = "https://oursite/sites/billing/_vti_bin/DMS/DMSWebService.svc/Billing/ArchiveBillCycle/"+$splListItem["ID"]
#Write-Host $Url
#https://oursite/sites/billing/_vti_bin/DMS/DMSWebService.svc/Billing/ArchiveBillCycle/145771
$r = Invoke-WebRequest -Credential $cred -Uri $Url -TimeoutSec 180 -ErrorAction:Stop
#Write-Host $r.Content.ToString()
if($r.Content -like '*<RequestSucceeded>false</RequestSucceeded>*')
{
write-host "Archiving Failed, File # $iNumber - Bill Cycle Id:" $splListItem["ID"], "Title:" $splListItem["Title"] , "ContentType:" $splListItem["ContentType"] , "Status:" $splListItem["Bill_x0020_Preparation_x0020_Status"] , "Billtodate:" $splListItem["Bill_x0020_to_x0020_date"] -ForegroundColor Red
$iNumberOfBillCyclesArchivedFailed+=1
}
elseif($r.Content -like '*<RequestSucceeded>true</RequestSucceeded>*')
{
write-host "Archived, File # $iNumber - Bill Cycle Id:" $splListItem["ID"], "Title:" $splListItem["Title"] , "ContentType:" $splListItem["ContentType"] , "Status:" $splListItem["Bill_x0020_Preparation_x0020_Status"] , "Billtodate:" $splListItem["Bill_x0020_to_x0020_date"] -ForegroundColor Green
$iNumberOfBillCyclesArchived+=1
}
else{
write-host "Archived, File # $iNumber - Bill Cycle Id:" $splListItem["ID"], "Title:" $splListItem["Title"] , "ContentType:" $splListItem["ContentType"] , "Status:" $splListItem["Bill_x0020_Preparation_x0020_Status"] , "Billtodate:" $splListItem["Bill_x0020_to_x0020_date"] -ForegroundColor Green
$iNumberOfBillCyclesArchived+=1
}
}
catch {
$iNumberOfBillCyclesArchivedFailed+=1
write-host "Archiving Failed, File # $iNumber - Bill Cycle Id:" $splListItem["ID"], "Title:" $splListItem["Title"] , "ContentType:" $splListItem["ContentType"] , "Status:" $splListItem["Bill_x0020_Preparation_x0020_Status"] , "Billtodate:" $splListItem["Bill_x0020_to_x0020_date"] -ForegroundColor Red
Failure
}
$iNumberOfContentTypes+=1
}
}
Write-Host "Number of items in the query: " $iNumber
Write-Host "Number of content types in the query: " $iNumberOfContentTypes
Write-Host "Number of bill cycles archived: " $iNumberOfBillCyclesArchived
Write-Host "Number of bill cycles archived failed: " $iNumberOfBillCyclesArchivedFailed
}