2016-03-02 156 views
2

我正在尝试使用PowerShell的POST请求。它需要生的类型的身体。我知道如何使用PowerShell传递表单数据,但不确定rawdata类型。对于Postman中的简单原始数据,例如如何使用PowerShell为POST请求创建原始主体

{ 
"@type":"login", 
"username":"[email protected]", 
"password":"yyy" 
} 

我在PowerShell中传递如下,它工作正常。

$rawcreds = @{ 
       '@type' = 'login' 
       username=$Username 
       password=$Password 
      } 

     $json = $rawcreds | ConvertTo-Json 

但是,对于像下面这样复杂的rawdata,我不确定如何在PowerShell中传递。

{ 
    "@type": Sample_name_01", 
    "agentId": "00000Y08000000000004", 
    "parameters": [ 
     { 
      "@type": "TaskParameter", 
      "name": "$source$", 
      "type": "EXTENDED_SOURCE" 
     }, 
     { 
      "@type": "TaskParameter", 
      "name": "$target$", 
      "type": "TARGET", 
      "targetConnectionId": "00000Y0B000000000020", 
      "targetObject": "sample_object" 
     } 
    ], 
    "mappingId": "00000Y1700000000000A" 
} 
+0

Invoke-WebRequest'和'Invoke-RestMethod'的'-Body'参数接受一个字符串,并将其用作“原始主体”,所以我不确定我是否理解这个问题。 – briantist

+0

那么你的意思是,我可以传递下面给出的整个原始身体? – live2learn

+0

把你想要的文字(原始)内容放到一个字符串中,然后传入。在你的第一个例子中,你创建了一个对象然后把它转换成JSON(一个字符串)。您的“复杂”示例是否意味着生JSON?你不确定如何建立? – briantist

回答

5

我的解释是,你的第二个代码块是你想要的原始JSON,而你不确定如何构建它。最简单的方法是使用一个here string

$body = @" 
{ 
    "@type": Sample_name_01", 
    "agentId": "00000Y08000000000004", 
    "parameters": [ 
     { 
      "@type": "TaskParameter", 
      "name": "$source$", 
      "type": "EXTENDED_SOURCE" 
     }, 
     { 
      "@type": "TaskParameter", 
      "name": "$target$", 
      "type": "TARGET", 
      "targetConnectionId": "00000Y0B000000000020", 
      "targetObject": "sample_object" 
     } 
    ], 
    "mappingId": "00000Y1700000000000A" 
} 
"@ 

Invoke-WebRequest -Body $body 

变量替换作品(因为我们使用@"代替@'),但你不必做字面"字符转义凌乱。

那么这意味着$source$将被解释为一个名为$source的变量被嵌入到字符串中,然后是文字$。如果这不是你想要的(也就是说,如果你想在本体中使用$source$),那么使用@''@来包装你的字符串,以便不嵌入PowerShell变量。

+0

感谢您的详细信息。它非常有帮助。是的,我想从字面上使用$ source $。正如你所提到的,我会使用@'$ source $'@。 – live2learn

相关问题