I had a need to manipulate some text files to get the clean data the other day and found it’s extremely easy to deal with text files with PowerShell.
To open a text file and get the content of it,
Get-Content path\filename.txt
But I can use ForEach cycle to read each line the same time.
foreach ($eachline in Get-Content path\filename.txt) { codes to do deal with each line }
Once I got the cleaned data in a new string, i.e. $newcontent, I can save it to a new text file.
Set-Content path\newfile.txt $newcontent
If I’d like to append the new content to an existing file, I can use Add-Content instead.
Add-Content path\newfile.txt $newcontent
It’s also worth noting that there is a list of special characters for special occasions like starting a new line, etc.
- `0 — Null
- `a — Alert
- `b — Backspace
- `n — New line
- `r — Carriage return
- `t — Horizontal tab
- `’ — Single quote
- `” — Double quote
Also, while we are at dealing with text files, let’s take look how many ways PowerShell can manipulate strings. Run the Get-Member cmdlet to find out.
"Strings in PowerShell" | PowerShell
The list is pretty impressive, covering most of the common string operations, such as Replace, Find, Compare, Concatenate, Split, Substring, etc.