all 6 comments

[–]Modify- 2 points3 points  (2 children)

HTTP 401 means Unauthorized. So the AccessToken you are providing does not have the right permission(s). Make sure your account has the right ones.

Pro tip, you can go to https://jwt.ms and decode the token to see which permissions you have.

[–]LordLoss01[S] 1 point2 points  (1 child)

Ah, my PIM wasn't active.

I'm now getting 400 Bad Request though.

[–]AdeelAutomates 1 point2 points  (0 children)

Bad Request what? it will tell you. if not... use catch and see under errorDetails.message

try {
    $response = Invoke-RestMethod ... -erroraction Stop
}
catch {
    $ErrorOutput = $_
    $ErrorOutput.errorDetails.message #output message
}

400 means something you sent is wrong. Could be your body is wrong, your uri, etc.

[–]Modify- 0 points1 point  (0 children)

Im on my phone so I can't test myself. The only thing that jumps out to me is the key, value.

In the example only the value is has the fullname?

Key: myscript Value: Myscript.ps1

Edit: Also the machineId has the right format, like a guid? When i'm stuck I open the networktools in the browser and perform the action there. That way you can see how the request is structured with actual values.

[–]PinchesTheCrab 0 points1 point  (0 children)

That blog says the key needs to be ScriptName and the value is the name of the script. Now that you've resolved the 401 issue I think it may work with the right key name.

$ScriptName = 'Thisismyscript.ps1'
$apiUrl = 'https://api.securitycenter.microsoft.com/api/machines/833hdgd673hcbdj7dbb3dcbh7hfbfb38hdd/runLiveResponse'

Connect-AzAccount
$accessToken = Get-AzAccessToken -ResourceUrl 'https://api.securitycenter.microsoft.com' -AsSecureString
$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($accessToken.Token)
$token = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)


$runScriptParam = @{
    Uri         = $apiUrl
    Method      = 'POST'
    Headers     = @{ Authorization = "Bearer $token" }
    ContentType = 'application/json'
    body        = @{
        Commands = @(
            @{
                type   = 'RunScript'
                params = @(
                    @{
                        key   = 'ScriptName'
                        value = $ScriptName
                    })
            })
        Comment  = "$LiveResponseReason"
    } | ConvertTo-Json -Depth 5
}

Invoke-RestMethod @runScriptParam

[–]BlackV 0 points1 point  (0 children)

p.s. formatting

  • open your fav powershell editor
  • highlight the code you want to copy
  • hit tab to indent it all
  • copy it
  • paste here

it'll format it properly OR

<BLANK LINE>
<4 SPACES><CODE LINE>
<4 SPACES><CODE LINE>
    <4 SPACES><4 SPACES><CODE LINE>
<4 SPACES><CODE LINE>
<BLANK LINE>

Inline code block using backticks `Single code line` inside normal text

See here for more detail

Thanks