2

I could not find an answer to this question anywhere.

How can a PowerShell script written in a file (as I understand, it cannot be a function in order to allow the pipelining directly to the script) be made to accept either pipeline input or a file input argument? The following criteria must be met:

  • either of which must be mandatory;
  • pipeline input is to be processed only after receiving all input into an array;
  • input argument is a file and the path must be validated;
  • a second optional argument specifies an output file.

The idea is to achieve a similar behavior to standard Linux commands as in cat file | <command> [-o out] or <command> -f file [-o out], in PowerShell being cat file | .\script.ps1 [-OutFile out] or .\script.ps1 -File file [-OutFile out].

1
  • See Joey's answer and you will understand the question. Commented Sep 30, 2016 at 13:06

1 Answer 1

2

You could have a script like this:

param([string]$Path)

if (!Path) {
  $scriptInput = $input
} else {
  $scriptInput = Get-Content $Path
}

# Do something with $scriptInput

Checking for either pipeline input or an argument is left as an exercise for you.

Sign up to request clarification or add additional context in comments.

1 Comment

This seems to work, but breaks (input object cannot be bound to any parameters...) when a second, optional argument is added and the pipeline method is used. I have edited my question to reflect the need for the second argument specifying an output file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.