header image

Processing files with switch

Posted by: | February 25, 2019 Comments Off on Processing files with switch |

The switch statement has a –file parameter that can be used to give the path to a file. The file is read one line at a time and processed through the switch statement. The example from last time can be used to demonstrate processing files with switch.


$fnum = 1

switch -file C:\test\Data.txt {
{$_ -like ‘HOST*’} {
$file = “C:\test\outdata{0:00}.txt” -f $fnum
$fnum ++
Add-Content -Path $file -Value $_
default {Add-Content -Path $file -Value $_}


Initialize the counter as before. Use switch with the –file parameter to read the file. If the line is like HOST* then its the start of a block so create a new file name, increment the counter and add the content to the file.


Otherwise use the switch’s default option just to write the content to the file. If the data is more complicated then introduce additional processing options and allow default to just write out the data to the file.


This option on switch isn’t used much from what I’ve seen but is worth considering as it can offer some performance gains over other approaches.

under: PowerShell

Comments are closed.