1

Is there any way to avoid passing parameters to a function, like "-Append $outfile" to Out-File, every time? I have a script which collects data from the system, something like:

... collect OS information ... | Out-File -Append $output
... collect local users ... | Out-File -Append $output
... collect logfile permissions ... | Out-File -Append $output
etc. 

The last command in the pipe is most of the time Out-File -Append $output - can this be done more elegant? I had different ideas:

  1. Create a wrapper function which passes the needed parameters to Out-File command - already tried, but I had problems to make it pipe-compatible

  2. Write all output into a String-Variable and write the content at the end of all commands into the file - needs a lot of memory

  3. Create something like an Output-Writer-Object which only receives once at initialization the necessary paramters - not tried yet

Thank you very much for your help!

Wim
  • 11,998
  • 1
  • 34
  • 57
Patrick
  • 1,046
  • 2
  • 10
  • 31

3 Answers3

0

You dont appear to be using a lot of arguments for this to be incredibly useful but a good suggestion would be to use splatting. I added some more parameters to illustrate how clean it can make code appear while still being functional.

$options = @{
    Append = $True
    FilePath = $output
    Encoding = "Unicode"
    Width = 400
}

Build a hastable of options and splat the cmdlet with them

... collect OS information ... | Out-File  @options
... collect local users ... | Out-File  @options
... collect logfile permissions ... | Out-File @options

Outside of that a wrapper function (of filter if it is easier) like you suggest would be another option. Look at the options in this answer. Specifically the filter

Community
  • 1
  • 1
Matt
  • 45,022
  • 8
  • 78
  • 119
0

You want to use the $PSDefaultParameterValues preference variable. Something like this:

$PSDefaultParameterValues = @{
    "Out-File:Encoding"="utf8";
    "Out-File:Append"=$true;
    "Out-File:FilePath"=$output
}

This feature is especially useful when you must specify the same alternate parameter value nearly every time you use the command or when a particular parameter value is difficult to remember, such as an email server name or project GUID.

0

Or put everything inside a function or scriptblock. Note that out-file defaults to utf16 encoding, and can mix encodings, as opposed to add-content.

& {
  ... collect OS information ... 
  ... collect local users ... 
  ... collect logfile permissions ... 
} | add-content $output
js2010
  • 23,033
  • 6
  • 64
  • 66