简体   繁体   中英

PowerShell Pipeline or Input Argument

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] cat file | <command> [-o out] or <command> -f file [-o out] , in PowerShell being cat file | .\\script.ps1 [-OutFile out] cat file | .\\script.ps1 [-OutFile out] or .\\script.ps1 -File file [-OutFile out] .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM