PowerShell DataTable delete column containing value "description" - powershell

I would like to delete all empty rows from the DataTable below as well as delete the column containing the value "description". I am able to delete all empty rows; however, I can't figure out how to also explicitly delete description from the DataTable.
Original DataTable:
dev_id : 4721
office_id : 355
name : Bobby
ip : 10.10.10.1
ipv6 : 2001:1930:ff28:ff00::1
mac :
serial_num : XX234555
platform : Supercode
:
description : I;need;to;delete;this;
:
:
max_speed : 100000
Code:
$myreader = $mycommand.ExecuteReader()
$DevicesDataTable.Load($myreader)
$myconnection.Close()
$Columns = $DevicesDataTable.Columns.Count
$Rows = $DevicesDataTable.Rows.Count
for ($r = 0; $r -lt $Rows; $r++) {
$Empty = 0
for ($c = 0; $c -lt $Columns; $c++) {
if (($DevicesDataTable.Rows[$r].IsNull($c)) -or ($DevicesDataTable.Rows[$r].Equals("description"))) {
$Empty++
}
}
if ($Empty -eq $Columns) {
$DevicesDataTable.Rows[$r].Delete()
}
}
# Delete
$DevicesDataTable.AcceptChanges()
Write-Output $DevicesDataTable
Result:
Note DataTable below still shows description:
dev_id : 4721
office_id : 355
name : Bobby
ip : 10.10.10.1
ipv6 : 2001:1930:ff28:ff00::1
serial_num : XX234555
platform : Supercode
description : I;need;to;delete;this;
max_speed : 100000
Note: I am able to identify the column containing "description", however, I'm not sure how to delete the respective row via the correct method:
if ($DevicesDataTable.Columns[$c].ColumnName.Equals("description"))

You can drop a column from the data table by calling Remove() on the Columns collection:
$DevicesDataTable.Columns.Remove('description')

Related

Split PSCustomObjects in to strings/array

Hi I have n sum of objects for each Node like this:
NodeName : 11111
System.AreaId : 2375
System.AreaPath : Project
System.TeamProject : Project
System.NodeName : Project
System.AreaLevel1 : Project
Every node can have different objects in it.
How can I split them to an arrays/strings without specifying the object name so I can create foreach separate object loop?
mklement0 beat me to what I was going to post. Since I have the code drafted already I will post it.
Like mklement0 said in comments, you can access object properties through use of .psobject.Properties. Below in the code I am using a switch statement to check if an object contains a specific property.
$objs = #(
[pscustomobject]#{
AreaId = 2375
AreaPath = ''
TeamProject = 'Project2'
NodeName = ''
AreaLevel1 = ''
},
[pscustomobject]#{
AreaId = 342
AreaPath = ''
TeamProject = 'Project2'
Color = 'Red'
}
)
switch ($objs) {
{ $_.psobject.properties.name -contains 'Color' } {
'Object contains Color property'
}
{ $_.psobject.properties.name -contains 'NodeName' } {
'Object contains NodeName property'
}
Default {}
}

Tidying up a powershell script

So I need help tidying up a script that I have. The purpose of this script is to make 18 different sql files based on the data below 18 different column headers. What my script does now is make 1 sql file based on which column I choose to input via "Read-Host". This is my current script
function get-header
{Read-Host "Type the Column header betwen B-Z for which sql files needs to be created"
}
function get-column
{
Read-Host "Type the Column number"
}
do
{
$val = get-header
}
while(!($val))
do
{$col = get-column
}
while(!($col))
switch ($val)
{
"B"{$column = "1"}
"C"{$column = "2"}
"D"{$column = "3"}
"E"{$column = "4"}
"F"{$column = "5"}
"G"{$column = "6"}
"H"{$column = "7"}
"I"{$column = "8"}
"J"{$column = "9"}
"K"{$column = "10"}
"L"{$column = "11"}
"M"{$column = "12"}
"N"{$column = "13"}
"O"{$column = "14"}
"P"{$column = "15"}
"Q"{$column = "16"}
"R"{$column = "17"}
"S"{$column = "18"}
"T"{$column = "19"}
"U"{$column = "20"}
"V"{$column = "21"}
"W"{$column = "22"}
"X"{$column = "23"}
"Y"{$column = "24"}
"Z"{$column = "25"}
default { $column = 'Unknown' }
}
if ($column -eq 'Unknown')
{
Write-Warning "Not a valid input"
return
}
$csv = Import-Csv "Indices Updates - September 2018.csv" -Header 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
$date = (Get-Date -Format "MM/dd/yyyy").Replace("-","/")
$sql = #("INSERT INTO benchmark_values(created_at,benchmark_id,date,amount,created_by_username)
foreach($data in $csv)
{
$secondcolumn = [int]$column + 1
$sql += "('$date',$col,'$($data.1)',$($data.$secondcolumn),'BPylla'),"
}
$sql | Out-File "sqldata.sql"
Now I want to get rid of read-host entirely because I dont want to input any values. I also will give an example of what the csv file looks like and what the sql file should look like.
So the goal is to produce different sql files from each column of information using the the sql format posted. I already have the template for that in my script now, I just need the script to create all the sql files based on headers and still input the data below the headers in the new sql files. Any help would be greatly appreciated! Thanks!

