是否可以将写入命令的输出保存在文件中?(API 和 Powershell)

Sea*_*... 1 api powershell openweathermap

我刚刚开始使用 Powershell,已经遇到了问题。\n我正在使用 OpenWeathermap ( https://openweathermap.org/ ) 的 API 来创建类似天气机器人的东西。

\n

我正在使用 API 中的这个函数:

\n
Write-WeatherCurrent -City $place -ApiKey $ApiKey -Units metric\n
Run Code Online (Sandbox Code Playgroud)\n

输出是这样的(如果我填写变量):\n10.2\xc2\xb0C (\xe2\x98\x81\xef\xb8\x8f 几朵云) in london

\n

所以我希望这个输出保存在文件中。我已经尝试过使用命令输出文件和>>。但它仅在终端中输出并且文件为空。我不确定,但是是因为“Write”-WeatherCurrent吗?

\n

如果有人能帮助我,我会很高兴:D

\n

谢谢

\n

Mat*_*sen 6

Write-WeatherCurrent用于Write-Host将输出直接写入主机控制台缓冲区。

如果您使用的是 PowerShell 5.0 或更高版本,则可以Write-Host使用公共参数将输出捕获到变量中InformationVariable

Write-WeatherCurrent -City $place -ApiKey $ApiKey -Units metric -InformationVariable weatherInfo
Run Code Online (Sandbox Code Playgroud)

$weatherInfo现在包含字符串输出,您可以将其写入文件:

$weatherInfo |Out-File path\to\file.txt 
Run Code Online (Sandbox Code Playgroud)

如果目标命令不公开公共参数,另一个选项是将Information流合并到标准输出流中:

$weatherInfo = Write-WeatherCurrent -City $place -ApiKey $ApiKey -Units metric 6>&1 # "stream 6" is the Information stream
Run Code Online (Sandbox Code Playgroud)