PowerShell – edit text from file

This is an example that I created to open a file, manipulate the text and output to the file.

$path_in = “C:testinput.txt”

$path_out = “C:testoutput.txt”

$endMessage = “=============== END ==============”

$reader = [System.IO.File]::OpenText($path_in)
$get_time_message = “program executed on ” + [datetime]::now.ToString(‘yyyy-MM-dd / HH:mm:ss’)

try {

add-content $path_out $get_time_message
add-content $path_out “to unix: “

$long_string_to_excel =””

while($true){

$line = $reader.ReadLine()

if ($line -eq $null) { break }

# divide the input line into array – remove white space

# it is hard coded here below for the lines that consist two and three space characters

$better_line = $line.replace(‘ ‘,’ ‘)

$best_line = $better_line.replace(‘ ‘,’ ‘).split(‘ ‘)

$stringToOutput = “rm -fr ” + $best_line[8]

$long_string_to_excel = $long_string_to_excel + $best_line[8] + “`r`n”

add-content $path_out $stringToOutput

}

add-content $path_out “`n”
add-content $path_out “to excel log: ”
add-content $path_out $long_string_to_excel
add-content $path_out $endMessage

}

finally {

$reader.Close()

}

write-host “program execution:`ncompleted”

Leave a Comment

Your email address will not be published. Required fields are marked *