OR condition inside AND condition in createQueryBuilder depend on condition

We need all active records using "tag" which matches search string in createQueryBuilder.
For Ex: Search for "NEW YORK" which internally search for "NEW" or "YORK" in Tags "new, ab, other"
My CODE:
$query = $this->createQueryBuilder();
$query->field('status')->equals("active");
if (isset($params["search"]) && !empty($params["search"])) {
$searchArr = explode(" ", $params["search"]);
foreach ($searchArr as $searchVal) {
$query->addOr(
$query->expr()->addOr($query->expr()->field('tags')->equals(new \MongoRegex('/.*' . $searchVal . '.*/')))
);
}
}
It will give result active OR (tag1 Or tag2). Expected result active AND (tag1 Or tag2)
Any suggestions?
Replace this
foreach ($searchArr as $searchVal) {
$query->addOr(
by this
foreach ($searchArr as $searchVal) {
$query->addAnd(

Sort and delete duplicates in multidimensional array

I have an multidimensional Array and want to sort it by the date and delete the duplicate entries (by date).
$arrayPlaces = [System.Collections.ArrayList]#()
and that is how the Array looks like:
$arrayPlaces.Add(($mailBarcodeInformation[2], $mailScannedStart.Substring(22), "", "", "", "", "", ""))
The empty fields are filled later. The second field $mailScannedStart.Substring(22) is the time and the Array should be sorted by that and the duplicates should also be removed.
I searched a lot but couldn't find any help.
A common approach is to add a custom object into an array and use the buit-in cmdlet sort -unique. It's much more readable:
$arrayPlaces = [System.Collections.ArrayList]#()
#.........
$arrayPlaces.Add([PSCustomObject]#{
barcode = $mailBarcodeInformation[2]
time = $mailScannedStart.Substring(22)
foo1 = ''
foo2 = ''
foo3 = ''
}) >$null
#...........
$sorted = $arrayPlaces | sort time -Unique
However, since you already use a .NET class you can switch to a fast .NET SortedDictionary, which automatically sorts and deduplicates the collection when items are added:
$arrayPlaces = [Collections.Generic.SortedDictionary[string,array]]#{}
Adding and overwriting the old value:
$key = $mailScannedStart.Substring(22)
$arrayPlaces[$key] = $mailBarcodeInformation[2], $key, "", "", "", "", "", ""
Checking for presence of an item using its key:
if ($arrayPlaces.ContainsKey($key)) { ....... }
Removing:
[void]$arrayPlaces.Remove('foo')
Accessing:
$items = $arrayPlaces['foo']
$item = $arrayPlaces['foo'][0]
Enumerating (faster):
foreach ($items in $arrayPlaces.Values) {
# .........
}
Enumerating/pipelining (slower):
$arrayPlaces.Values | foreach { $_[0] = $_[1] + $[2] }

How to get returned data from mongoDB in Perl?

I read http://api.mongodb.org/perl/current/MongoDB/Examples.html and seems to be only documentation from mongoDB on Perl. How do I get my query result from mongoDB in perl. Let us say into Hash. I have successfully made connection to the db so far. I managed to do inserts into collections. Now how do I issue select query and get its returned data into hash or something similar?
Update:
Example of my data
{
"_id" : ObjectId("asdhgajsdghajgh"),
"country" : "USA"
"city" : "Boston"
}
{
"_id" : ObjectId("asdhgajsdghajgh"),
"country" : "USA"
"city" : "Seattle"
}
{
"_id" : ObjectId("asdhgajsdghajgh"),
"country" : "Canada"
"city" : "Calgary"
}
My code
my $cursor = $my_collection
->find({ country => 1 })
;
while (my $row = $cursor->next) {
print "$row\n";
}
This code is not resulting any output.
I want to basically iterate through the entire collection and read document by document.
Not sure what I am doing wrong. I used the code above. I changed $cur->next to $cursor->next I am guessing it was a typo. I appreciate all the answers so far.
That's not the official documentation. Head right to the CPAN:
MongoDB::Tutorial
MongoDB::Examples
Iterating results is pretty similar to the DBI way:
use Data::Printer;
use MongoDB;
# no query is performed on initialization!
my $cursor = $collection
->find({ active => 1, country => 'Canada' }) # filter "active" records from Canada
->sort({ stamp => -1 }) # order by "stamp" attribute, desc.
->limit(1000); # first 1000 records
# query & iterate
while (my $row = $cur->next) {
# it is 'p', from Data::Printer!
p $row;
}