【问题标题】:Powershell Invoke-WebRequest appending to a file instead of writingPowershell Invoke-WebRequest 附加到文件而不是写入
【发布时间】:2021-12-14 01:06:43
【问题描述】:

PowerShell 的Invoke-WebRequest 提供-OutFile,将响应主体写入到文件中。

@('Global/JetBrains','Global/Vim','Global/VisualStudioCode','Global/macOS','Python','Terraform') `
  | ForEach-Object {
    Invoke-WebRequest -UseBasicParsing -Outfile "$Env:USERPROFILE/.gitignore" -Uri `
    "https://raw.githubusercontent.com/github/gitignore/master/$PSItem.gitignore"
  }

我想追加到文件$Env:USERPROFILE/.gitignore,似乎Invoke-WebRequest 不支持这个。我该怎么做?

另外,关于如何使这个 PowerShell 脚本更具可读性/简洁性的任何提示?

注意:我使用的是 PowerShell 版本 5.1.19041.1237

【问题讨论】:

    标签: powershell append invoke-webrequest


    【解决方案1】:
    • 不要使用-OutFile,它不支持追加到文件;而是将响应文本输出到成功输出流(管道)。

    • 将结果传送到Add-Content 以便附加到目标文件。

    注意:根据后面的要求,目标文件路径已根据this answer进行了更正,保证了目标目录的存在。

    # Make sure that the platform-appropriate target dir. exists.
    $outDir = ("$HOME/.config/git", "$HOME/git")[$env:OS -eq 'Windows_NT']
    $null = New-Item -Type Directory -Force $outDir
    
    'Global/JetBrains', 'Global/Vim', 'Global/VisualStudioCode', 'Global/macOS', 'Python', 'Terraform' | 
      ForEach-Object {
        Invoke-RestMethod -Uri "https://raw.githubusercontent.com/github/gitignore/master/$PSItem.gitignore"
      } | 
        Add-Content $outDir/ignore
    

    【讨论】:

    • 谢谢@mklement0!我刚刚从this post 那里得知默认路径实际上是%USERPROFILE%\git\ignore,如果其他人关心.gitignore 的细节
    • @IntrastellarExplorer,我再次更新了答案以使其跨平台。
    猜你喜欢
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多