Search code examples
powershellazurecmdazure-web-app-servicekudu

Run PowerShell over Kudu Command API to Edit Files


I need to modify the contents of files of my Azure Web App such as the Web.config and text files. Using the Kudu command line API I am able to create a directory or deal with objects using something like the following:

$username = "`$myuser"
$password = "mypass"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))   
$apiUrl = "https://mywebapp.scm.azurewebsites.net/api/command"

$commandBody = @{
    command = "md D:\home\site\wwwroot\newDirectory"
}

Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST -ContentType "application/json" -Body (ConvertTo-Json $commandBody) | Out-Null 

How can I modify files via the Kudu Command API? My ideal state would be to execute PowerShell over the command line API using something like the following:

powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File myFile.txt"

The above command works when I enter this in the CMD Debug Console of the Kudu interface, but I need to call this over the API. I tried the following:

$username = "`$myuser"
$password = "mypass"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))   
$apiUrl = "https://mywebapp.scm.azurewebsites.net/api/command"

$commandBody = @{
    command = powershell.exe -command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File myFile.txt"
}

Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST -ContentType "application/json" -Body (ConvertTo-Json $commandBody) | Out-Null 

However, it doesn't edit the file and instead throws an error of:

Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken


Solution

  • This doesn't look right:

    command = powershell.exe -command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File myFile.txt"
    

    Are you trying to run this powershell command client side or Kudu side? I'm guessing Kudu, in which case you will need to escape it. e.g.

    command = "powershell.exe -command `"(gc myFile.txt) -replace 'foo', 'bar' | Out-File myFile.txt`""