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。
uj5u.com熱心網友回復:
不要使用
-OutFile,它不支持附加到檔案;相反,將回應文本輸出到成功輸出流(管道)。- 使用
Invoke-RestMethod而不是Invoke-WebRequest更簡單,因為它直接輸出回應文本。
- 使用
將結果傳送到
Add-Content以附加到目標檔案。
注意:根據后來的要求,目標檔案路徑已根據此答案更正,并確保目標目錄的存在。
# 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/345240.html
上一篇:將字串連接到Get-WmiObject表中的整數-PowerShell
下一篇:Powershell腳本在SetAccessRule上拋出System.Management.Automation.PSMethod錯誤
