N
N
NewDevLab2020-05-07 11:44:21
PowerShell
NewDevLab, 2020-05-07 11:44:21

Similar behavior to Out-File?

How to make MyFunc behave like Out-File?

"str1",
"str2",
"str3" | Out-File -FilePath "test1.txt"

$arr1 = @("str1", "str2", "str3")
Out-File -InputObject $arr1 -FilePath "test2.txt"

"str1",
"str2",
"str3" | MyFunc -FilePath "test3.txt"

@("str1",
"str2",
"str3") | MyFunc -FilePath "test4.txt"

$arr2 = @("str1", "str2", "str3")
MyFunc -InputObject $arr2 -FilePath "test5.txt"

function MyFunc() {
  param (
    [Alias("InputObject")] [parameter(ValueFromPipeline = $true)] [array] $cmds,
    [Alias("FilePath")] [string] $fileName
  )
  $cmds | Out-File $fileName
}


test3.txt and test4.txt output only the last element of the array. Tried array, string[], psobject. Passes only the last element of the array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaxKozlov, 2020-05-07
@NewDevLab

If you use it, [parameter(ValueFromPipeline = $true)]
you must adhere to the appropriate type of function for the pipeline, namely - to do all the processing in a block PROCESS{}- the block will receive everything that enters the input from the pipe in a loop. blocks BEGIN{}and END{}are activated, respectively, at the very beginning and end, where the value of $ cmds will not be available

function MyFunc() {
  param (
    [Alias("InputObject")] [parameter(ValueFromPipeline = $true)] [array] $cmds,
    [Alias("FilePath")] [string] $fileName
  )
  BEGIN {}
  PROCESS {
    $cmds | Out-File $fileName} -Append
  }
  END{}
}

in BEGIN{} you may need to clean up the file

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question