Alternative to foreach items in a sharepoint list - sharepoint

I MODIFIED THE CAML AND IT'S NOW WORKING AND DOES NOT LOOP THROUGH ALL THE ITEMS IN A LIST.
I am looking for list items where workflow status equal "Error Occurred". I have the following code and it's working fine. However, there are 124,000 items in my list and the code goes through each item in the list. Is there a way to limit this to items where workflow status (workflow name is "Archive Data") is "Error Occurred". Please suggest. I added following CAML and changed the code but it still returns all the records. I tested the CAML with u2u and it returns 144 records. I added write-host to get a count and commented out the foreach for test.
# Terminates all workflow in a give list
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$web = Get-SPWeb "http://inside.nov.com/sales/SouthEast"
$web.AllowUnsafeUpdates = $true
# $list name is list display name
$list = $web.Lists["New Orders"]
$CAML = '<Where>
<Eq>
<FieldRef Name="ArchiveData" />
<Value Type="WorkflowStatus">3</Value>
</Eq>
</Where>'
$query = new-object Microsoft.SharePoint.SPQuery
$query.Query = $CAML
$listitems = $list.GetItems($query)
Write-Host "Count: " $listitems.Count
#foreach ($item in $listItems)
#{
# foreach ($wf in $item.Workflows)
# {
# #Cancel Workflows
# [Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf)
# }
#}
$web.Dispose()

I updated the original code and it's working. The keyword "Query" dont need to be in CAML when using SPQuery object. The SPQuery automatically wraps the CAML with keyword.
Thanks

Related

How to get a last modified file date of a subfolder inside a document library

When I upload a file in to a subfolder the subfolder modified date is not updated where as the document library last modified date is updated
Now I want to find which file is last updated inside a subfolder using csom
You could use caml query to get the lasted modified item in a library like this:
$list = $Web.Lists.GetByTitle($ListTitle)
$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$query.ViewXml = '<View><Query><OrderBy><FieldRef Name="Modified" Ascending="FALSE"/></OrderBy></Query><RowLimit>1</RowLimit></View>'
$items = $list.GetItems($query)
$Context.load(items)
$context.ExecuteQuery()

Powershell getting same values when using if in foreach

I'm trying to get metric from Azure to Zabbix.
The issue is that Metric for VM consists of 2 words:Percentage CPU, and Zabbix doesn't allow item keys to consists of 2 words. I also tried Percentage%20CPU but getting errors in Zabbix, and I created Zabbix key percentage_cpu.
So I decided prior sending data from Zabbix to Azure to "translate" percentage_cpu to Percentage%20CPU. This works great if only that key is present, but issue starts when I add another key (in this example SQL metric).
For SQL metric all values are in one word - no need to change anything, but then metric for VM is also assigned to SQL. I'm trying to avoid writing separate file for every service
$host_items = Get-ZabbixHostItems -url $zabbix_url -auth $zabbix_auth -
zabbix_host $host_name
foreach ($host_item in $host_items)
{
#$host_item_details = select-string -InputObject $host_item.key_ -Pattern '^(azure\.sql)\.(.*)\.(.*)\[\"(.*)\"\]$';
$host_item_details = select-string -InputObject $host_item.key_ -Pattern '^(azure\.\w{2,})\.(.*)\.(.*)\[\"(.*)\"\,(.*)]$';
#$host_item_details = select-string -InputObject $host_item.key_ -Pattern '^(azure)\.(.*)\.(.*)\.(.*)\[\"(.*)\"\,(.*)]$';
$host_item_provider = $host_item_details.Matches.groups[1];
$host_item_metric = $host_item_details.Matches.groups[2];
$host_item_timegrain = $host_item_details.Matches.groups[3];
$host_item_resource = $host_item_details.Matches.groups[4];
$host_item_suffix = $host_item_details.Matches.groups[5];
if ($host_item_metric='percentage_cpu')
{$host_item_metric='Percentage%20CPU'}
else
{ $host_item_metric = $host_item_details.Matches.groups[2];}
#}
$uri = "https://management.azure.com{0}/providers/microsoft.insights/metrics?api-version={1}&interval={2}&timespan={3}&metric={4}" -f `
$host_item_resource, `
"2017-05-01-preview", `
$host_item_timegrain.ToString().ToUpper(), `
$($(get-date).ToUniversalTime().addminutes(-15).tostring("yyyy-MM-ddTHH:mm:ssZ") + "/" + $(get-date).ToUniversalTime().addminutes(-2).tostring("yyyy-MM-ddTHH:mm:ssZ")), `
$host_item_metric;
write-host $uri;
}
output of hostitems_
azure.sql.dtu_consumption_percent.pt1m["/subscriptions/111-222/resourceGroups/rg/providers/Microsoft.Sql/servers/mojsql/databases/test",common]
azure.vm.percentage_cpu.pt1m["/subscriptions/111-222/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/test",common]
When I ran code above I'm getting these URI's
https://management.azure.com/subscriptions/111-222/resourceGroups/rg/providers/Microsoft.Sql/servers/mojsql/databases/test/providers/microsoft.insights/m
etrics?api-version=2017-05-01-preview&interval=PT1M&timespan=2018-08-11T07:38:05Z/2018-08-11T07:51:05Z&metric=Percentage%20CPU
https://management.azure.com/subscriptions/111-222/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/test/providers/microsoft.insights/metric
s?api-version=2017-05-01-preview&interval=PT1M&timespan=2018-08-11T07:38:05Z/2018-08-11T07:51:05Z&metric=Percentage%20CPU
For first link (SQL) metric should be dtu_consumption but I'm getting same metric for both links
Second attempt:
if ($host_item_metric -eq 'percentage_cpu')
{$host_item_metric='Percentage%20CPU';}
else
{ $host_item_metric = $host_item_details.Matches.groups[2];}
write-host $host_item_metric
}
output: (original values)
dtu_consumption_percent
percentage_cpu
had to use -like
if ($host_item_metric -like 'percentage_cpu')
{$host_item_metric='Percentage%20CPU';}
else
{ $host_item_metric = $host_item_details.Matches.groups[2]}

Evaluate variable(s) inside string passed escaped to function in PowerShell

I have a PowerShell function like this (I have simplified it here to make it more understandable):
Function QueryList
{
param(
[Parameter(Mandatory=$true,Position=1)]
[Microsoft.SharePoint.SPList] $list
[Parameter(Mandatory=$true,Position=2)]
[string] $camlQuery
)
$itemsQry = New-Object Microsoft.SharePoint.SPQuery
$itemsQry.Query = $camlQuery
$itemsQry.ViewFieldsOnly = $false
$itemsQry.RowLimit = 0
$itemsQry.ViewAttributes = "Scope='Recursive'"
return $list.GetItems($itemsQry)
}
Function MigrateList
{
param(
[Parameter(Mandatory=$true,Position=1)]
[Microsoft.SharePoint.SPList] $list,
[Parameter(Mandatory=$true,Position=2)]
[string] $matchingItemsQuery
)
foreach ($listItem in $list.Items)
{
# get items using the query (how to inject '$listItem' into query string?)
$targetItem = QueryList -list $list -camlQuery $matchingItemsQuery
# do something with matching items
...
}
}
# main script
$matchingItemsQuery = "<Where><Eq><FieldRef Name='Title' /><Value Type='TEXT'>`$(`$listItem[`"Title`"])</Value></Eq></Where>"
$targetItems = MigrateList -list $listXy -matchingItemsQuery $matchingItemsQuery
As you can see, I want to query some items from a list, matching a given criteria. As the criteria changes from list to list I want to be able to pass the query to the function, inside the query there is a reference to the variable that will only exist in the 'MigrateList' function (here: $listItem).
As it is now, the variable will of course not be evaluated to the objects value ("Title" column value of $listItem) as it is passed as a string, as the '$' are escaped (which is needed to pass the query to the function).
I know it is maybe not the nicest construct but it would get the job done. So how could I change the script that the passed query string will be injected with the $listItem object (in this case, column value)?
Thank you for the comments, especially #TheIncorrigible1 for the tip regarding using a scriptblock, which I (successfully) tried to implement.
I got it to work with this:
Function MigrateList
{
param(
[Parameter(Mandatory=$true,Position=1)]
[Microsoft.SharePoint.SPList] $list,
[Parameter(Mandatory=$true,Position=2)]
[scriptblock] $itemMatchQuerySb
)
foreach ($listItem in $list.Items)
{
# get items using the query (how to inject '$listItem' into query string?)
$matchingItemsQuery = (. $itemMatchQuerySb)
$targetItem = QueryList -list $list -camlQuery $matchingItemsQuery
# do something with matching items
...
}
}
# main script
$matchingItemsQuerySb = [scriptblock]::Create("echo ""<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>`$(`$listItem[`"Title`"])</Value></Eq></Where>""")
$targetItems = MigrateList -list $listXy -matchingItemsQuery $matchingItemsQuery

List of all subscription

How to check all report's subscriptions on Sharepoint 2010?
I know only how to check subsciption on specific report:
Unfortunately, there is no way way for you to do this from the GUI. You are going to have to break out PowerShell to get this information.
NOTE: I haven't tested this code, kinda writing it from the hip, but the gist should be able to help you out.:
$spWeb = Get-SPWeb <Site reports are contained in>
$spRepList = $spWeb.Lists["<List containing reports Name>"];
#Get all files
$spFileList = $spRepList.Files;
foreach($spFile in $spFileList)
{
#determine if the file is a report or a regular document
if($spFile.URL -like "*.rdl")
{
$reportServiceProxy = New-WebServiceProxy -URI <url to the reporting web service> -Namespace <Namespace of the service> -UseDefaultCredentials
$subscriptionList += $reportServiceProxy.ListSubscriptions($site);
#From here you can write to a file or write to the screen. I will let you decide
$subscriptionList | select Path, report, Description, Owner, SubscriptionID, lastexecuted,Status | where {$_.path -eq $spFile.URL}
}
}
Hope this helps.
Dave

Not able to update list field properties using sharepoint powershell

How do I use PowerShell to update list field properties? When I try the following:
$site = Get-SPSite -Identity "http://vikas:26112/"
$web= $site.OpenWeb()
$spList = $web.GetList("/Lists/Support Links")
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
$spList.Fields.Add("FirstName",$spFieldType,$false)
$spList.Fields[“FirstName”].Description = “My FirstName Field”
$spList.Fields[“FirstName”].Required=$true
$spList.Fields["FirstName"].EnforceUniqueValues=$true
$spList.update()
$web.Dispose()
After executing this FirstName field is added to list but properties of this field remains unchanged:
Description =""
Required=false
EnforceUniqueValues=false
The problem is that you are not updating the field and that indexer is returning different instances each time you use it. You must store the instance of the field in some variable, then change it, then update it.
Change your code like this:
$site = Get-SPSite -Identity "http://vikas:26112/"
$web= $site.OpenWeb()
$spList = $web.GetList("/Lists/Support Links")
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
$spList.Fields.Add("FirstName",$spFieldType,$false)
$field = $spList.Fields[“FirstName”]
$field.Description = “My FirstName Field”
$field.Required=$true
$field.EnforceUniqueValues=$true
$field.update()
$web.Dispose()

Resources