* 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
Related
Help me please figure out how asynchronous loop execution works.
In many forums, examples are very cumbersome and not understandable
During execution, the program window freezes, and at the end of the cycle it shows the final number
for example
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = #"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="Рассылка интернет-трафика" Height="200" Width="300" ResizeMode="NoResize">
<Grid Width="300">
<TextBox Name="text_result" TextWrapping="Wrap" Margin="0,0,0,0" VerticalAlignment="Top" Height="31" Width="200" />
<Button Name="button_start" Content="Start" Height="31" Margin="0,50,0,0" VerticalAlignment="Top" Width="200" />
<Button Name="button_close" Content="Close" Height="31" Margin="0,100,0,0" VerticalAlignment="Top" Width="200"/>
</Grid>
</Window>
"#
#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader"; exit}
# Store Form Objects In PowerShell
$xaml.SelectNodes("//*[#Name]") | ForEach-Object {Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name)}
$button_start.Add_Click({
for ($row = 2; $row -le 1000; $row++) {
$text_result.Text = $row
}
})
#Загружаем главную форму
$Form.ShowDialog() | out-null
It took me quite a while to figure this one out. Let me preface by saying that Adam the Automator has a fantastic breakdown:
https://adamtheautomator.com/building-asynchronous-powershell-functions/
The easiest way to think about executing an asynchronous loop is to think about tricking powershell. In short, you just want it to do something in the background while your script is running. So, you just need to turn the loop you would like into a script block and use start-job, a.k.a. &.
Let's use a common task, such as looking through a bunch of files. Here, we'll use gci.
$scriptblock = {
param ($folder)
Get-ChildItem -Path $folder}
Start-job -ScriptBlock $scriptblock -ArgumentList "C:\Windows" -name "stackexample"
The name is important so that you can reference it later. Now you have a job in the background, and you're good to continue with your script. But what happens if you want to see if the job is done? There's a command for checking on the status of your job (code below).
Get-Job -Name stackexample
One thing to note, make sure to CLOSE your jobs once they're done.
$status = (Get-Job -Name stackexample).state
if ($status -eq "completed")
{
Remove-Job -Name stackexample
}
Wait, I need to know what those folders were! No problem. We just need to tell the scriptblock to output data (write-host, for example). Then, we receive the job before we close it. So a full circuit might look like this:
$scriptblock = {
param ($folder)
$folders = Get-ChildItem -Path $folder
write-host $folders
}
Start-job -ScriptBlock $scriptblock -ArgumentList "C:\Windows" -name "stackexample"
Start-Sleep -Seconds 5
$status = (Get-Job -Name stackexample).state
if ($status -eq "completed")
{
Receive-Job -Name StackExample -Wait
Remove-Job -Name stackexample
}
You can get so much fancier from here, but that is the core of what 'asynchronous code execution' is - telling powershell to do something time consuming while you're doing other stuff.
As applied to your code, you can use the button click to set off a job and run in the background, then receive the final results.
$xaml.SelectNodes("//*[#Name]") | ForEach-Object {Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name)}
$scriptblock = {
for ($row = 2; $row -le 1000; $row++)
{
$result = $row
}
return $result
}
$button_start.Add_Click({
Start-job -ScriptBlock $scriptblock -Name scriptblock
While ((Get-Job -Name scriptblock).State -ne "Completed")
{
start-sleep 1
}
$results = receive-job -Name scriptblock -keep
remove-job -Name scriptblock
$text_result.Text = $results
})
Above the button click we've defined the script block. When the button is clicked, it kicks off the job and then watches it with the while loop. Once the job is finished, we can extract the result (done here with return $result in the scriptblock). Receive the job and you have your final variable which you can now display for the user.
With no cycle.
The form is just a name in this case. You can remove all GUI elements from it if you want.
$Script:SyncHashTable = [Hashtable]::Synchronized(#{})
$RunSpace = [Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()
$RunSpace.ApartmentState = "STA"
$RunSpace.ThreadOptions = "ReuseThread"
$RunSpace.Open()
$RunSpace.SessionStateProxy.SetVariable("SyncHashTable", $Script:SyncHashTable)
$PowerShellCmd = [Management.Automation.PowerShell]::Create().AddScript({
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Script:SyncHashTable.objForm = New-Object System.Windows.Forms.Form
$Script:SyncHashTable.InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$Script:SyncHashTable.objForm.Size = New-Object System.Drawing.Size(340, 200)
$Script:SyncHashTable.objForm.Name = "objForm"
$Script:SyncHashTable.objForm.Text = "Test form"
$Script:SyncHashTable.objLabel = New-Object System.Windows.Forms.Label
$Script:SyncHashTable.objLabel.Location = New-Object System.Drawing.Size(10,20)
$Script:SyncHashTable.objLabel.Size = New-Object System.Drawing.Size(320,20)
$Script:SyncHashTable.objLabel.Text = "Enter the data and press the OK button or key Enter"
$Script:SyncHashTable.objForm.Controls.Add($Script:SyncHashTable.objLabel)
$Script:SyncHashTable.objTextBox = New-Object System.Windows.Forms.TextBox
$Script:SyncHashTable.objTextBox.Location = New-Object System.Drawing.Size(10,40)
$Script:SyncHashTable.objTextBox.Size = New-Object System.Drawing.Size(300,20)
$Script:SyncHashTable.objForm.Controls.Add($Script:SyncHashTable.objTextBox)
$Script:SyncHashTable.objForm.KeyPreview = $True
$Script:SyncHashTable.objForm.Add_KeyDown( { if ($_.KeyCode -eq "Enter") { $Script:SyncHashTable.X = $Script:SyncHashTable.objTextBox.Text;$Script:SyncHashTable.objForm.Close() } })
$Script:SyncHashTable.objForm.Add_KeyDown( { if ($_.KeyCode -eq "Escape") { $objForm.Close() } })
$Script:SyncHashTable.OKButton = New-Object System.Windows.Forms.Button
$Script:SyncHashTable.OKButton.Location = New-Object System.Drawing.Size(75,120)
$Script:SyncHashTable.OKButton.Size = New-Object System.Drawing.Size(75,23)
$Script:SyncHashTable.OKButton.Text = "OK"
$Script:SyncHashTable.OKButton.Add_Click( { $Script:SyncHashTable.X = $Script:SyncHashTable.objTextBox.Text;$Script:SyncHashTable.objForm.Close() } )
$Script:SyncHashTable.objForm.Controls.Add($Script:SyncHashTable.OKButton)
$Script:SyncHashTable.InitialFormWindowState = $Script:SyncHashTable.objForm.WindowState
$Script:SyncHashTable.objForm.add_Load($Script:SyncHashTable.OnLoadForm_StateCorrection)
[void] $Script:SyncHashTable.objForm.ShowDialog()
})
$PowerShellCmd.Runspace = $RunSpace
$obj=$PowerShellCmd.BeginInvoke()
#Time to retrieve our missing object $AsyncObject
$BindingFlags = [Reflection.BindingFlags]'nonpublic','instance'
$Field = $PowerShellCmd.GetType().GetField('invokeAsyncResult',$BindingFlags)
$AsyncObject = $Field.GetValue($PowerShellCmd)
Write-Host 'Here is your code that will be executed in parallel with the form code'
Write-Host '(any length and execution time)'
Write-Host "`$PowerShellCmd.EndInvoke(`$AsyncObject) will wait for results from the form,"
Write-Host "or pick them up if they are ready."
Write-Host "=================================="
#Closing the execution space when getting the result
$PowerShellCmd.EndInvoke($AsyncObject)
'This is the result of executing the form code: {0}' -f $Script:SyncHashTable.X
So I have a button that pulls this function to search for all the Install.Log files on a machine.
After loading the results, I want to have a double click event on the a row, where it will open the log file.
I am having a hard time adding a click event, and anytime I try to find something related to Datatables I find stuff about java. Any guidance or links would be appreciated.
Thanks in advace
TEST THE CODE FOR YOUR SELF BY RUNNING THIS IN PS ISE
$ComputerName = "your computer name here"
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = #'
<Window Name="Form"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="Install Logs" Height="488.773" Width="797.65" Icon = "\\bconac01\ds-support\GS_IT\Tools\Test Tools (Alx)\Tool\icon.ico" ShowInTaskbar="False">
<Grid Margin="0,0,-8,-21">
<DataGrid Name="DataGrid1" HorizontalAlignment="Left" Height="368" VerticalAlignment="Top" Width="772" Margin="10,41,0,0"/>
<Label Content="Filter" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>
<TextBox Name="FilterTextBox" HorizontalAlignment="Left" Height="26" Margin="78,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="172"/>
</Grid>
</Window>
'#
#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
try{$Software=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader. Some possible causes for this problem include: .NET Framework is missing PowerShell must be launched with PowerShell -sta, invalid XAML code was encountered."; exit}
# Store Form Objects In PowerShell
$xaml.SelectNodes("//*[#Name]") | ForEach-Object{
Set-Variable -Name ($_.Name) -Value $Software.FindName($_.Name)
Write-host $_.Name
}
$Fields = #(
'Name'
'LastWriteTime'
)
#$Services = Get-WmiObject -Computer ($prebox.text + $device.text) -Class Win32reg_AddRemovePrograms | Select-object -Property *
$Services = Get-ChildItem \\$ComputerName\c$\build\logs -Include *install* -recurse -ErrorAction Stop | Sort-Object LastWriteTime -Descending
# Add Services to a datatable
$Datatable = New-Object System.Data.DataTable
[void]$Datatable.Columns.AddRange($Fields)
foreach ($Service in $Services)
{
$Array = #()
Foreach ($Field in $Fields)
{
$array += $Service.$Field
}
[void]$Datatable.Rows.Add($array)
}
#$filter = "DisplayName LIKE 'B%'"
#$Datatable.DefaultView.RowFilter = $filter
# Create a datagrid object and populate with datatable
$DataGrid1.ItemsSource = $Datatable.DefaultView
$DataGrid1.CanUserAddRows = $False
$DataGrid1.IsReadOnly = $True
$DataGrid1.GridLinesVisibility = "None"
$DataGrid1.Add_CellMouseClick({gridClick})
function gridClick(){
$rowIndex = $DataGrid1.CurrentRow.Index
$columnIndex = $DataGrid1.CurrentCell.ColumnIndex
Write-Host $rowIndex
Write-Host $columnIndex
Write-Host $DataGrid1.Rows[$rowIndex].Cells[0].value
Write-Host $DataGrid1.Rows[$rowIndex].Cells[$columnIndex].value}
$FilterTextBox.Add_TextChanged({
$InputText = $FilterTextBox.Text
$filter = "Name LIKE '$InputText%'"
$Datatable.DefaultView.RowFilter = $filter
$DataGrid1.ItemsSource = $Datatable.DefaultView
$form.Controls.Add($DataGrid1)
$Software.Controls.Add($DataGrid1)
})
# Shows the form
$statusBar1.Text = "Done."
$Software.Add_Shown({$Software.Activate()})
$Software.ShowDialog() | out-null
--Things Ive tried that are suggested.
[
Ok. Here's a sample with gridview cell click event. You can add cell double click event with $DataGrid1.Add_CellMouseClick({gridClick})
hope this should help
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(900,600)
$DataGrid1 = New-Object System.Windows.Forms.DataGridView
$DataGrid1.Size=New-Object System.Drawing.Size(800,400)
$DataGrid1.Add_CellMouseClick({gridClick})
$form.Controls.Add($DataGrid1)
#Create an unbound DataGridView by declaring a column count.
$DataGrid1.ColumnCount = 4
$DataGrid1.ColumnHeadersVisible = $true
#Set the column header names.
$DataGrid1.Columns[0].Name = "Recipe"
$DataGrid1.Columns[1].Name = "Category"
$DataGrid1.Columns[2].Name = "Third COlumn"
$DataGrid1.Columns[3].Name = "Rating"
#Populate the rows.
$row1 = #("Meatloaf","Main Dish", "boringMeatloaf", "boringMeatloafRanking")
$row2 = #("Key Lime Pie","Dessert", "lime juice evaporated milk", "****")
$row3 = #("Orange-Salsa Pork Chops","Main Dish", "pork chops, salsa, orange juice", "****")
$row4 = #("Black Bean and Rice Salad","Salad", "black beans, brown rice", "****")
$row5 = #("Chocolate Cheesecake","Dessert", "cream cheese", "***")
$row6 = #("Black Bean Dip", "Appetizer","black beans, sour cream", "***")
$rows = #( $row1, $row2, $row3, $row4, $row5, $row6 )
foreach ($row in $rows){
$DataGrid1.Rows.Add($row)
}
function gridClick(){
$rowIndex = $DataGrid1.CurrentRow.Index
$columnIndex = $DataGrid1.CurrentCell.ColumnIndex
Write-Host $rowIndex
Write-Host $columnIndex
Write-Host $DataGrid1.Rows[$rowIndex].Cells[0].value
Write-Host $DataGrid1.Rows[$rowIndex].Cells[$columnIndex].value}
$form.ShowDialog()
As per your requirement here's one another sample I have created with WPF with PowerShell. You can bind the event using $WPFListView.Add_MouseDoubleClick({gridClick}) and to access the selected cell value using column like $WPFListView.SelectedValue.OriginalFileName
Try this as it is in PowerShell ISE. This is how it looks
##Sample DataTable
$tabName = "SampleTable"
#Create Table object
$table = New-Object system.Data.DataTable “$tabName”
#Define Columns
$col1 = New-Object system.Data.DataColumn OriginalFileName,([string])
$col2 = New-Object system.Data.DataColumn FileDescription,([string])
$col3 = New-Object system.Data.DataColumn FileVersionRaw,([string])
#Add the Columns
$table.columns.add($col1)
$table.columns.add($col2)
$table.columns.add($col3)
#Create a row
$row = $table.NewRow()
$row.OriginalFileName = "Test Log"
$row.FileDescription = "Test log data"
$row.FileVersionRaw = "v1.0"
$row1 = $table.NewRow()
$row1.OriginalFileName = "IIS Log"
$row1.FileDescription = "IIS Sys log"
$row1.FileVersionRaw = "v2.0"
$row2 = $table.NewRow()
$row2.OriginalFileName = "User Data"
$row2.FileDescription = "User data details"
$row2.FileVersionRaw = "v1.0"
$row3 = $table.NewRow()
$row3.OriginalFileName = "Sys Info"
$row3.FileDescription = "System Info Details"
$row3.FileVersionRaw = "v2.0"
#Add the row to the table
$table.Rows.Add($row)
$table.Rows.Add($row1)
$table.Rows.Add($row2)
$table.Rows.Add($row3)
##Sample DataTable
$inputXML = #"
<Window x:Class="FileVersionChecker.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FileVersionChecker"
mc:Ignorable="d"
Title="FileVersionChecker" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="115*"/>
<ColumnDefinition Width="373*"/>
<ColumnDefinition Width="29*"/>
</Grid.ColumnDefinitions>
<ListView Name="ListView" Grid.Column="1" HorizontalAlignment="Left" Height="150" Margin="10,10,0,0" VerticalAlignment="Top" Width="350">
<ListView.View>
<GridView>
<GridViewColumn Header="OriginalFileName" DisplayMemberBinding ="{Binding 'OriginalFileName'}" Width="100"/>
<GridViewColumn Header="FileDescription" DisplayMemberBinding ="{Binding 'FileDescription'}" Width="100"/>
<GridViewColumn Header="FileVersionRaw" DisplayMemberBinding ="{Binding 'FileVersionRaw'}" Width="100"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
"#
$inputXML = $inputXML -replace 'mc:Ignorable="d"', '' -replace "x:N", 'N' -replace '^<Win.*', '<Window'
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = $inputXML
#Read XAML
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
try {
$Form = [Windows.Markup.XamlReader]::Load( $reader )
}
catch {
Write-Output "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .net is installed."
}
$xaml.SelectNodes("//*[#Name]") | ForEach-Object {Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name)}
$WPFListView.ItemsSource = $table.DefaultView
$WPFListView.Add_MouseDoubleClick({gridClick})
function gridClick()
{
Write-Host ""
Write-Host "$($WPFListView.SelectedValue.OriginalFileName) , $($WPFListView.SelectedValue.FileDescription), $($WPFListView.SelectedValue.FileVersionRaw)"
}
$Form.ShowDialog() | out-null;
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
}
I'm using SP 2013 on-premises and I'm wanting to query a list for items by passing a number of IDs to the list and then returning only the Title field. This is executing in Powershell. I have the following that I am using as the ViewXml:
<View>
<ViewFields>
<FieldRef Name='Title'/>
</ViewFields>
<Query>
<Where>
<In>
<FieldRef Name='ID' />
<Values>
<Value Type='Counter'>1131</Value>
<Value Type='Counter'>478</Value>
<Value Type='Counter'>360</Value>
<Values>
</In>
</Where>
</Query>
</View>
I get the following when running $ctx.executeQuery();
Exception calling "ExecuteQuery" with "0" argument(s): "Cannot complete this action.
Please try again."
Here is the rest of the code minus the variable definitions and the bit where the client dlls are added
$pwd = Read-Host -Prompt "Enter password" -AsSecureString
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$ctx.Credentials = New-Object System.Net.NetworkCredential($userId, $pwd)
$vFields = "<Value Type='Counter'>1131</Value><Value Type='Counter'>478</Value><Value Type='Counter'>360</Value>";
try{
$lists = $ctx.web.Lists ;
$list = $lists.GetByTitle($ListName);
$query = New-Object Microsoft.SharePoint.Client.CamlQuery;
$xmlCAML = "<View><ViewFields><FieldRef Name='Title'/></ViewFields><Query><Where><In><FieldRef Name='ID'/><Values>$vFields<Values></In></Where></Query></View>";
write-host $xmlCAML -ForegroundColor Yellow
$query.ViewXml = $xmlCAML
$listItems = $list.GetItems($query);
$ctx.load($listItems);
$ctx.executeQuery();
foreach($listItem in $listItems)
{
Write-Host "Title - " $listItem["Title"]
}
}
catch{
write-host "$($_.Exception.Message)" -foregroundcolor red
}
if you haven't already sorted this, it's just a single-keystroke fix, you've just failed to properly close the <Values>...</Values> element in your CAML. Needs to be:
<View>
<ViewFields>
<FieldRef Name='Title'/>
</ViewFields>
<Query>
<Where>
<In>
<FieldRef Name='ID' />
<Values>
<Value Type='Counter'>1131</Value>
<Value Type='Counter'>478</Value>
<Value Type='Counter'>360</Value>
</Values> <!-- <== Here :) -->
</In>
</Where>
</Query>
</View>
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
}