Whats the appropriate Filter syntax for Powershell? - azure-powershell

What is wrong in my filter?
Get-Mailbox -Filter { ( ArchiveStatus -eq 0 ) -AND ( RecipientTypeDetails -eq UserMailbox ) }
Cannot bind parameter 'Filter' to the target. Exception setting "Filter": "Invalid filter syntax. For a
description of
the filter parameter syntax see the command help.
" ( ArchiveStatus -eq 0 ) -AND ( RecipientTypeDetails -eq UserMailbox ) " at position 58."
At C:\Users\username\AppData\Local\Temp\tmp_1retngr4.15m\tmp_1retngr4.15m.psm1:19986 char:9
$steppablePipeline.End()
~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : WriteError: (:) [Get-Mailbox], ParameterBindingException
FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.Exchange.Management.RecipientTasks.GetMailbox

You should use this format:
Get-Mailbox | Where-Object {$_.ArchiveStatus -eq "0" -and $_.RecipientTypeDetails -eq "UserMailbox"}
See reference here.

Put 0 and UserMailbox in quotes.

Related

PowerShell - next day

I am trying to look into some past days to see if they are weekend or bank holiday. If they are failling into weekend, I am trying to run the query with the subsequent Monday of if bank holiday, trying to run it with next day.
The code is below.
function Check-BankHoliday
{
param
(
[Parameter(Position=1, Mandatory=$true)]
$DayChk
)
$JAMSHost="ukjam01apwpd"
if(!(test-path "JD:\")){$null=New-PSDrive JD JAMS $JAMSHost}
$CalendarName = "Default"
$DateTypeName = "BankHoliday"
$BHDates = Get-ChildItem JD:\Calendars\$CalendarName\$DateTypeName | Select-Object StartDate
$BHDayChk=$false
ForEach ($Date in $BHDates)
{
$BHDayDate=$Date.StartDate.ToString("dd/MM/yyyy")
if($BHDayDate -contains $ImpDateChk)
{
$BHDayChk=$true
}
}
Pop-Location
Return $BHDayChk
}
$lastquarter="select convert (char,(SELECT DATEADD(dd, -1, DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0))), 23) as lastquarter"
$lastquarter_day=Invoke-Sqlcmd -Query $lastquarter -ServerInstance "UKWAR01APWPD\WHERESCAPE" -Database RJISDWH
$lastquarter_day= $lastquarter_day.lastquarter
$lastquarter_day = $lastquarter_day.trim(' ')
$lastquarter_day=(Get-Date $lastquarter_day).DayOfWeek
write-host $lastquarter_day
$BHDayChk_lastquarter=Check-BankHoliday $lastquarter_day
if ($BHDayChk_lastquarter -OR $lastquarter_day -eq "Sunday" -OR $lastquarter_day -eq "Saturday")
{
Write-Output "$lastquarter_day had been set as BankHoliday or weekend JAMS Calendars and Changing this to LastWorkDay"
#$lastquarter_day= ConvertTo-Date "today -1 workday" -server $JAMSHost
$lastworkday= ConvertTo-Date "today -1 workday" -server $JAMSHost
$lastquarter=$lastworkday.AddDays(1)
}
else
{
Write-Output "$lastquarter_day is not a BankHoliday or weekend in JAMS Calendars"
}
$SQLquery = "
declare #lastquarter varchar = '$lastquarter_day_date'
declare #sql nvarchar(1000)
set #sql = 'select bp1.sedol, b.benchmark_name, b.description,
bp1.price as '' ' +convert(char,#lastquarter,23) + ' ''
FROM
dbo.ds_benchmark_prices bp1
left join [RJISDWH].dbo.ds_benchmark b on b.sedol=bp1.sedol
where convert(char,bp1.price_date,23) = ''$lastquarter_day'' -- last quarter end
order by b.sedol'
exec (#sql)
"
$lastquarter is returning 2022-12-31 which is a weekend ( Saturday) and if condition below is capturing that being Saturday successfully too.
if ($BHDayChk_lastquarter -OR $lastquarter_day -eq "Sunday" -OR $lastquarter_day -eq "Saturday")
Howevever, how would I add day to Saturday so it runs on the following Monday . I have tried
$lastworkday= ConvertTo-Date "today -1 workday" -server $JAMSHost
$lastquarter=$lastworkday.AddDays(1)
write-host $lastquarter
and that would return 20/01/2023 00:00:00
Below would not work
$lastquarter=$lastquarter.AddDays(1) or $lastquarter=$lastquarter_day .AddDays(1)
I get following error
Method invocation failed because [System.String] does not contain a method named 'AddDays'.
At line:47 char:3
$lastquarter=$lastquarter.AddDays(1)
+ CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MethodNotFound

Powershell, invoke-sqlcmd, export-csv fails to show data if there is more than one result

I have the below code to get data from a SQL DB and export it into a CSV file:
#Server and Database names
$SQLServer = "Servername"
$DB = "DatabaseName"
#SQL Command
$FullScriptSQL="Select * from MyTable WHERE Column = 'TestData'"
#Invoke the command, rename the column headers and export to CSV file
$FullScriptCallLinked = Invoke-Sqlcmd -ServerInstance $SQLServer -Database $DB -Query $FullScriptSQL | select-object #{ expression={$_.Column1};label='Column1 Name'},#{ expression={$_.Column2};label='Column2 Name'},#{ expression={$_.Column3}; label='Column3 Name' },#{ expression={$_.Column4} ; label='Column4 Name' }
Export-CSV -Path ".\ResultFile\FullScript.csv" -inputobject $FullScriptCallLinked -Append -NoTypeInformation
This works perfectly if there is one result. But if there is more than one result, it will show the below in the csv file
I am at my wits end as to why it is doing this. It's obviously the DB parameter data or something to that effect. Been googling for a few days with no luck. Anyone smarter than I able to assist please?
Instead of using Select-Object to rename your columns, which is quite inefficient, you could give the alias to your columns on the query itself:
$SQLServer = "Servername"
$DB = "DatabaseName"
$query = #'
SELECT Column1 AS "Column1 Name",
Column2 AS "Column2 Name",
Column3 AS "Column3 Name",
Column4 AS "Column4 Name"
FROM MyTable
WHERE ColumnX = 'TestData'
'#
Invoke-Sqlcmd -ServerInstance $SQLServer -Database $DB -Query $query |
Export-CSV -Path ".\ResultFile\FullScript.csv" -NoTypeInformation
Also, as in my comment, the code you have on your question is fine and should work, the only problem was using -InputObject instead of piping the results to Export-Csv:
$FullScriptCallLinked | Export-Csv -Path ".\ResultFile\FullScript.csv" -NoTypeInformation
Figured it out. I knew I was close!
#Server and Database names
$SQLServer = "Servername"
$DB = "DatabaseName"
#SQL Command
$FullScriptSQL="Select * from MyTable WHERE Column = 'TestData'"
#Invoke the command, rename the column headers and export to CSV file
$FullScriptCallLinked = Invoke-Sqlcmd -ServerInstance $SQLServer -Database $DB -Query $FullScriptSQL
foreach($i in $FullScriptCallLinked){
select-object #{ expression={$_.Column1};label='Column1 Name'},#{ expression={$_.Column2};label='Column2 Name'},#{ expression={$_.Column3}; label='Column3 Name' },#{ expression={$_.Column4} ; label='Column4 Name' }
Export-CSV -Path ".\ResultFile\FullScript.csv" -inputobject $i -Append -NoTypeInformation
}

Powershell -join Object property values

I'm attempting to produce a variable containing a string of Object properties that are joined with "','". This is to pass into a SQL select where clause. My input looks like this:
foreach ($csv in $CSVFiles) {
$csvOutput = Import-Csv $csv.FullName
$group = $csvOutput | Group-Object order-id, amount-type | Where-Object {$_.Group.'order-id' -ne '' -and $_.Group.'amount-type' -eq 'ItemPrice'}}
Within the above loop. I'm looking to retrieve the order-id and pass it into a new variable $OrdNum. I'm doing this like so:
$OrdNum = $group | Select-Object #{Name='order-id';Expression={$_.Values[0]}}
To perform the join I have attempted:
$OrdNum = ($group | Select-Object #{Name='order-id';Expression={$_.Values[0]}}) -join "','"
This gives ','','','','','','','','','','','',' with no values.
I have also tried:
$OrdNum = ($group | Select-Object -Property 'order-id') -join "','"
Which produces the same result.
I'm expecting $OrdNum to look like 12345','43567','76334','23765 etc.
I'm working under the assumption that $OrdNum is required in that format to pass to this SQL query:
$query = “SELECT ARIBH.ORDRNBR AS [ORDER No'],AROBP.IDRMIT AS [RECPT No'], FROM [XXXX].[dbo].[AROBP] FULL JOIN [XXXX].[dbo].[ARIBH] ON [XXXX].[dbo].[AROBP].[IDMEMOXREF] = [XXXX].[dbo].[ARIBH].[IDINVC] where ARIBH.ORDRNBR IN ('$OrdNum')"
Any assistance on the -join greatly appreciated OR if there is an alternative method to pass the values into SQL avoiding the -join then I'm open to suggestions. Thanks very much.
Thanks to Theo for the updated code. This works as expected.
I have also reworked my existing example with the following. Preserving the original grouping, this also works:
foreach ($csv in $CSVFiles) {
$csvOutput = Import-Csv $csv.FullName -Delimiter "`t"
$group = $csvOutput | Group-Object order-id, amount-type | Where-Object {$_.Group.'order-id' -ne '' -and $_.Group.'amount-type' -eq 'ItemPrice'}
($OrdNum = $csvOutput | Where-Object {![string]::IsNullOrWhiteSpace($_.'order-id')}).'order-id' | Out-Null
$OrdNum = ($OrdNum.'order-id' | Select-Object -Unique) -join "','"
}
I'm not quite sure if I understand the question properly, but I don't really see the need for grouping at all, when all you seem to want is an array of 'order-id' values joined with a comma.
# assuming $CSVFiles is a collection of FileInfo objects
$OrdNum = foreach ($csv in $CSVFiles) {
# import the csv and output the order numbers that match your where condition
(Import-Csv -Path $csv.FullName | Where-Object { ![string]::IsNullOrWhiteSpace($_.'order-id') -and $_.'amount-type' -eq 'ItemPrice'}).'order-id'
}
# if needed you can de-dupe the returned arrau with either `$OrdNum | Select-Object -Unique` or `$OrdNum | Sort-Object -Unique`
# join the array elements with a comma to use in your query
$OrdNum = $OrdNum -join ','
As per your comment, you need the grouping for other purposes later on.
In that case, something like this could work for you:
# create a List object to collect the order-id values
$orders = [System.Collections.Generic.List[string]]::new()
# loop through the CSV files and collect the grouped data in variable $group
$group = foreach ($csv in $CSVFiles) {
# import the csv and output objects that match your where condition
$items = Import-Csv -Path $csv.FullName | Where-Object { ![string]::IsNullOrWhiteSpace($_.'order-id') -and $_.'amount-type' -eq 'ItemPrice'}
if ($items) {
# add the 'order-id' values to the list
$orders.AddRange([string[]]($items.'order-id'))
# output the grouped items to collect in variable $group
$items | Group-Object order-id, amount-type
}
}
# join the elements with a comma to use in your query
$OrdNum = $orders -join ','
P.S. You need the [string[]] cast for the AddRange() method to avoid exception: Cannot convert argument "collection", with value: "System.Object[]", for "AddRange" to type "System.Collections.Generic.IEnumerable``1[System.String]": "Cannot convert the "System.Object[]
" value of type "System.Object[]" to type "System.Collections.Generic.IEnumerable``1[System.String]"."

update sql table for Active Directory createdon and disabled on information

I have a user table in the database that i am trying to update with Createdon date and disabled on date with the data from Active Directory. So far this is what I have:
$SearchRoot = "OU=NonAIQ,OU=FrontOffice,DC=dev,DC=local"
$serverName = "localhost"
#$SearchRoot = "OU=NonAIQ,OU=FrontOffice,DC=dmz,DC=local"
#$serverName = "spoproddb3.dmz.local"
try {
Import-Module "sqlps" -DisableNameChecking
if ((Get-PSSnapin -Name "Quest.ActiveRoles.ADManagement" -ErrorAction SilentlyContinue) -eq $null ) {
Add-PsSnapin "Quest.ActiveRoles.ADManagement"
}
$externalUsers = Get-QADUser -SizeLimit 0 -SearchRoot $SearchRoot | Select-Object whencreated, whenchanged
$externalUsers | % {
$query = #"
Update tbl_EdgeUsers Set CompanyName = '$_.CreationDate'
Where UserUPN = $_.UserPrincipalName;
"#
Write-Host "The query is $query"
Invoke-SqlCmd -ServerInstance $serverName -Query $query -Database "EdgeDW"
}
} finally {
Remove-Module "sqlps" -ErrorAction SilentlyContinue
Remove-PsSnapin "Quest.ActiveRoles.ADManagement"
}
Now for when created, we just grab all the values.
But since AD does not track the Disabled in date, I am using the when changed date since we dont make changes to an account once it is changed.
The part that I am stuck on is about the logic for when changed date. For this I have to check if an account is disabled. If it is the update the table with that date. If an account is not disabled, then ignore that value and set the value in the sql table as '1/1/9999'.
can you guys please help with this logic?
Thank you in advance for any help.
of top of my head maybe something such as this, although thinking about it now, its a nasty way having the invoke-sql inside the foreach loop if the dataset is large, probably better to output the results of the if statement to csv or somewhere then run the invoke-sql against that.
$users = Get-ADUser -Filter * -Properties whenchanged | Select-Object -Property UserPrincipalName, whenchanged, enabled
$disabledsql = #"
update tbl_EdgeUsers Set date = '$user.whenchanged'
Where UserUPN = '$user.UserPrincipalName';
"#
$activesql = #"
update tbl_EdgeUsers Set date = '1/1/9999
Where UserUPN = '$user.UserPrincipalName';
"#
foreach ($user in $users)
{
if ($user.enabled -eq 'False')
{
Invoke-Sqlcmd -ServerInstance $serverName -Query $disabledsql -Database 'EdgeDW'
}
else
{
Invoke-Sqlcmd -ServerInstance $serverName -Query $activesql -Database 'EdgeDW'
}
}

Get-ADuser : The search filter cannot be recognized

Hope you will be able to help. When I issue the below command:
$g = get-ADGroupMember -Server sbintldirectory.com -Identity group1
$n = get-ADGroupMember -Server ad.msdsprd.com -Identity group1
$g.samaccountname | where {$n.samaccountname -notcontains $psitem} | out-file c:\temp\new.txt
$users = gc C:\Temp\new.txt
$a = $users | foreach {Get-ADuser -LDAPFilter "(samaccountname=$_)" -Server dc:3268}
$a | select samaccountname, distinguishedName | out-file c:\temp\list.txt
$group = "CN=group1,OU=Testing,DC=domain,DC=com"
get-content "c:\temp\list.txt" | ForEach `
{
Get-ADuser -LDAPFilter "(samaccountname eq $_)" -Server dc:3268 | ForEach `
{Add-ADGroupMember -Identity $group -Members $_.distinguishedName}
}
Result:
Get-ADuser : The search filter cannot be recognized
At line:10 char:1
+ Get-ADuser -LDAPFilter "(samaccountname eq $_)" -Server dc:3268 | Fo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : The search filter cannot be recognized,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Many thanks.
You are using -LDAPFilter incorrectly on this line:
Get-ADuser -LDAPFilter "(samaccountname=$_)" -Server dc:3268
-LDAPFilter is for writing a filter in LDAP syntax.
You are merely trying to get a specific user, where $_ already represents the username:
Get-ADuser -Identity $_ -Server dc:3268
Refer to the documentation on Get-ADUser for details about the properties.