Q: How do I read the content of a file in Windows PowerShell?
Using the right cmdlet, it's easy to read the content of a PowerShell file.
John Savill
November 21, 2011
1 Min Read
A: Reading the content of a file in PowerShell is very easy. You use the Get-Content cmdlet and the filename. Here’s an example:
Get-Content "d:projectspowershellwakeup.dat"
To save the content to a variable just use this:
$data = Get-Content "d:projectspowershellwakeup.dat"
Each line of the file is an array element with the variable passed, so to display just the first line you could use this:
$data = Get-Content "d:projectspowershellwakeup.dat"$data[0]
If you used $data.count, it would show the number of lines in the file. You can also access each line and perform some action by using the PowerShell foreach function, in this manner:
$data = Get-Content "d:projectspowershellwakeup.dat"write-host $data.count total lines read from fileforeach ($line in $data){ write-host $line}
Learn more: Q. Can PowerShell read and parse XML files?
About the Author
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.
You May Also Like