在PowerShell中进行Http post调用时,将JSON正文中的字段设置为文件中的内容

问题描述 投票:0回答:2

我正在尝试安装digicert CA颁发的证书。首先,我使用Powershell脚本生成CSR(证书签名请求)。我将生成的CSR放在txt文件中,并删除所有换行符,空格和回车符。我使用以下脚本来做到这一点:

$CSR > C:\Scripts\CSR.txt
$path = "C:\Scripts\CSR.txt"
(Get-Content $path -Raw).Replace("`r`n","") | Set-Content $path -Force
(Get-Content $path -Raw).Replace(" ","") | Set-Content $path -Force
(Get-Content $path -Raw).Replace("`r`n","") | Set-Content $path -Force -NoNewline

之后,我想发一个对digiCert的http帖子来获取证书ID。为此,我使用以下脚本:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
$body = @"
{
 "profile_name": "XXX",
 "common_name": "XX",
 "additional_dns_names": [
   "XX",
   "XX"
 ],
 "csr":$CSRWithNoCRLF,

 "signature_hash": "sha256",
 "validity": {
   "months": 36
 },
 "organization": {
   "name": "XXX",
   "units": [

   ]
 }
}
"@


$header = @{
 "Accept"="application/json"
 "KEY"="XXXX"
 "Content-Type"="application/json"
} 

$response = Invoke-WebRequest -Uri "https://www.digicert.comXXXX" -Method Post -Body $body -Headers $header 
$Content = $response.Content

对于JSON正文中的csr字段,我想直接复制C:\ Scripts \ CSR.txt文件的内容。我尝试了以下方法,但它无法正常工作。

$CSRWithNoCRLF = Get-Content $path

并使用$ CSRWithNoCRLF作为csr的值。但Get-Content正在添加换行符和回车,并使CSR值失真。所以这不是工作。关于如何解决这个问题的任何想法?

powershell https certificate http-post csr
2个回答
1
投票

Get-Content正在添加换行符

有几种方法,每种都是完整的解决方案:

$CSRWithNoCRLF = Get-Content $path -Raw     # requires PSv3+

Get-Content $path | Out-String

(Get-Content $path) -join "`n"       # use "`r`n" for Windows-style line-endings

编辑

检查你发送的是什么。试试这个:

[regex]::Escape($Body)

如果您使用(Get-Content $path) -join "n“`那么您在CSR部分中将没有\ r \ n行结尾。但是,为什么要手工制作JSON?如果您在Windows框中执行此操作,您将在JSON字符串中使用Windows行结尾。

试试这个:

$Body = [pscustomobject]@{
    profile_name = "XXX"
    common_name = "XX"
    additional_dns_names = @(
        "XX",
        "XX"
    )
    csr = (Get-Content $Path) -join "`n"
    signature_hash = "sha256"
    validity = [pscustomobject]@{
        months = 36
    }
    organization = [pscustomobject]@{
        name = "XXX"
        units = @()
    }

} | ConvertTo-Json -Compress

请注意,我正在使用Compress

> [regex]::Escape($Body) -match '\\r'
False

放手一搏。


1
投票

试试这个 :

$CSRWithNoCRLF = (Get-Content $path -Raw).Replace("`r`n","").Replace(" ","")
$body = @"
{
 "profile_name": "XXX",
 "common_name": "XX",
 "additional_dns_names": [
   "XX",
   "XX"
 ],
 "csr":"$CSRWithNoCRLF",

 "signature_hash": "sha256",
 "validity": {
   "months": 36
 },
 "organization": {
   "name": "XXX",
   "units": [

   ]
 }
}
"@
$header = @{
 "Accept"="application/json"
 "KEY"="XXXX"
 "Content-Type"="application/json"
} 

$response = Invoke-WebRequest -Uri "https://www.digicert.comXXXX" -Method Post -Body $body -Headers $header 
$Content = $response.Content

我认为修改后不需要将证书保存到文件中。

© www.soinside.com 2019 - 2024. All rights reserved.