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

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 {}
... ... ... ...

Related

How can I filter out custom rules from Azure WAF logs?

I am using the following query to monitor Azure WAF, it works fine but I want to filter out custom rule hits from the query and only show blocks by MSFT Default Rulesets but I cannot find how to do that
The following query show blocks from custom rules AND MSFT default rules, I want to only show MSFT default rule set blocks
I understand I can exclude the name or all my custom rules but that will be difficult to maintain
AzureDiagnostics
| where ResourceProvider == "MICROSOFT.NETWORK" and Category == "FrontdoorWebApplicationFirewallLog"
| where action_s == "Block"
| where requestUri_s contains "xxx" or requestUri_s contains "xxx" or requestUri_s contains "xxx" or requestUri_s contains "xxx" or requestUri_s contains "xxx" or requestUri_s contains "xxx"
| extend ParsedUrl = parseurl(requestUri_s)
| summarize BlockCount = count() by TimeStamp = bin(TimeGenerated, 3h), ClientIP = clientIP_s, RuleName = ruleName_s, Host = host_s, PATH = tostring(ParsedUrl.Path)
| order by TimeStamp desc

Modify a value returned from Invoke-sqlcmd

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

PowerShell - xml files with conflicting multiple namespaces on the same element name

Related to PowerShell 5.1
I was playing around with XML to show how to handle conflicting namespaces. Here's the example I created:
<Employees>
<ms:Employee id='1' xmlns:ms="MicrosoftEmployees">
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</ms:Employee>
<ms:Employee id='2' xmlns:ms="MicrosoftEmployees">
<FirstName>Paul</FirstName>
<LastName>Allen</LastName>
</ms:Employee>
<ap:Employee id='1' xmlns:ap="AppleEmployees">
<Name>Steve Jobs</Name>
</ap:Employee>
<ap:Employee id='2' xmlns:ap="AppleEmployees">
<Name>Steve Wozniak </Name>
</ap:Employee>
</Employees>
The scenario might be combining data from two different companies.
PowerShell demonstration program:
cls
$filename = "c:\XMLClass\IntroSamples\Sample05_Simpler_Namespace.xml"
[xml]$xmlDoc = Get-Content $filename
$xmlDoc.Employees.Employee[0]
$xmlDoc.Employees.Employee[1]
$xmlDoc.Employees.Employee[2]
$xmlDoc.Employees.Employee[3]
Output:
id ms FirstName LastName
-- -- --------- --------
1 MicrosoftEmployees Bill Gates
2 MicrosoftEmployees Paul Allen
1
2
Is there anyway to get a more logical output?
It seems like PowerShell locks into the first schema it sees for the Employee element, then cannot show the Name element of the Apple employees. This actually makes sense, but I was just checking to see if there is something fancier to handle this that I might be missing.
I know I could use SelectSingleNodes and XPath, but was just trying to see if and how PowerShell could handle this "out of the box".
If I reverse the code:
$xmlDoc.Employees.Employee[2]
$xmlDoc.Employees.Employee[3]
$xmlDoc.Employees.Employee[1]
$xmlDoc.Employees.Employee[0]
Then the output is:
id ap Name
-- -- ----
1 AppleEmployees Steve Jobs
2 AppleEmployees Steve Wozniak
1 ms:Employee
2 ms:Employee
Use format list to see all the properties. Format-table doesn't handle different sets of properties well.
$xmldoc.employees.employee | format-list
id : 1
ms : MicrosoftEmployees
FirstName : Bill
LastName : Gates
id : 2
ms : MicrosoftEmployees
FirstName : Paul
LastName : Allen
id : 1
ap : AppleEmployees
Name : Steve Jobs
id : 2
ap : AppleEmployees
Name : Steve Wozniak

Get nested values in one line

I'm new to powershell so I had a simple question. Suppose I have the following powershell code:
$t = Get-SomeData -someParam someParamValue
$t.SomeProperty.SomeNestedField
The second command above will print the value of SomeNestedField, which is nested inside t's property called someProperty
Can I combine these two lines into one powershell command (perhaps through piping), so that the output of the second command comes from just one command overall ?
Requirement is that it should print the value, not assign it to some powershell variable ..
Perhaps something like:
Get-SomeData -someParam someParamValue | SomeProperty | SomeNestedField
Some info that might help out:
Suppose I change above code to this:
$t = Get-SomeData -someParam someParamValue
$u = $t.SomeProperty
$t.GetType()
$u.GetType()
When I execute $t.GetType(), the BaseType listed is a class, but if I do $u.GetType(), it's BaseType is listed as System.ValueType
You can use SELECT aka SELECT-OBJECT
Get-SomeData -someParam someParamValue | select -ExpandProperty SomeProperty
Or ()
(Get-SomeData -someParam someParamValue).SomeProperty.SomeNestedField

Powershell replacing string with multiple values

I am new to powershell. Here are some code examples will help me to explain:
The first example gives the correct output I want which is a list of values, two values in this example, under OrganizationalUnitDistinguishedNames
PS C:\Users\Administrator\Desktop> $test=Get-APSDirectoryConfigList -DirectoryName test.com
PS C:\Users\Administrator\Desktop> $test
CreatedTime DirectoryName OrganizationalUnitDistinguishedNames ServiceAccountCredentials
----------- ------------- ------------------------------------ -------------------------
12/4/2017 9:26:50 AM test.com {OU=t1,DC=acc, OU=t2,DC=test} Amazon.AppStream.Model.ServiceAccountCredentials
PS C:\Users\Administrator\Desktop> $test.OrganizationalUnitDistinguishedNames
OU=t1,DC=acc
OU=t2,DC=test
However, the following command treats two values "OU=t2,DC=test,OU=t1,DC=acc" as a single string. What is the correct syntax to create with two separate values instead of a single string? I have tried different ways (with or without double quotes), they don't work.
PS C:\Users\Administrator\Desktop> $test=New-APSDirectoryConfig -DirectoryName test.com -OrganizationalUnitDistinguishedName "OU=t2,DC=test,OU=t1,DC=acc" -ServiceAcco
untCredentials_AccountName TEST\serviceaccount -ServiceAccountCredentials_AccountPassword secret_password
PS C:\Users\Administrator\Desktop> $test
CreatedTime DirectoryName OrganizationalUnitDistinguishedNames ServiceAccountCredentials
----------- ------------- ------------------------------------ -------------------------
12/4/2017 9:33:25 AM test.com {OU=t2,DC=test,OU=t1,DC=acc} Amazon.AppStream.Model.ServiceAccountCredentials
PS C:\Users\Administrator\Desktop> $test.OrganizationalUnitDistinguishedNames
OU=t2,DC=test,OU=t1,DC=acc
Try:
$OUDNArray = #("OU=t2,DC=test","OU=t1,DC=acc")
$test=New-APSDirectoryConfig -DirectoryName test.com -OrganizationalUnitDistinguishedName $OUDNArray -ServiceAccountCredentials_AccountName TEST\serviceaccount -ServiceAccountCredentials_AccountPassword T3st12345
According to the AWS Appstream Docs:
Parameters
-OrganizationalUnitDistinguishedName <String[]> The distinguished names of the organizational units for computer accounts.
Required? False Position? Named Accept pipeline input? False
The OrganizationalUnitDistinguishedName accepts an array.