运行 PowerShell 通过 Kudu 命令 API 编辑文件

Run PowerShell over Kudu Command API to Edit Files

我需要修改我的 Azure Web 应用程序的文件内容,例如 Web.config 和文本文件。使用 Kudu 命令行 API 我可以创建目录或使用类似以下内容处理对象:

$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 

如何通过 Kudu 命令修改文件 API?我的理想状态是通过命令行 API 使用如下内容执行 PowerShell:

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

当我在 Kudu 界面的 CMD 调试控制台中输入时,上面的命令有效,但我需要通过 API 调用它。我尝试了以下方法:

$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 

但是,它不会编辑文件,而是抛出以下错误:

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

这看起来不对:

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

您是要 运行 这个 powershell 命令客户端还是 Kudu 端?我猜是 Kudu,在这种情况下你需要逃避它。例如

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