AWS EC2 powerShell tips

Ever find yourself looking for ways to use powerShell? maybe that’s just me. Hahaha

Recently I was supporting some EC2 in the cloud testing some new AWS features and services and I found my self locked out and released this machine was not domain joined but I couldn’t login.

With the windows PowerShell cmdlets swirling around my head I recalled a similar situation with a dev hyper-v client. This made me remember the root cause was an expired local user password.

I am not sure if I have ever had the chance to share the:

Get-LocalUser
Set-LocaUser

These two commands are a good way to quickly check users and set passwords. Let’s see if you can make use of these by tapping into

get-Help

My issue was resolved by using amazons PowerShell in the browser and changing the local users password expiration policy. I am sure other sys admins and cloud admins can leverage this using various powerShell cloud instances to connect to their cloud servers and clients. Expiration policy comes in handy when you only want the user to access the infra temporarily for development purposes.

I hope this finds that local user experience easier to manage due to the considerable amount time the powerShell devs put in to do this for admins.

Let me know if you used this differently, like script disabling and creating local accounts or the default administrator account.

Confluence CVE Vulnerability Checker

Some people host confluence from Atlassian on local infrastructure and no access to the cloud.
I was curious if this could be an issue with learning whether or not your version is vulnerable.

So here is something I noticed to be helpful to all Confluence admins that want to check and not worry about the deep distracted deep reading needed in a slew of other CVE and parse relevant details to only their versions.

I wrote this to not leave out those behind proxies so have fun securing your instances.

function Check-ConfluenceSecurity
{
<#
.Synopsis
   checks confluence from the internet using network and version parameters
.DESCRIPTION
   checks Atlassian confluence from the internet using network and version parameters proxy and credentials are optional and this should return cve with your version numbers.
THIS DOES NOT FIX CONFLUENCE! This just provides a report with CVE containing your version number for Administrator evaluation.
.EXAMPLE
  Check-ConfluenceSecurity -Network VPN -version '7.18.1' | ft -Wrap
   #>
    [CmdletBinding( 
                  SupportsShouldProcess=$true, 
                  PositionalBinding=$false,
                  HelpUri = 'http://www.powershell.city/',
                  ConfirmImpact='Medium'
                  )]

 

 Param
    (
        
        [Parameter()][ValidateSet("Standard","VPN")]$Network='Standard',
        [Parameter(mandatory=$true)]$version,
        [Parameter()]$proxy

)

switch($Network)
{
Standard{Invoke-WebRequest 'https://atst-data.atl-paas.net/healthcheck/cve/confluence.json'| ConvertFrom-Json|where description -like "*$version*"|select cveid,description -OutVariable result | Out-Null}
VPN{Invoke-WebRequest 'https://atst-data.atl-paas.net/healthcheck/cve/confluence.json' -proxy $proxy -ProxyCredential $(Get-Credential -Message "Enter Proxy Credentials")| ConvertFrom-Json|where description -like "*$version*"|select cveid,description -OutVariable result | Out-Null}

 

}#endswitch
return $result| sort cveid -Unique 
}

Feel free to stay secure!
this function returns parsed data from :
www.atlassian.com/trust/security/advisories

Disable Bitlocker

Disabling bitlocker with PowerShell is as easy as you might not believe.

You must first unlock the drive

Unlock-BitLocker -MountPoint D:

Then you can do some object juggling to select the one you want fast using tab completion.

Something to consider, we know you can do this in the GUI, however the GUI i s point and click, where in the city of PowerShell you can use combo moves by combining cmdlets and saving on processing power, battery life and not sacrificing performance.

Understand the Error of your ways.

We all have different way to accomplish a task that is given to us. Sometimes we make mistakes and we are panicking to fix the errors better know as PowerShell error handling.

Sometimes, knowing your mistakes is better than googling or trying to the answers. I’m comfortable with PowerShell, the errors are defined in a pretty straight forward way.

The errors come out as objects with properties too and this can come in handing when you want your script to show a specific error for a certain function.

