I can get output from a program (in this case it's restic on windows) to a variable. I then split thant variables of lines and output it to a log function I have. Which actually posts to syslog.
$command = & $ResticExe backup $folder_list --tag $tag --exclude-file=$WindowsExcludeFile
for ($i=0; $i -lt $command.length; $i++)
{
Log($command[$i])
}
the restic command when the variables are expanded is something like
restic.exe backup C:\users\administrator\documents --tag Documents
Ideally I'd like to redirect the output of that command to my Log function as it's happening. There are options for redirecting command output to a file, but I can't see one that I could use to capture each line for the Log function.
Use a call to ForEach-Object
in order to process each line emitted to stdout from a call to an external program, referring to each input object (line) using the automatic $_
variable:
& $ResticExe backup $folder_list --tag $tag --exclude-file=$WindowsExcludeFile |
ForEach-Object { Log $_ }
If you have control over the definition of the Log
command, you can modify it to accept pipeline input directly, which enables a solution that is both more concise and more efficient:
# Sample Log command that accepts pipeline input.
# The `process` block is executed for each input object, reflected in $_
function Log { process { "[$_]" } }
1..3 |
Log # -> '[1]', '[2]', '[3]'
See the relevant section of the conceptual about_Functions help topic.