Powershell version used: 3.0
Hello everyone,
I'm looking to try and create a new Powershell pipeline and execute a script within it, then get the output it produces into an output variable, but I can't get any output produced from within the object (from the executed script). The whole point of this is so I don't have to manage the $Error object, which I intend to use for error detection. Here's an example below:
$ps = [Powershell]::Create()
$File = ".\Test2.ps1"
$SortedParams = "-Name blah -Key foo"
$RootDirectory = Get-Location
$ExecutionDirectory = "$RootDirectory\Test3"
$ps.AddCommand("Set-Location").AddParameter("Path", "$ExecutionDirectory")
write-host "COMMAND 1: " $ps.Commands.Commands.Item(0).CommandText
$ps.AddScript("$File $SortedParams")
write-host "COMMAND 2: " $ps.Commands.Commands.Item(1).CommandText
$output = $ps.Invoke()
write-host $output
I should mention that I'm trying to use the following 3 methods of producing output within the script executed:
- Write-Host
- Write-Output
- Write-Verbose (used $ps.Streams.Verbose to try to get output, but nothing)
Any suggestions or tips you can give is much appreciated!
Unless you feel there's a specific need to do things the way you're doing them, you might want to look into using PowerShell background jobs instead.
Background jobs allow you to run PowerShell commands in a separate PowerShell instance and then collect the output from those jobs into a variable (if that's what you want to do).
Check out the about_Jobs help topic for more information.
Here's a quick example: