#### Reading Text files with Powershell | Get-Content cmdlet

More often than not when scripting you will have to deal with reading files with Powershell when scripting. Whether its logs or files comparison orrrr feeding a list to the script to store and use as a variable, you will need to read a file from your script. Thankfully Powershell has the Get-Content cmdlet which will read a file with just one line of code.

### Using Get-Content Cmdlet to read a text file

Get-Content "D:\text_file.txt"

And that’s it! that’s all you need to do! And it will read the file like this

Let’s see how we can play around with this shall we!

### Retrieving specific lines

Powershell Get-Content Cmdlet takes in each line as an array. So the 1st line will be in the 0th element, the 2nd line will be in the 1st element and so on… To play around with this concept we need to get the content to a variable

$text = Get-Content "D:\text_file.txt" So$text[0] which is the 0th element will contain line 1, $text[1] which is the 1st element will contain line 2 and so on… ### Traversing a list and Searching for text To explore this concept let’s get a more practical example. Let’s say our text file is a list of server names that we manage as follows Let’s say we need to filter out just the windows servers from the list. This can be done as follows by searching for the “windows” phrase. Get-Content "D:\server_list.txt" | Where-Object {$_ -like '*windows*'}

Now lets say we need to connect to all of the windows servers (hypothetically). We can traverse this list with a for-loop (I am not going to use a Enter-PSSession, but for clarity of this exercise I’m just going to display a text – you can do the hard work on your own 😉 )

$windows_servers = Get-Content "D:\server_list.txt" | Where-Object {$_ -like '*windows*'}

ForEach ($windows_server in$windows_servers){

Write-Host "Connecting to $windows_server" #Alternatively here is where you would use Enter-PSSession -ComputerName$windows_server

}

So that’s about it. I’ve just touched the surface of what you can do with Get-Content. As time permits I will do a more elaborate post on search and loops. Till then – keep scripting!

#### Storing Passwords securely with Powershell

Security is paramount in our line of work, a breach would mean a catastrophe of epic proportions for a sys admin – I mean what can’t you do if you’re the administrator right? So we set our passwords T0b3imp055ibleT0Guess and lock them up in keypasses.

But we sys admins are lazy, when it comes to scripts – we leave it to ask for our password every time we execute the script, but what if we need to automate the script – schedule it to run automatically? we can’t leave them in plain sight, plain text! Not to worry – as always powershell has a module to save our skins. Here’s how you store your passwords securely and retrieve them when needed:

Powershell thankfully has the ConvertFrom-SecureString module to convert any text to a secure string. Save the following script separately and it will prompt you to enter a new password and will save it in the location with the file name you have specified

$password_file_location = "D:\test\credentials.txt" \\location and filename can be anything you want it to be Read-Host "Enter New Password" -AsSecureString | ConvertFrom-SecureString | Out-File$password_file_location

Use the following lines in your script (that does the automation job) to retrieve the saved password

$password_file_location = "D:\test\credentials.txt"$password = Get-Content $password_file_location | ConvertTo-SecureString Now the$password variable contains the password you have saved previously. Use it in the part of the code you use to connect to the server and viola you’re through without having to type your password all the time or using a plain text password!

Note: This doesn’t guarantee security, but it’s definitely a step in the right direction!

#### Error handling in Powershell : Try / Catch blocks in Powershell

Recently I had a project to develop a web portal that would trigger a powerCLI script. The problem was that if anything except the required JSON output popped up, especially any errors, the whole thing would crash. The only work around was to error handle the sh#t out of the code!!!

The best and easiest way to error handle / catch exceptions is to use try / catch blocks – if you’re familiar with Java (or any kind of) programming, powershell try catch blocks work exactly the same way. If you’re not – don’t worry I got your back.

### What is a try catch block?

Try catch block is a way to structure your code to handle errors and catch any exceptions that your code might throw. There is also a “Finally” block that is also a part of the whole thing.

Try block – This is where you place the code which you need to check for exceptions
Catch block – This is where you specify what you need the code to do IF an exception is caught
Finally block – This is where you specify the code that you need to run regardless of whether an exception was caught or not

try{

//The code that needs checking for exceptions
}

catch{

//What should happen if an exception is caught
}

Finally{

//What should run regardless of what happens above
}

### Code Example

try{

Connect-VIServer $vcenter -Credential$credentials -ErrorAction Stop
Write-host "This will not run if an exception is caught"
}

catch{

Write-host "Oops something is wrong with the credentials"
}

Finally{

Write-host "This runs regardless of what happens above"
}

The above code is a PowerCLI script which will try to connect to a vCenter with the given credentials and if an exception is caught it will display the text in the catch block.

IMPORTANT: DONT FORGET THE -ERRORACTION The -ErrorAction stop is extremely important for the code to function as expected. This is will stop powershell from executing the next lines and divert the code to the catch block. If ErrorAction was not there it will continue executing everything regardless of an exception.