[PowerShell] How to read a file's content and save it
Get-Content
Get-Content cmdlet is used to read the content of a file, for example CustomerList.txt file. There are a few scenarios where we need to read a file and we could automate this using Get-Content cmdlet in PowerShell.
Scenario 1 :
Given that there is a CustomerList.txt file
When customers want to apply for a loan
Then a bank officer will check in the CustomerList.txt if he has any existing load with the bank
Example of the code :
$file = "C:\CustomerList.txt"
Get-Content -Path $file
There are a few parameters that I like to use with Get-Content cmdlet.
- TotalCount = Display the content based on the no. of count defined by the value of TotalCount
- Tail = Display the content of the no. of last lines defined by the value of Tail
I try to use -Filter parameter of Get-Content cmdlet but it doesn’t filter the value that I am expected it to return. Thus, I use Select-String cmdlet together with Get-Content cmdlet to filter certain value from the content of the file.
Example of the code :
$file = "C:\CustomerList.txt"
$filteredWord = @("Amy Farrah Fowler","Sheldon Cooper","Penny Hofstadter")
Get-Content $file | Select-String -Pattern $filteredWord -SimpleMatch
Set-Content
Set-Content cmdlet on another hand is used to save a content to a file.
Example, if we have a set of data and we want to save it in a .txt file we could use Set-Content cmdlet.
$text = "Welcome to Software Kueh blog."
$textPath = "C:\PowerShellExercise\welcome.txt"
Set-Content -Path $textPath -Value $text
If the filename exists, use -Force parameter to overwrite previous file.