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!

Leave a Reply

Your email address will not be published. Required fields are marked *