To capture output from multiple statements in PowerShell, enclose them in a script block ({ ... }
) and invoke that with &
(or with .
, if you want the code to run directly in the caller's scope, but that makes no difference for calling external programs such as git
):
$log = & { Push-Location $tempRepo;git init -q;git remote add origin ssh://git@git.weblnk.silverlnka.net/gxp/$repo;git fetch origin $branch -q;git log "$prevCommit..origin/$branch" --name-only --pretty=format: --full-history;Pop-Location }
If you also need to capture stderr output from external programs such as git
, append 2>&1 | % ToString
to the call, but note that git log
normally outputs just to stdout, so no extra effort is needed.
Here's a simple example of a cmd.exe
command that produces both stdout and stderr output, and how to capture both in a PowerShell variable.
$out = cmd /c 'ver & nosuch' 2>&1 | % ToString
Note:
In the context of & { ... }
, you're free to apply 2>&1 | % ToString
to either the entire command group (& { foo.exe; <# ...#> } 2>&1 | % ToString
); or to individual commands inside (& { foo.exe 2>&1 | % ToString; <# .. #> }
)
2>&1
can have unexpected side effects - see this answer for background information.
what I would like to do is create an array holding all lines excluding lines that appear empty.
If external-program output comprises more than 1 line, PowerShell automatically captures the output in in an array of individual lines.
To simply remove empty lines from such an array, use:
# Assume that $out contains output captured from an external program.
@($out) -ne '' # returns sub-array of non-empty lines.
As for what you tried:
$log = Push-Location $tempRepo;git init -q;git remote add origin ssh://git@git.weblnk.silverlnka.net/gxp/$repo;git fetch origin $branch -q;git log "$prevCommit..origin/$branch" --name-only --pretty=format: --full-history;Pop-Location
Because your command line is composed of multiple, ;
-separated statements, what $log = ...
captures is just the output from the first statement, Push-Location $tempRepo
- and since Push-Location
produces no output, $log
ends up effectively $null
.