I'm creating a PowerShell console app to manage Nginx for Windows, and I'm running into an issue with capturing the output from commands I execute. When I use the `Invoke-Expression` command, it sometimes returns null even though I see the output on the screen. For example, running `Invoke-Expression -Command "d:nginxnginx.exe -t"` provides output confirming that the Nginx configuration is valid. However, I can't manipulate that output since it seems to return null, which means I cannot change the text color with `Write-Host`. I'm looking for a way to capture the command's output so that I can format it as needed. How can I achieve this?
3 Answers
I agree, using `Invoke-Expression` for an `.exe` file isn't ideal. Instead, try redirecting the output streams using the call operator:
```powershell
$results = & d:nginxnginx.exe -t 3>&1 2>&1 > $env:TEMPtest.txt
```
This method captures all output into a text file, which you can then read and format. Also, check if `nginx.exe` has specific logging options that could help you get the output in a more manageable way.
You might want to consider using `Start-Process` instead of `Invoke-Expression`. `Start-Process` is better suited for running executables. For capturing output, you can redirect the standard output directly. Here's an example:
```powershell
$results = & d:nginxnginx.exe -t
```
Or use `Start-Process` with the `-RedirectStandardOutput` parameter. That way, you can manipulate the output afterwards with additional formatting.
For what you're aiming to do, consider creating a custom function like this one:
```powershell
Function Start-ProcessWithOutput {
param (
[Parameter(Mandatory)]
[string]$FilePath,
[Parameter()]
[string[]]$ArgumentsList
)
$tmp = [System.IO.Path]::GetTempFileName()
$process = Start-Process -FilePath $FilePath -ArgumentList $ArgumentsList -NoNewWindow -RedirectStandardOutput $tmp -PassThru
$process.WaitForExit()
Get-Content -Path $tmp
}
```
This function starts a process and waits for it to complete, while capturing the output into a temporary file, which you can then read.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically