SP2010 Delete list items after CAML Query - powershell

I want to delete list items from my CAML query but currently cannot using a foreach loop.
What would be the best way to delete the items after the CAML query?
$Query = New-Object Microsoft.SharePoint.SPQuery
$Query.Query = "
<Where>
<Leq>
<FieldRef Name='Created' />
<Value Type='DateTime'>
<Today OffsetDays='-30' />
</Value>
</Leq>
</Where>
<OrderBy>
<FieldRef Name='Created' Ascending='False' />
</OrderBy>"
#Get List Items matching the query
$ListItems = $oList.GetItems($Query)
write-host "Number of items retrieved:" $ListItems.Count;
foreach($ListItem in $ListItems)
{
write-host "Deleting"+ $listItem.ID + $listItem.Name + $listItem["Created"];
#$ListItem.delete();
}

Please delete list item in foreach loop like this:
$spweb = get-spweb http://sp/sites/devtest
$oList = $spweb.Lists.TryGetList("List2")
if ($oList)
{
$query = New-Object Microsoft.SharePoint.SPQuery
$query.Query = "
<Where>
<Leq>
<FieldRef Name='Created' />
<Value Type='DateTime'>
<Today OffsetDays='-30' />
</Value>
</Leq>
</Where>
<OrderBy>
<FieldRef Name='Created' Ascending='False' />
</OrderBy>"
$ListItems = $oList.GetItems($Query)
Write-host "Number of items retrieved:" $ListItems.Count;
foreach($item in $ListItems)
{
Write-Host "Deleting Item - $($item.Id)"
$oList.GetItemById($item.Id).delete()
}
}

Related

pick required content from text file located on multiple remote servers and write to log in csv from where script is executed

I am writing a script to read a text file from multiple remote servers and get required details from text file writing those details to csv log file creating on pc from where script is executed.
I want to add try, catch and if condition to get my script working as expected.
Requirement as below:
read file from remote server located under path,
replace unwanted characters ( which is being done by code -replace)
saving text file with set-content(already done)
get required content from file, store in a array variable(done)
write content in log file (.csv) created on PC from where the script is being executed.
Issue is script getting details, but when trying to write to log its not writing and giving error "Cannot index into a null array."
my code is below:
$servers = gc .\servers.txt
$Global:ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
$date = (get-date).ToString("yyyyMMdd_HHmm")
$ILOContent = "$ScriptDir\ILOConfigData_$date.csv"
Add-Content -Path $ILOContent -Value "ILO_Name,ILO_Domain,Network_Details,ILO-TimeZone,Directory_Users,LDAP_Directory_Authentication,Directory_Groups,SNMP-Settings,Directory_Server_Address"
Foreach($server in $servers){
Invoke-Command -ComputerName $server -Credential $Credential -ScriptBlock {
New-Item -Path "C:\Program Files\Hewlett Packard Enterprise\HPONCFG" -ItemType File -Name Current_ILOConfig.xml -Force| Out-Null
Set-Location "C:\Program Files\Hewlett Packard Enterprise\HPONCFG"
$ILODataPath = Get-Location
$WantFile = "$ILODataPath\Current_ILOConfig.txt"
$FileExists = Test-Path $WantFile
If ($FileExists -eq $True) {Remove-Item $WantFile }
Sleep(2)
Write-Host "Gathering current ILO configuration for $ENV:COMPUTERNAME"
& "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe" /a /w `
"C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml" |Out-Null
Get-Content .\Current_ILOConfig.xml|Set-Content "Current_ILOConfig.txt"
Sleep(3)
$ILORAW_DATA = Get-Content .\Current_ILOConfig.txt
$ILORAW_DATA|ForEach-Object{
$_ -replace '<!-- ' `
-replace ' -->' `
-replace '<' `
-replace ' />' `
-replace '"' `
}|Set-Content .\Current_ILOConfig.txt
$ILO_DATA = Get-Content .\Current_ILOConfig.txt
Write-Host "Getting DNS details"
$DNS_NAME = $ILO_DATA |Where {$_ |Select-String -Pattern " DNS_NAME VALUE"," DOMAIN_NAME VALUE"}
$ILONAME = $DNS_NAME -split "="
$ServerILO = $ILONAME[1]
$ILONAME[3]
Write-Host "Getting Network details"
$NT = $ILO_DATA | where {$_ |Select-String -Pattern " IP_ADDRESS VALUE"," SUBNET_MASK"," GATEWAY_IP_ADDRESS"," PRIM_DNS_SERVER VALUE", " SEC_DNS_SERVER VALUE"," TER_DNS_SERVER VALUE" }
$Network = [array]$NT -join "`n"
$Network.Trim()
Write-Host "Getting ILO TimeZone"
$TZ= $ILO_DATA |Where {$_ | Select-String -Pattern " TIMEZONE VALUE"}
$TimeZone =$TZ -Split "="
$TimeZone[1]
#DIRECT
Write-Host "Getting Directory User details"
$DIR_USER = $ILO_DATA |Where {$_ | Select-String -Pattern " DIR_USER_CONTEXT"}
$User =#()
foreach($Usr in $DIR_USER)
{
$User += ($Usr -split "VALUE=")[1]
}$User ; $DIR_USERS = [Array]$User -join "`n"
Write-Host "getting Global:ScriptDir location"
Set-Location $Global:ScriptDir
Get-Location
$Data = $ILONAME[1]+$ILONAME[3]+$Network,$Model,$TimeZone[1],$DIR_USERS
$Data|Select-Object $ILONAME[1],$ILONAME[3],$Network,$TimeZone[1],$DIR_USERS |Export-Csv -Append -Path $ILOContent -notypeinformation
}
}
Example of the XML:
<!-- HPONCFG VERSION = "5.4.0.0" -->
<!-- Device: iLO 5 Firmware Version : 2.44 Firmware Date : 30-4-2021 -->
<RIBCL VERSION="2.0">
<LOGIN USER_LOGIN="admin" PASSWORD="password">
<RIB_INFO mode="write">
<MOD_NETWORK_SETTINGS>
<ENABLE_NIC VALUE="Y" />
<SHARED_NETWORK_PORT VALUE="N" />
<VLAN_ENABLED VALUE="N" />
<SPEED_AUTOSELECT VALUE="Y" />
<DHCP_ENABLE VALUE="N" />
<DHCP_GATEWAY VALUE="Y" />
<DHCP_DNS_SERVER VALUE="Y" />
<DHCP_WINS_SERVER VALUE="Y" />
<DHCP_STATIC_ROUTE VALUE="Y" />
<DHCP_DOMAIN_NAME VALUE="Y" />
<DHCP_SNTP_SETTINGS VALUE="N" />
<REG_WINS_SERVER VALUE="Y" />
<REG_DDNS_SERVER VALUE="N" />
<PING_GATEWAY VALUE="Y" />
<IP_ADDRESS VALUE="100.11.13.65" />
<SUBNET_MASK VALUE="255.255.255.255" />
<GATEWAY_IP_ADDRESS VALUE="100.11.13.1" />
<DNS_NAME VALUE="server-ilo" />
<DOMAIN_NAME VALUE="Contasa.com" />
<PRIM_DNS_SERVER VALUE="10.110.21.73" />
<SEC_DNS_SERVER VALUE="10.110.21.74" />
<TER_DNS_SERVER VALUE="10.110.21.75" />
<PRIM_WINS_SERVER VALUE="0.0.0.0" />
<SEC_WINS_SERVER VALUE="0.0.0.0" />
<SNTP_SERVER1 VALUE="" />
<SNTP_SERVER2 VALUE="" />
<TIMEZONE VALUE="Beijing, Chongqing, Hong Kong, Urumqi, Taipei, Perth" />
<STATIC_ROUTE_1 DEST="0.0.0.0" MASK="0.0.0.0" GATEWAY="0.0.0.0" />
<STATIC_ROUTE_2 DEST="0.0.0.0" MASK="0.0.0.0" GATEWAY="0.0.0.0" />
<STATIC_ROUTE_3 DEST="0.0.0.0" MASK="0.0.0.0" GATEWAY="0.0.0.0" />
<IPV6_STATIC_ROUTE_1 IPV6_DEST="::" PREFIXLEN="0" IPV6_GATEWAY="::" ADDR_STATUS="INACTIVE" />
<IPV6_STATIC_ROUTE_2 IPV6_DEST="::" PREFIXLEN="0" IPV6_GATEWAY="::" ADDR_STATUS="INACTIVE" />
<IPV6_STATIC_ROUTE_3 IPV6_DEST="::" PREFIXLEN="0" IPV6_GATEWAY="::" ADDR_STATUS="INACTIVE" />
<IPV6_PRIM_DNS_SERVER VALUE="::" />
<IPV6_SEC_DNS_SERVER VALUE="::" />
<IPV6_TER_DNS_SERVER VALUE="::" />
<IPV6_DEFAULT_GATEWAY VALUE="::" />
<IPV6_PREFERRED_PROTOCOL VALUE="N" />
<IPV6_ADDR_AUTOCFG VALUE="N" />
<IPV6_REG_DDNS_SERVER VALUE="N" />
<DHCPV6_STATELESS_ENABLE VALUE="N" />
<DHCPV6_STATEFUL_ENABLE VALUE="N" />
<DHCPV6_RAPID_COMMIT VALUE="N" />
<DHCPV6_DOMAIN_NAME VALUE="N" />
<DHCPV6_SNTP_SETTINGS VALUE="N" />
<DHCPV6_DNS_SERVER VALUE="N" />
<ILO_NIC_AUTO_SELECT VALUE="DISABLED" />
<ILO_NIC_AUTO_SNP_SCAN VALUE="0" />
<ILO_NIC_AUTO_DELAY VALUE="90" />
<ILO_NIC_FAIL_OVER VALUE="DISABLED" />
<ILO_NIC_FAIL_OVER_DELAY VALUE="300" />
<SNP_PORT VALUE="1" />
</MOD_NETWORK_SETTINGS>
</RIB_INFO>
<RIB_INFO mode="write">
<MOD_GLOBAL_SETTINGS>
<SESSION_TIMEOUT VALUE="30" />
<ILO_FUNCT_ENABLED VALUE="Y" />
<F8_PROMPT_ENABLED VALUE="Y" />
<F8_LOGIN_REQUIRED VALUE="N" />
<RIBCL_STATUS VALUE="Y" />
<WEBSERVER_STATUS VALUE="Y" />
<WEBGUI_STATUS VALUE="Y" />
<REMOTE_CONSOLE_STATUS VALUE="Y" />
<VIRTUAL_MEDIA_STATUS VALUE="Y" />
<HTTPS_PORT VALUE="443" />
<HTTP_PORT VALUE="80" />
<REMOTE_CONSOLE_PORT VALUE="179" />
<VIRTUAL_MEDIA_PORT VALUE="179" />
<SNMP_ACCESS_ENABLED VALUE="Y" />
<SNMP_PORT VALUE="161" />
<SNMP_TRAP_PORT VALUE="161" />
<SSH_PORT VALUE="21" />
<SSH_STATUS VALUE="Y" />
<SERIAL_CLI_STATUS VALUE="3" />
<SERIAL_CLI_SPEED VALUE="1" />
<VSP_LOG_ENABLE VALUE="N" />
<MIN_PASSWORD VALUE="8" />
<AUTHENTICATION_FAILURE_LOGGING VALUE="3" />
<AUTHENTICATION_FAILURE_DELAY_SECS VALUE="10" />
<AUTHENTICATION_FAILURES_BEFORE_DELAY VALUE="1" />
<LOCK_CONFIGURATION VALUE="N" />
<RBSU_POST_IP VALUE="Y" />
<ENFORCE_AES VALUE="N" />
<IPMI_DCMI_OVER_LAN_ENABLED VALUE="N" />
<REMOTE_SYSLOG_ENABLE VALUE="N" />
<REMOTE_SYSLOG_PORT VALUE="514" />
<REMOTE_SYSLOG_SERVER_ADDRESS VALUE="" />
<ALERTMAIL_ENABLE VALUE="N" />
<ALERTMAIL_EMAIL_ADDRESS VALUE="" />
<ALERTMAIL_SENDER_DOMAIN VALUE="" />
<ALERTMAIL_SMTP_PORT VALUE="25" />
<ALERTMAIL_SMTP_SERVER VALUE="" />
<ALERTMAIL_SMTP_SECURE_ENABLE VALUE="Y" />
<ALERTMAIL_SMTP_AUTH_ENABLE VALUE="N" />
<ALERTMAIL_SMTP_AUTH_USERNAME VALUE="" />
<PROPAGATE_TIME_TO_HOST VALUE="N" />
<IPMI_DCMI_OVER_LAN_PORT VALUE="623" />
</MOD_GLOBAL_SETTINGS>
</RIB_INFO>
<DIR_INFO mode="write">
<MOD_DIR_CONFIG>
<DIR_AUTHENTICATION_ENABLED VALUE="Y" />
<DIR_LOCAL_USER_ACCT VALUE="Y" />
<DIR_SERVER_ADDRESS VALUE="contasa.com" />
<DIR_SERVER_PORT VALUE="3269" />
<DIR_OBJECT_DN VALUE="" />
<DIR_USER_CONTEXT_1 VALUE="CN=ABC,DC=Contasa,DC=com" />
<DIR_USER_CONTEXT_2 VALUE="CN=XYZ,DC=Contasa,DC=com" />
<DIR_USER_CONTEXT_3 VALUE="CN=DDD,DC=Contasa,DC=com" />
<DIR_USER_CONTEXT_6 VALUE="" />
<DIR_USER_CONTEXT_7 VALUE="" />
<DIR_USER_CONTEXT_8 VALUE="" />
<DIR_USER_CONTEXT_9 VALUE="" />
<DIR_USER_CONTEXT_10 VALUE="" />
<DIR_USER_CONTEXT_11 VALUE="" />
<DIR_USER_CONTEXT_12 VALUE="" />
<DIR_USER_CONTEXT_13 VALUE="" />
<DIR_USER_CONTEXT_14 VALUE="" />
<DIR_USER_CONTEXT_15 VALUE="" />
<DIR_ENABLE_GRP_ACCT VALUE="Y" />
<DIR_GRPACCT1_NAME VALUE="Administrators" />
<DIR_GRPACCT1_SID VALUE="" />
<DIR_GRPACCT2_NAME VALUE="Authenticated Users" />
<DIR_GRPACCT3_NAME VALUE="CN=ABC,DC=Contasa,DC=com" />
<DIR_GRPACCT4_NAME VALUE="CN=XYZ,DC=Contasa,DC=com" />
<DIR_GRPACCT5_NAME VALUE="CN=DDD,DC=Contasa,DC=com" />
<DIR_GRPACCT6_SID VALUE="" />
<DIR_KERBEROS_ENABLED VALUE="N" />
<DIR_KERBEROS_REALM VALUE="" />
<DIR_KERBEROS_KDC_ADDRESS VALUE="" />
<DIR_KERBEROS_KDC_PORT VALUE="88" />
<DIR_GENERIC_LDAP_ENABLED VALUE="N" />
</MOD_DIR_CONFIG>
</DIR_INFO>
<RIB_INFO mode="write">
<MOD_SNMP_IM_SETTINGS>
<SNMP_ACCESS VALUE="Enable" />
<SNMP_ADDRESS_1_ROCOMMUNITY VALUE="" />
<SNMP_ADDRESS_2_ROCOMMUNITY VALUE="" />
<SNMP_ADDRESS_3_ROCOMMUNITY VALUE="" />
<SNMP_ADDRESS_1 VALUE="Server1.contasa.com" />
<SNMP_ADDRESS_2 VALUE="Server1.contasa.com" />
<SNMP_ADDRESS_3 VALUE="" />
<SNMP_ADDRESS_3_TRAPCOMMUNITY VERSION="" VALUE="" />
<SNMP_PORT VALUE="160" />
<SNMP_TRAP_PORT VALUE="160" />
<TRAP_SOURCE_IDENTIFIER VALUE="iLO Hostname" />
<RIB_TRAPS VALUE="Y" />
<OS_TRAPS VALUE="N" />
<COLD_START_TRAP_BROADCAST VALUE="Y" />
<SNMP_PASSTHROUGH_STATUS VALUE="N" />
<WEB_AGENT_IP_ADDRESS VALUE="" />
<CIM_SECURITY_MASK VALUE="3" />
<SNMP_SYS_CONTACT VALUE="" />
<SNMP_SYS_LOCATION VALUE="" />
<AGENTLESS_MANAGEMENT_ENABLE VALUE="Y" />
<SNMP_SYSTEM_ROLE VALUE="" />
<SNMP_SYSTEM_ROLE_DETAIL VALUE="" />
</MOD_SNMP_IM_SETTINGS>
</RIB_INFO>
<SERVER_INFO mode="write">
<SET_HOST_POWER_SAVER HOST_POWER_SAVER="3" />
</SERVER_INFO>
<USER_INFO mode="write">
<ADD_USER USER_NAME="admin" USER_LOGIN="admin" PASSWORD="%user_password%">
<ADMIN_PRIV value="Y" />
<REMOTE_CONS_PRIV value="Y" />
<RESET_SERVER_PRIV value="Y" />
<VIRTUAL_MEDIA_PRIV value="Y" />
<CONFIG_ILO_PRIV value="Y" />
</ADD_USER>
</USER_INFO>
<RIB_INFO mode="write"></RIB_INFO>
<RIB_INFO mode="write">
<SET_FEDERATION_MULTICAST>
<MULTICAST_FEDERATION_ENABLED VALUE="No" />
<MULTICAST_DISCOVERY_ENABLED VALUE="No" />
<MULTICAST_ANNOUNCEMENT_INTERVAL VALUE="600" />
<IPV6_MULTICAST_SCOPE VALUE="Site" />
<MULTICAST_TTL VALUE="5" />
</SET_FEDERATION_MULTICAST>
</RIB_INFO>
<SSO_INFO mode="write">
<MOD_SSO_SETTINGS>
<TRUST_MODE VALUE="DISABLED" />
<USER_ROLE LOGIN_PRIV="Y" />
<USER_ROLE REMOTE_CONS_PRIV="N" />
<USER_ROLE VIRTUAL_MEDIA_PRIV="N" />
<USER_ROLE RESET_SERVER_PRIV="N" />
<USER_ROLE CONFIG_ILO_PRIV="N" />
<USER_ROLE ADMIN_PRIV="N" />
<OPERATOR_ROLE LOGIN_PRIV="Y" />
<OPERATOR_ROLE REMOTE_CONS_PRIV="Y" />
<OPERATOR_ROLE VIRTUAL_MEDIA_PRIV="Y" />
<OPERATOR_ROLE RESET_SERVER_PRIV="Y" />
<OPERATOR_ROLE CONFIG_ILO_PRIV="N" />
<OPERATOR_ROLE ADMIN_PRIV="N" />
<ADMINISTRATOR_ROLE LOGIN_PRIV="Y" />
<ADMINISTRATOR_ROLE REMOTE_CONS_PRIV="Y" />
<ADMINISTRATOR_ROLE VIRTUAL_MEDIA_PRIV="Y" />
<ADMINISTRATOR_ROLE RESET_SERVER_PRIV="Y" />
<ADMINISTRATOR_ROLE CONFIG_ILO_PRIV="Y" />
<ADMINISTRATOR_ROLE ADMIN_PRIV="Y" />
</MOD_SSO_SETTINGS>
</SSO_INFO>
<SERVER_INFO mode="write">
<SERVER_AUTO_PWR VALUE="RESTORE" />
</SERVER_INFO>
<SERVER_INFO MODE="write">
<SET_POWER_CAP POWER_CAP="0" />
</SERVER_INFO>
</LOGIN>
</RIBCL>
As commented, I think it's a bad idea to parse properties from an XML file using textual methods.
Better let PowerShell parse it for you and pick the properties you need:
$date = (Get-Date).ToString("yyyyMMdd_HHmm")
$scriptDir = Split-Path $MyInvocation.MyCommand.Path # or use: $PSScriptRoot
$outFile = "$ScriptDir\ILOConfigData_$date.csv"
$servers = Get-Content -Path .\servers.txt
$result = foreach ($server in $servers) {
Write-Host "Gathering current ILO configuration for '$server'"
Invoke-Command -ComputerName $server -Credential $Credential -ScriptBlock {
& "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe" /a /w `
"C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml" | Out-Null
# load the xml the hponcfg.exe just created (PowerShell will parse it for you)
$config = New-Object -TypeName System.Xml.XmlDocument
$config.Load("C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml")
# preselect the nodes for MOD_NETWORK_SETTINGS and DIR_USER_CONTEXT_1, DIR_USER_CONTEXT_2 etc.
$networkSettings = $config.RIBCL.LOGIN.RIB_INFO.MOD_NETWORK_SETTINGS
$userContext = $config.RIBCL.LOGIN.DIR_INFO.MOD_DIR_CONFIG.ChildNodes | Where-Object {$_.Name -like 'DIR_USER_CONTEXT*' }
# output a PSObject to be collected in variable $result
[PsCustomObject] #{
Server = $env:COMPUTERNAME
DNSName = $networkSettings.DNS_NAME.VALUE
DomainName = $networkSettings.DOMAIN_NAME.VALUE
IPAddress = $networkSettings.IP_ADDRESS.VALUE
SubnetMask = $networkSettings.SUBNET_MASK.VALUE
GateWay = $networkSettings.GATEWAY_IP_ADDRESS.VALUE
PrimaryDnsServer = $networkSettings.PRIM_DNS_SERVER.VALUE
SecondaryDnsServer = $networkSettings.SEC_DNS_SERVER.VALUE
TertiaryDnsServer = $networkSettings.TER_DNS_SERVER.VALUE
TimeZone = $networkSettings.TIMEZONE.VALUE
# join the UserContext values that are not empty with a NewLine (or any other character you choose)
UserContext = ($userContext.VALUE | Where-Object { $_ -match '\S' }) -join [environment]::NewLine
}
}
}
# remove the extra properties Invoke-Command added
$result = $result | Select-Object * -ExcludeProperty "PSComputerName","RunspaceId","PSShowComputerName"
# save the result as CSV file
$result | Export-Csv -Path $outFile -NoTypeInformation -UseCulture
Result when opened in Excel:

Add Click event to DataTable (powershell)

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;

Changes in SharePoint Powershell CAML Query Effect not Taken

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
}

Get recurring events from sharepoint (2010) with powershell + CAML

* 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

CAML in Powershell with IN CLause

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>