1

PowerShell's Invoke-WebRequest provides -OutFile that writes the response body to a file.

@('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"
  }

I would like to append to the file $Env:USERPROFILE/.gitignore, and it doesn't seem like Invoke-WebRequest will support this. How can I go about doing this?

Also, any tips on how I can make this PowerShell script more readable/concise?

Note: I am using PowerShell version 5.1.19041.1237.

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119

1 Answers1

3
  • Do not use -OutFile, which doesn't support appending to a file; instead, output the response text to the success output stream (pipeline).

  • Pipe the result to Add-Content in order to append to the target file.

Note: As later requested, the target file path has been corrected per this answer, and the existence of the target directory is ensured.

# 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
  • 382,024
  • 64
  • 607
  • 775
  • Thank you @mklement0! I have just learned from [this post](https://stackoverflow.com/a/22885996/11163122) that the default path is actually `%USERPROFILE%\git\ignore`, if anyone else cares about the `.gitignore` specifics – Intrastellar Explorer Oct 28 '21 at 21:27
  • 1
    @IntrastellarExplorer, I've updated the answer again to make it cross-platform. – mklement0 Oct 28 '21 at 21:41