2017-08-10 171 views
0

以下是我的PowerShell腳本中的片段,其中參數$book$author的值未被替換。請提出一些我可以應用的技術來修復它或分享一些可以幫助我的代碼。將參數值傳遞給PowerShell腳本

$body = @{ 
version = '1.0' 
inactive = 'false' 
yml = { "Service1:\n book: $book\n author: $author\n "} | ConvertFrom-Json 
} | ConvertTo-Json 

$request = Invoke-WebRequest -UseBasicParsing -Method Post -Uri $uri -Body 
$body -Headers $headers -ContentType $contentType 

$response = ConvertFrom-Json -InputObject $request.Content 

回答

1

你有一些奇怪的東西在這條線怎麼回事

... yml = { "Service1:\n book: $book\n author: $author\n "} | ConvertFrom-Json } | ConvertTo-Json 

因爲它說:「做這個身體script block,並嘗試將腳本塊轉換成JSON」。

所以,如果你想在yml字段中有一個JSON字符串,你有兩個選擇。

  1. 寫正確的JSON字符串自己:

    @{...put the rest of your elements here...; yml = "{Service1:'', book:'$book', author: '$author'}" 
    
  2. 填充hashtable第一,然後將其轉換成JSON字符串:

    @{...put the rest of your elements here...; yml = @{Service1=''; book='$book'; author='$author'} } | ConvertTo-Json 
    
+0

@vorou ...我認爲你可能沒有仔細看過花括號...... ConvertTo-Json是最外層的構造,而ConvertFrom-Json僅用於該哈希表中的元素...請再看看...謝謝你提出這2個選項...讓我試試,我會讓你knkow ... –

+0

你是對的,我錯過了大括號;看到更新 – vorou

+0

請不理我的問題,因爲我不再尋求解決方案......它已經通過一些其他技術照顧。真的很欣賞肝雖然。 –

相關問題