Run PowerShell over Kudu Command API to Edit Files

旧街凉风 提交于 2019-12-11 05:56:13

问题


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


回答1:


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`""


来源:https://stackoverflow.com/questions/44766365/run-powershell-over-kudu-command-api-to-edit-files

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