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
.
CodePudding user response:
Do not use
-OutFile
, which doesn't support appending to a file; instead, output the response text to the success output stream (pipeline).- Using
Invoke-RestMethod
rather thanInvoke-WebRequest
is simpler, as it outputs the response text directly.
- Using
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