Small Tips and Tricks – PowerShell – how to read content from text file

Hi All,
Greetings for the day!!!
Today new small but useful finding
Background / Use Case
In one of our PowerShell script we need to read the credentials (Username / Password OR Client APP ID / Client Secret Key OR Certificate password) from local text file
Details
- Get-Content CMDLET is used to read the text file from given path
- Get-Content CMDLET reads file line by line
- Example – Following is the content in sample text file – “credentials.txt”
- Username
- Password
$creds = Get-Content -Path <Path of text file>
$creds = Get-Content -Path “credentials.txt”
- By default, Get-Content reads every line in a text file and creates an array as its output with each line of the text as an element in that array.
- So, output of above command will be
Username
Password
Syntax
Get-Content
[-ReadCount <Int64>]
[-TotalCount <Int64>]
[-Tail <Int32>]
[-Path] <String[]>
[-Filter <String>]
[-Include <String[]>]
[-Exclude <String[]>]
[-Force]
[-Credential <PSCredential>]
[-Delimiter <String>]
[-Wait]
[-Raw]
[-Encoding <Encoding>]
[-AsByteStream]
[-Stream <String>]
[<CommonParameters>]
Get-Content
[-ReadCount <Int64>]
[-TotalCount <Int64>]
[-Tail <Int32>]
-LiteralPath <String[]>
[-Filter <String>]
[-Include <String[]>]
[-Exclude <String[]>]
[-Force]
[-Credential <PSCredential>]
[-Delimiter <String>]
[-Wait]
[-Raw]
[-Encoding <Encoding>]
[-AsByteStream]
[-Stream <String>]
[<CommonParameters>]
Simple example
- Lets have simple text file – “credentials.txt” with following content
user name – prasham@knowledgejunction1.onmicrosoft.com
password – LIFE IS BEAUTIFUL
Script to read above file
#Get-Content demo
# Get-Content <File Path>
$credentialFileContent = Get-Content "C:\Prasham\Articles\PowerShell\getcontent\credentials.txt"
Write-Host " "
Write-Host "All file content - " $credentialFileContent
Write-Host " "
#Get-Content reads file line by line in text file and creates an array
Write-Host "Content at Line 1" $credentialFileContent[0]
Write-Host "Content at Line 1" $credentialFileContent[1]
Output of the above script will be
PS C:\> C:\Prasham\Articles\PowerShell\getcontent\getcontent.ps1
All file content - user name - prasham@knowledgejunction1.onmicrosoft.com password - LIFE IS BEAUTIFUL
Content at Line 1 user name - prasham@knowledgejunction1.onmicrosoft.com
Content at Line 1 password - LIFE IS BEAUTIFUL
Thanks for reading !!! HAVE A FANTASTIC TIME AHEAD !!! LIFE IS BEAUTIFUL 🙂
2 Responses
[…] Small Tips and Tricks – PowerShell – how to read content from text file – https://knowledge-junction.in/2023/02/10/small-tips-and-tricks-powershell-how-to-read-content-from-t… […]
[…] We have detailed article on how to read text file – Small Tips and Tricks – PowerShell – how to read content from text file – https://knowledge-junction.in/2023/02/10/small-tips-and-tricks-powershell-how-to-read-content-from-t… […]