Home > Back-end >  Is it possible to save the output from a write command in a file? (API and Powershell)
Is it possible to save the output from a write command in a file? (API and Powershell)

Time:10-23

i just started with Powershell and have already a problem. I am using the API from OpenWeathermap (https://openweathermap.org/) to create something like a weather-bot.

I am using this function from the API:

Write-WeatherCurrent -City $place -ApiKey $ApiKey -Units metric

Where the Output something like this (if I fill the Variables): 10.2°C (☁️ few clouds) in london

So I want this Output to save in a File. I already tried with the Commands Out-File and >>. But it only outputs in the Terminal and the File is empty. I am not sure, but is it because of "Write"-WeatherCurrent?

I would be happy if anybody could help me :D

Thank you

CodePudding user response:

Write-WeatherCurrent uses Write-Host to write the output directly to the host console buffer.

If you're using PowerShell 5.0 or newer, you can capture the Write-Host output to a variable with the InformationVariable common parameter:

Write-WeatherCurrent -City $place -ApiKey $ApiKey -Units metric -InformationVariable weatherInfo

$weatherInfo now contains the string output and you can write it to file:

$weatherInfo |Out-File path\to\file.txt 

If the target command doesn't expose common parameters, another option is to merge the Information stream into the standard output stream:

$weatherInfo = Write-WeatherCurrent -City $place -ApiKey $ApiKey -Units metric 6>&1 # "stream 6" is the Information stream
  • Related