Linq VB.net to PowerShell 5.1 - vb.net

I have a Linq query in VB.Net which works fine.
I now need to transform this to work in PowerShell by using the static Linq methods.
I figured out how to do simple select and where queries but especially the grouping and "new with" I am not sure how to translate...
The goal is to find out if the entries (dataRows) in a Data Table that do have the same AttributeKey also have the same AttributeValue AndAlso the same AttributeType or not.
Dim dt As New DataTable
dt.Columns.Add("AttributeKey")
dt.Columns.Add("AttributeValue")
dt.Columns.Add("AttributeType")
dt.Rows.Add("Action", "MakeItSo", "System.String")
dt.Rows.Add("Action", "MakeItSo", "System.String")
dt.Rows.Add("Action", "True", "System.Boolean")
dt.Rows.Add("Single", "MyVal", "System.String")
Dim srcGroupBy = dt.AsEnumerable.GroupBy(Function(Attrib) New With
{
Key .AttributeKey = Attrib.Field(Of String)("AttributeKey")
}).
Where(Function(grp) grp.Count() > 1).
Select(Function(grp) New With {
Key .AttributeKey = grp.Key.AttributeKey,
Key .CounterVal = grp.GroupBy(Function(AttributeVal) AttributeVal.Item("AttributeValue").ToString().ToUpper()).Count(),
Key .CounterType = grp.GroupBy(Function(AttributeType) AttributeType.Item("AttributeType").ToString().ToUpper()).Count(),
Key .ExistsInInconsistentStates = grp.GroupBy(Function(x) x.Item("AttributeValue").ToString().ToUpper()).Count() > 1 Or
grp.GroupBy(Function(x) x.Item("AttributeType").ToString().ToUpper()).Count() > 1
})
I could also solve this without Linq in PS like this:
[PSObject]$res=$DV |
Group-Object -Property "AttributeKey" |
Where-Object -FilterScript {$PsItem.Count -gt 1} |
Select-Object -Property #("Name","Count",#{Name='CountDistinctVals';Expression=`
{
$PsItem.Group.AttributeValue |
Select-Object -Unique |
Measure-Object |
Select-Object -ExpandProperty "Count"
}`
},#{Name='CountVals';Expression=`
{
$PsItem.Group.AttributeValue |
Select-Object |
Measure-Object |
Select-Object -ExpandProperty "Count"
}`
},#{Name='CountDistinctTypes';Expression=`
{
$PsItem.Group.AttributeType |
Select-Object -Unique |
Measure-Object |
Select-Object -ExpandProperty "Count"
}`
},#{Name='CountTypes';Expression=`
{
$PsItem.Group.AttributeType |
Select-Object |
Measure-Object |
Select-Object -ExpandProperty "Count"
}`
})
I can then evaluate the first row and check if distinct count = all count which would also meet my requirement for that particular use case.
Anyway, it would be still interesting for me to know whether it could be done also in Linq with PS. (Not saying that this would always be the preferred way)
Thanks
Chris

Related

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.

how to check, if authenticated user in array from db

In my DB I have a project table which has
project
id | title | users |
1 | First | 1,2,3 |
2 | Second| 2,6 |
how can I check Yii::app()->user->id contained in users field? I want to check, if true then show row in gridview.
Which $criteria must I use?
Use LIKE query for checking your user id exist or not in users column.
$user = Yii::app()->user->id;
$result = Yii::app()->db->createCommand('SELECT * FROM project WHERE users LIKE "%'.$user.'%"')->queryAll();
if(count($result)){
//Your other scripts to show in grid view
}
If you have a Project model class then you also can use:
$user = Yii::app()->user->id;
$criteria = new CDbCriteria;
$criteria->select = '*';
$criteria->compare('t.users', $user, true);
$results = Project::model()->findAll($criteria);

Select query question

I have a table in a mysql-database with the fields
"name", "title", "cd_id", "tracks"
The entries look like this:
Schubert | Symphonie Nr 7 | 27 | 2
Brahms | Symphonie Nr 1 | 11 | 4
Brahms | Symphonie Nr 2 | 27 | 4
Shostakovich | Jazz Suite Nr 1 | 19 | 3
To get the tracks per cd (cd_id) I have written this script:
#!/usr/bin/env perl
use warnings; use strict;
use DBI;
my $dbh = DBI->connect(
"DBI:mysql:database=my_db;",
'user', 'passwd', { RaiseError => 1 } );
my $select_query = "SELECT cd_id, tracks FROM my_table";
my $sth = $dbh->prepare( $select_query );
$sth->execute;
my %hash;
while ( my $row = $sth->fetchrow_hashref ) {
$hash{"$row->{cd_id}"} += $row->{tracks};
}
print "$_ : $hash{$_}\n" for sort { $a <=> $b } keys %hash;
Is it possible to get these results directly with an appropriate select query?
"SELECT cd_id, SUM(tracks) as tracks FROM my_table GROUP BY cd_id"
edit: see here for further information and other things you can do with GROUP BY: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
Use an aggregate function
SELECT `cd_id`, SUM(`tracks`) AS s
FROM `your_table`
GROUP BY `cd_id`