0

I have a list of commands I run in a script like this

Some-Cmdlet -someswitch | Outfile -filepath .\somefile.txt -append
Another-Cmdlet -someswitch | Out-File -filepath .\somefile.txt -append
Hello-Cmdlet -someswitch | Out-File -filepath .\somefile.txt -append
Banana-Cmdlet -someswitch | Out-File -filepath .\somefile.txt -append

It is actually a long list of commands creating this somefile.txt.

If I have to change the location or name of somefile.txt, I have to edit every line one by one. I'd like to clean up the script for maintainability, so what I'd like is something like this:

For the following list of commands:

Some-Cmdlet -someswitch
Another-Cmdlet -someswitch
Hello-Cmdlet -someswitch
Banana-Cmdlet -someswitch

Always add this to the command:

 | Outfile -filepath .\somefile.txt -append

That way I only have to edit the script in one place if somefile.txt path or name needs to be changed.

1 Answer 1

1

The easiest way to save you respecifying the same file name each time is just to save the file name in a variable, and then reference that variable on each line, like this:

$FileName = .\somefile.txt

Some-Cmdlet -someswitch | Outfile -filepath $FileName -append
Another-Cmdlet -someswitch | Out-File -filepath $FileName -append
Hello-Cmdlet -someswitch | Out-File -filepath $FileName -append
Banana-Cmdlet -someswitch | Out-File -filepath $FileName -append
1
  • Cool, thanks. In another question someone just turned me on to the Start-Transcript cmdlet, which might even work better for me!
    – Daniel
    Sep 26, 2016 at 12:22

Not the answer you're looking for? Browse other questions tagged .