So take some time and look at cmdlets write-error and also using the cmdlet binding parameters found on built in PowerShell commands “-ErrorAction” and combining them with try, catch, and finally statements that are the dream team when it comes with error handling.

There are a number of different option regarding this and what you need, is what you should choose. try them all on and see what shoe fits.

5.1 options

Newer Version of PowerShell has a great deal of newer functionality and choices.

Powershell 7.2

Notice how the break command drops into a debug prompt instead. This helps with Scripting and finding… bugs. so now that we have squashed that the next thing is to find was to have it help you to avoid red letters and failed automation. Share what you have done with it.

Storing Objects and Text.

The best case scenario in my opinion of using variables is to leverage objects. I know some of the users prefer text only, but objects carry much more information, that can be logged or leveraged. Here is an example:

Having computer’s name vs and object with multiple properties.

the first 3 lines is easier to type, but less flexible.

The 3 last lines are are magic…

This is just scratching the surface

Having the same data in the variable and then manipulating them to give you what you want so that the data is applicable and even passed to more commands.

So lets say there is another propery or point of interest that needs to be associated with the computer and user….

Can you do that with text and then create a fancy excel sheet? maybe if you want to have panic attacks about deadlines. It is all about the objects of desire lol.

Lets add a serial number:

static data addition

Lets get Dynamic like a duo (no Microsoft pun) with dynamic Data

This object is now dynamic and can be used to extrapolate data inside of a remote script, report, or function.

Brain Check… share your real world applications of create dynamic and static objects.

If you cannot think of any then use the code to inventory your home PCs. Don’t forget to add the serial number:

Get-CimInstance Win32_bios

Don’t Forget to select the properties you need or expand them to just get the inside of the object.

Want to learn what is selectable with any object? Indicate the object and pipe it to get-member.

Get-CimInstance Win32_bios | get-member

Using Object properties

A lot of people see PowerShell as conversion tool, but it can do so much more.

It can uninstall apps, inventory your applications. Rename files to a standard. Create shares, modify files and sessions and give an Administrator access to a computer without interrupting a session.

It is built on .net/c# so it can do everything a program can. You just have to know your property and methods on your objects.

I am mainly speaking about windows platform. I may do a write up on Linux impact.

I can write excel, word files with out office being installed, send emails and query websites for remote data. Consolidated information and write to databases. The list is ridiculous.

I wanted to interact more so I would like to take on a challenge from the comments. What is something you think you cannot do in PowerShell?!

PowerShell Importing Data from Excel

If you want to import Excel data I recommend giving the people who toke the time to develop this module Import-Excel. It can be Read about on the PSGallery here: https://www.powershellgallery.com/packages/ImportExcel/

After reading we will try to find the module using built im module package for powershell :

“find-module importexcel”

we can pipe this into an “install-module” command with a few parameters to ensure a smooth install.

find-module importexcel | install-module -Scope CurrentUser -SkipPublisherCheck

this should install the module and you import Excel workbooks as easily as you can excel and text files.

Import-Excel, Export-Excel with a few extra parameters like -worksheet so you can target data sets and even write reports with details on different pages!

I use this to write share permission reports with different shares on different worksheets. So other things you can do is a security audit on servers and write a server to each worksheet and then write a pivot table for a summary report.

I how you download and support this module because it is nothing short of amazing, you dont have to have the excel application installed to import or export to Excel!

Convert from OATime

One of my favorite reasons I love PowerShell is because can tap into its programming roots for added power. I will demonstrate later in my post.

If you notice the data is the same in both fields and the send row and under the time column the data type is changed and now actually displays a date.

Here is why:

An OLE Automation date is implemented as a floating-point number whose integral component is the number of days before or after midnight, 30 December 1899, and whose fractional component represents the time on that day divided by 24. For example, midnight, 31 December 1899 is represented by 1.0; 6 A.M., 1 January 1900 is represented by 2.25; midnight, 29 December 1899 is represented by -1.0; and 6 A.M., 29 December 1899 is represented by -1.25.

