Modify a value returned from Invoke-sqlcmd - powershell

I've searched for a number of hours now and am unable to figure out how to do this.
I query an MSSQL database that returns 2 columns, one of these values is empty/null but does represent something in the SQL database(I've tested disabling it).
How would I check through what is returned from my query for the empty value and modify this to something else?
$TestQuery = Invoke-Sqlcmd -Database $DB -Query $qcd -ServerInstance "SomeInstance\Instance1" -Verbose
Result:
Activity Setting
-------- -------
All Operation Enabled
Backup Enabled
Restore Enabled
Prune Enabled
Aux Copy Enabled
Schedule Enabled
Archive Check Enabled
Tape Erase Enabled
Offline content Index Enabled
Online Content Index Enabled
Enabled
You can see the last item returned doesn't have a value but does reflect a setting in the application we use, I just want to modify that value to "Value1" for example.
Any help is greatly appreciated, I did try using hashtables but had no idea what I was doing despite several hours of googling.
Edit:
My Query:
SELECT JM.opName AS 'Activity',
CASE action
WHEN 1 THEN 'Disabled'
WHEN 2 THEN 'Enabled'
END AS 'Setting'
FROM JMJobAction AS J
LEFT JOIN JMJobOperationNames JM on JM.opType = J.opType
WHERE clientId = 1
AND appType = 0
AND J.opType != 8
AND appId = 1

You may do the following in PowerShell:
$TestQuery = Invoke-Sqlcmd -Database $DB -Query $qcd -ServerInstance "SomeInstance\Instance1"
$TestQuery |
Where { [string]::IsNullOrEmpty($_.Activity) } | Foreach-Object {
$_.Activity = 'Value1' # Update all empty or nulls with Value1
}
$TestQuery # Contains updated results
Note that this does not update the actual database. You will need a separate query that writes back to the database.
When a database table contains a NULL, it is interpreted as the System.DBNull data type in PowerShell. [System.DBNull]::Value is not the same as $null. So if you only wanted to query for NULL values, then your query could more appropriately be modified to the following:
$TestQuery | Where Activity -is [DBNUll]

I don't know if I understand your question correctly.
I understand that you want to have a default_value when there is no data in a column.
That can be solved in your SQL Query with case. Here an example
[Edit] Based on your added query
SELECT
CASE
WHEN JM.opName is null OR JM.opName = '' THEN "DefaultActivity"
ELSE JM.opName
END AS Activity,
CASE action
WHEN 1 THEN 'Disabled'
WHEN 2 THEN 'Enabled'
END AS 'Setting'
FROM JMJobAction AS J
LEFT JOIN JMJobOperationNames JM on JM.opType = J.opType
WHERE clientId = 1
AND appType = 0
AND J.opType != 8
AND appId = 1

Related

3 Array ForEach Loop SQL Query

I have a SQL Server, SQL Database, and Company array that I need to run a forEach Loop on.
I can do it with a single value array but I have NO idea how to do it for multiple arrays needing the information from the other arrays
Each position in the array corresponds to information about the others. i.e. Company1 uses DB01 with database AR_Agency1, Company2 uses DB02 and database AR_Agency2(See array below).
Ex:
$Company = (“Company1″,”Company2″,”Company3″,”Company4″,”Company5”)
$DatabaseServer = (“DB01”, “DB02”, “DB03”, “DB04”, “DB02”)
$Database= (“AR_Agency1”, “AR_Agency2”, “Agency3”, “Agency4”, “Agency5”)
#SQL Query
$Query = ‘UPDATE tblAsyncJobQueue SET InactiveUntil = NULL’
So what I want to do is something like this
ForEach ($company in $companies) {
#Invoke-Sqlcmd -ServerInstance $DatabasesServer -Database $Database -Query $Query
}
End state I need the query run on each Company database.
As already answered at Powershell.org, a hash table might work. For simple workloads, it's easier to use indexed loops instead of foreach.
Since all the releated info for a company, server and database are at the same location, accessing nth company means nth server and nth database too. Array elements are accessed via [] notation like so,
for($i=0; $i -lt $Company.Length; ++$i) {
write-host $("Process {0} / {1} / {2}" -f $company[$i], $databaseserver[$i], $database[$i])
}
# Output
Process Company1 / DB01 / AR_Agency1
Process Company2 / DB02 / AR_Agency2
Process Company3 / DB03 / Agency3
Process Company4 / DB04 / Agency4
Process Company5 / DB02 / Agency5

How to push data into a "JSON" data type column in Postgresql

I have the following POSTGRESQL table
id | name | email | weightsovertime | joined
20 | Le | le#gmail.com | [] | 2018-06-09 03:17:56.718
I would like to know how to push data (JSON object or just object) into the weightsovertime array.
And since I am making a back-end server, I would like to know the KnexJS query that does this.
I tried the following syntax but it does not work
update tableName set weightsovertime = array_append(weightsovertime,{"weight":55,"date":"2/3/96"}) where id = 20;
Thank you
For anyone who happens to land on this question, the solution using Knex.js is:
knex('table')
.where('id', id)
.update({
arrayColumn: knex.raw(`arrayColumn || ?::jsonb`, JSON.stringify(arrayToAppend))
})
This will produce a query like:
update tableName
set weightsovertime = arrayColumn || $1::json
where id = 20;
Where $1 will be replaced by the value of JSON.stringfy(arrayToAppend). Note that this conversion is obligatory because of a limitation of the Postegre drive
array_append is for native arrays - a JSON array inside a jsonb column is something different.
Assuming your weightsovertime is a jsonb (or json) you have to use the concatenation operator : ||
e.g:
update the_table
set weitghtsovertime = weightsovertime||'[{"weight": 55, "date": "1996-03-02"}]'
where id = 20;
Online example: http://rextester.com/XBA24609

How can I access properties of the IpPermissions property of Get-EC2SecurityGroup?

I am trying to get a list of security groups. (Successful - Using Get-EC2SecurityGroup)
Get a list of the specific IPPermissions associated with each security group. ( Successful - Using (Get-EC2SecurityGroup).IpPermissions )
Only return results where the FromPort = "xxx" ( Unsuccessful - Not sure how to access the FromPort property that is returned in the result list )
Ultimately what I am trying to accomplish is:
Get a list of existing security groups, and loop through each group.
While looping through each group, call the IpPermissions, and look for the specific FromPort "xxx".
If the FromPort is a match, record the other properties: (FromPort, IpProtocol, IpRanges, ToPort, UserIdGroupPairs)
Problem I am having
I am not sure how to do a loop using the amazon objects
I cant seem to access the properties even though they appear to be named and have values.
I have tried using -Filter with many different iterations, with no success.
The documentation seems self-referencing, and the examples I have run across dont get down to this level of detail.
Results returned from (Get-EC2SecurityGroup).IpPermissions
FromPort : 123
IpProtocol : tcp
IpRanges : {0.0.0.0/0}
ToPort : 123
UserIdGroupPairs : {}
Here's an example that does as you've described:
Filters security group objects by FromPort
Of the matched security groups, output IpProtocol, IpRanges, ToPort, and UserIdGroupPairs.
Code:
# Example using port 22
PS C:\> $port = 22
PS C:\> Get-EC2SecurityGroup |
? { $_.IpPermissions.FromPort -eq $port } |
% { $_.IpPermissions } |
Select -property IpProtocol, IpRanges, ToPort, UserIdGroupPairs
Output:
IpProtocol IpRanges ToPort UserIdGroupPairs
---------- -------- ------ ----------------
tcp {0.0.0.0/0} 22 {}
... ... ... ...

Using "Select" in SharePoint list query

I have a list with a large number of datapoints. (130 columns, 31000 items). I run certain scripts to data-mine and/or update that info. One trick I use to speed up processing time is to pull the whole list into an array at the beginning. This allows powershell to query the array instead of going back to the list each time.
In these scripts I'm usually only searching a few of the fields, making it inefficient to pull all 130+ columns I'm hoping looking for a way to limit what fields are being pulled in.
In the below script, everything works fine until I add the "Select" part of the query. I then get an error of "Unable to index into an object of type System.Management.Automation.PSObject".
Any pointers are greatly appreciated!
$oList = $Web2.Lists["Forecasting data source"]
$aList = $Web.Lists["ArrayTest"]
filter MyFilter {if ($_["CHGTaskRegion"] -eq "Syracuse") {$_}}
$list = $oList.Items | MyFilter | Select ["CHGTaskFacility"],["CHGTicketNumber"]
$list | ForEach-Object {
$ListItem = $aList.Items.Add()
$ListItem["Title"] = [string]$_["CHGTaskFacility"]
$ListItem["Number"] = [string]$_["CHGTicketNumber"]
$ListItem.Update()
}
EDIT:
This is way after the fact but I saw this old post of mine and figured it was worth coming back to. The proper method isn't actually to pull in the whole list and then search it. The right way is to simply get just the items you wanted in the first place using a CAML query. Like so:
$spqQuery = New-Object Microsoft.SharePoint.SPQuery
$spqQuery.Query =
" <Where>
<Eq>
<FieldRef Name='CHGTaskRegion' />
<Value Type='File'>Syracuse</Value>
</Eq>
</Where>"
$spqQuery.ViewFields = "<FieldRef Name='CHGTaskFacility' /><FieldRef Name='CHGTicketNumber' />"
$spqQuery.ViewFieldsOnly = $true
$splListItems = $splList.GetItems($spqQuery)
Have you tried:
$list = $oList.Items | MyFilter | Select {$["CHGTaskFacility"]}, {$["CHGTicketNumber"]}
Add underscore after dollar signs. For some reason _ is not showing up in the code above.
/Pawel
I think the code should be :
$list = $oList.Items | MyFilter | Select CHGTaskFacility,CHGTicketNumber
The way you wrote it, means that you tried to type cast, anything between [ ] being the type.
And so it got confused.
CHGTaskFacility and CHGTicketNumber are properties of the $list of objects, and so Select CHGTaskFacility,CHGTicketNumber is sufficient for Powershell to select them.
UPDATE:
I think the filter code may be incorrect:
filter MyFilter {if ($_."CHGTaskRegion" -eq "Syracuse") {$_}}

Adding a datetime to a datatable with the current datetime?

I'm trying to add a field to a datatable with the current datetime. I want to add it here so that when I use another piece of code to create the table, it creates it as datetime (add-sqltable, for what it's worth).
#create the datatable
$quer = invoke-sqlcmd2 -serverinstance myservername -database "tempdb" -query "select ##servername as servername" -As 'DataTable'
#now add the datetime field
$quer.columns.add("InsDate",[DateTime])
At this point I get stuck. This doesn't work:
$quer | %{$_.InsDate = get-date}
I get this error message:
Exception setting "InsDate": "Unable to cast object of type
'System.Management.Automation.PSObject' to type 'System.IConvertible'.Could
n't store <2/26/2013 11:26:23 AM> in InsDate Column. Expected type is DateTime."
Changing the format doesn't work either. Is there some way to do this? Thanks.
Try this:
$quer | %{[datetime]$_.InsDate = get-date}
or this:
$quer | %{$_.InsDate = [datetime](Get-Date)}
I don't have the ability to test your specific case, but I believe one of them should work.
Edit: Changed closing ')' to '}' in second to fix answer.
Here's a workaround:
$date = get-date
$quer | %{$_.InsDate = [DateTime]$date}
Found here:
DateTime parsing in PowerShell
Hmm might be missing the obvious here, but can't you adjust your SQL query to just pull the datetime at the source?
Something like this:
select
##servername as [servername],
GETDATE() as [DateTime]
That is probably what I would do, rather than fudging it in later! :D