Powershell Read A Text File

I get a lot of data in different formats for a lot of different users. Nothing is ever perfect. This is the simple script I use to begin the process of reading files:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 #File parameter
 Param( 
        [String] 
        $file
    ) 
#Get the current directory
$scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
#Build Full Path
$filePath = $scriptDir + "\" + $file
#Get File Contents
$content = Get-Content -Path $filePath
#Get Max number of rows
$intRowMax = $content.count
#loop through rows
for($intRow = 0 ; $intRow -lt $intRowMax ; $intRow++)
{
#display
Write-Host $content[$intRow]
}  


#Alternative
Write-Host "`n**********Alternative*******" 
foreach($line in Get-Content $filePath) {
#display
Write-Host  $line
}

Pretty straightforward example. I added an alternative that uses a foreach with the Get-Content command. Call this script from the local directory with both files (But obviously you can easily modify to call a file in a different location)



I don't do any error catching here, because I'm lazy and if it fails to read the file I get to see the ugly error. It is not a production script.




NOTE: Get-Content command output is a list of strings, not the whole contents of the file. You can just write $content, because it is smart enough to know what you are trying to do, but it is frowned upon. Read this article for more information 


Comments