The base OLE Automation Date is midnight, 30 December 1899. The minimum OLE Automation date is midnight, 1 January 0100. The maximum OLE Automation Date is the same as DateTime.MaxValue, the last moment of 31 December 9999.

first there are not many reasons to convert excel to csv (who am I kidding it is tons). I ran across this issue helping a friend. I can’t believe how incredibly complicated it was to convert the time into a format that was more legible inside of the CSV file.

I think we can agree that sometimes things are harder than what they need to be and I will ensure that this can go easier specially if you take the time to make a function so that you can recall the fix in the future.

Here is a partial solution found as method:

but wait, this is to convert to not convert from!
After looking for all the methods there is no method for ‘fromOADate’!

It clicked immediately that .Net had the solution in its C# library….hopefully. https://docs.microsoft.com/en-us/dotnet/api/system.datetime.fromoadate?view=netcore-3.1

After visiting the link and reading I was more confused and still hopeful I had remembered C#/.net calls look different in PowerShell.

Looks like it the call is unrelated but I only needed the syntax to conjure my own C#

After playing with the way it was called.

now that the proof of concept is there, YAY!

now to test this solution in a different form of reusable code:

$data is defined
Function is defined and ready to take objects and pipline input.

here it is with plain input:

but it could be working incorrectly, lets plug in the data.

lets see the final solution

I know this one was lengthy but I felt like it helped really breakdown the process for beginners.

now the the script/Code:

$data=@()
$data+=New-Object psobject -Property @{name="Xajuan"; Age="" ; Birthdate=41526}
$data+=New-Object psobject -Property @{name="Tyesha"; Age="" ; Birthdate=33172}
$data+=New-Object psobject -Property @{name="Xajuan"; Age="" ; Birthdate=31234}





function Convert-FromOATime
{
<#
.Synopsis
   Coverting OA time to regular time. 
.DESCRIPTION
   A proof of concept blending programming knowledge and scripting.
.EXAMPLE
   $data.birthdate | Convert-FromOATime
.EXAMPLE
   $data | select name,@{name='age';e={(get-date -format yyyy) -($($_.birthdate|Convert-FromOATime|get-date -format yyyy))}},@{name='birthdate';e={$_.birthdate|Convert-FromOATime}}
.NOTES
   By Xajuan Smith
   PowerShell.city
#>
[cmdletbinding()]
param([parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)][Alias('Time')][string[]]$Date)

begin{
        $results=@()
     }

Process{
            foreach($Item in $Date)
            {
                $results+=[DateTime]::FromOADate($($Item)) | get-date -Format MM-dd-yyyy

            }
       }


end{$results}


}#end Function


#example
$data | select name,@{name='age';e={(get-date -format yyyy) -($($_.birthdate|Convert-FromOATime|get-date -format yyyy))}},@{name='birthdate';e={$_.birthdate|Convert-FromOATime}}

Formatting dates from text or objects

Ever imported data just to have a non readable date stamp?

Get-date can take your text that is a date and turn it into something more readable.

Take “15-FEB-20” for example. It’s not really a wildly used format.

Pipe that to get-date like so:

Then you can format your date to remove time and what not.

If you have imported the data you can fix the entry using the select statement.

$data |select name,@{name=’Birthday’;e={$_.birthday | get-date -format MM-dd-yyyy}}

Planning stops the issues from Spanning.

Planning is vital to any infrastructure environment and when scripting or using PowerShell is by no means any different. when you add a high level plan/structure and use it as a map of to-dos and things you want to add later and things you would like to change.

See the source image

Failure to plan can mean data loss and errors that go uninvestigated. Either of which is not what you want to lay eye on or expose ears to. Error handling should go hand in hand with any PowerShell approached solution to cover your bases.

One way is to write a road map of comments in your script prior to coding. reference snippets as often as you can. enough detail so that you wont be lost of you reference that script or function 2 or 3 years from current date to create easily understood code and recycle.