【问题标题】:Is it possible to save the output from a write command in a file? (API and Powershell)是否可以将写入命令的输出保存在文件中? (API 和 Powershell)
【发布时间】:2021-12-08 04:23:00
【问题描述】:

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

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

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

输出是这样的(如果我填写变量): 伦敦 10.2°C(☁️ 几朵云)

所以我希望这个输出保存在一个文件中。我已经尝试过使用 Commands Out-File 和 >>。但它只在终端输出,文件为空。我不确定,但是否因为“Write”-WeatherCurrent?

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

谢谢

【问题讨论】:

    标签: powershell api openweathermap


    【解决方案1】:

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

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

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

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

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

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

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

    【讨论】:

    • @Searching....你应该只传递目标变量的name,所以它是-InformationVariable weatherInfo,而不是-InformationVariable $weatherInfo(没有$)跨度>
    • 感谢您的快速响应,但仍然无法正常工作。输出仍然写入主机控制台缓冲区,但文件和变量为空。
    • 刚做了,但似乎不起作用:(
    • @Searching.... 您是否尝试过从我的答案中复制粘贴命令并按原样运行?输出仍应写入控制台,然后复制到名称指定的变量中。如果它仍然不起作用,您能否分享您正在使用的 PowerShell 版本? "$($PSVersionTable.PSVersion)"
    • 如果要执行多个语句并从所有语句中捕获信息流,请将它们包装在这样的块中:&{ Write-WeatherCurrent ...; Write-WeatherForecast ... } 6>&1
    猜你喜欢
    • 2012-02-18
    • 2023-03-11
    • 2022-10-24
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    相关资源
    最近更新 更多