Converting PowerShell to Bash

旧街凉风 提交于 2021-01-28 19:32:57

问题


I need to convert the following PowerShell script to a Bash script. Could someone help me out? I'm really new to Bash and don't know how to manipulate the output from a curl command and then convert it to Json.

$headers = @{"X-Octopus-ApiKey"="<api_key>"}

$machine = Invoke-RestMethod "http://my.url/api/machines/discover?host=<ip_address>&type=ssh" -Headers $headers -Method Get
$machine.Name = "<hostname>"
$machine.Roles += "<role>"
$machine.EnvironmentIds += "<environment>"
$machine.Endpoint.AccountId = "<account_id>"

Invoke-RestMethod "http://my.url/api/machines" -Headers $headers -Method Post -Body ($machine | ConvertTo-Json -Depth 10)

回答1:


Powershell return object response from Invoke-RestMethod but curl return json string format. You have to parse the response of curl to extract the values of Roles and EnvironmentIds using json parser tool like jq.

Be sure that you installed jq

The following script is the conversion of the Powershell script:

    headers='{"X-Octopus-ApiKey"="<api_key>"}'
    #$machine = Invoke-RestMethod "http://my.url/api/machines/discover?host=<ip_address>&type=ssh" -Headers $headers -Method Get

    response=$(curl -s  -X GET -H $headers "http://my.url/api/machines/discover?host=<ip_address>&type=ssh")        
    echo $response
    Name="Myhostname"
    Roles=$(echo $response | jq -r ".Roles")
    echo $Roles
    Roles+="Myrole2"
    EnvironmentIds=$(echo $response | jq -r ".EnvironmentIds")
    echo $EnvironmentIds
    EnvironmentIds+="Myenvironment2"
    echo $EnvironmentIds
    AccountId="Myaccount_id"
    #compose json string to be passed as a body for the next curl call
    machine=$(printf '
    {"Name":"%s",
    "Roles":"%s" ,
    "EnvironmentIds":"%s" ,
    "Endpoint" : {
                   "AccountId" : "%s"      
                 }
    }' "$Name" "$Roles"  "$EnvironmentIds" "$AccountId")
    echo $machine

    #Invoke-RestMethod "http://my.url/api/machines" -Headers $headers -Method Post -Body ($machine | ConvertTo-Json -Depth 10)
    response=$(curl -s  -X POST -H $headers -d $machine  "http://my.url/api/machines")
    echo $response


来源:https://stackoverflow.com/questions/40145333/converting-powershell-to-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!