lib*_*bzz 6 powershell invoke-webrequest
问题:
如何将文件内容放入 Invoke-WebRequest 的 JSON 正文中,而不包含不需要的文件元数据?
我的目标是发送一个 HTTP 请求,如下所示:
Invoke-WebRequest -Uri http://localhost:4321/updatefile `
-ContentType 'application/json' `
-Method POST `
-Body $Body
Run Code Online (Sandbox Code Playgroud)
在哪里:
PS C:\Users\User1234> $Body = ConvertTo-Json @(
@{filename='file1.txt';filecontent=$file1},
@{filename='file2.txt';filecontent=$file2}
)
PS C:\Users\User1234> $file1 = Get-Content "C:\path\to\file1.txt"
PS C:\Users\User1234> $file2 = Get-Content "C:\path\to\file2.txt"
Run Code Online (Sandbox Code Playgroud)
当我打印变量时:
PS C:\Users\User1234> echo $file1
aaaaa
PS C:\Users\User1234> echo $file2
bbbbb
Run Code Online (Sandbox Code Playgroud)
...它按照我的预期打印文件的内容。
但是打印文件内容显示$Body了更多我不需要的信息:
PS C:\Users\User1234> echo $Body
{
"filename": "file1.txt",
"filecontent": {
"value": "aaaaa",
"PSPath": "C:\\path\\to\\file1.txt",
"PSParentPath": "C:\\path\\to",
"PSChildName": "file1.txt",
"PSDrive": {
"CurrentLocation": "Users\\User1234",
"Name": "C",
"Provider": "Microsoft.PowerShell.Core\\FileSystem",
"Root": "C:\\",
"Description": "OS",
"MaximumSize": null,
"Credential": "System.Management.Automation.PSCredential",
"DisplayRoot": null
},
"PSProvider": {
"ImplementingType": "Microsoft.PowerShell.Commands.FileSystemProvider",
"HelpFile": "System.Management.Automation.dll-Help.xml",
"Name": "FileSystem",
"PSSnapIn": "Microsoft.PowerShell.Core",
"ModuleName": "Microsoft.PowerShell.Core",
"Module": null,
"Description": "",
"Capabilities": 52,
"Home": "C:\\Users\\User1234",
"Drives": "C D Y"
},
"ReadCount": 1
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下方法设置$file1和$file2值:
$file1 = [IO.File]::ReadAllText("C:\path\to\file1.txt")
$file2 = [IO.File]::ReadAllText("C:\path\to\file2.txt")
Run Code Online (Sandbox Code Playgroud)
……但结果是一样的。
先设置$body,然后转换为json。
$body = @(
@{
filename = 'file1.txt'
filecontent = [io.file]::ReadAllText("1.txt")
}
)
$body | ConvertTo-Json
Run Code Online (Sandbox Code Playgroud)
或者
$body = @(
@{
filename = 'file1.txt'
filecontent = (get-content 1.txt) -join "`r`n"
}
)
$body | ConvertTo-Json
Run Code Online (Sandbox Code Playgroud)
输出
{
"filename": "file1.txt",
"filecontent": "1\r\n2\r\n3\r\n"
}
Run Code Online (Sandbox Code Playgroud)
原因很简单,get-content返回一个数组,convertto-json完成其工作,但可能不是您所期望的。
| 归档时间: |
|
| 查看次数: |
12525 次 |
| 最近记录: |