在kudu命令api上运行powershell以编辑文件

wixjitnu  于 2021-06-20  发布在  Kudu
关注(0)|答案(1)|浏览(386)

我需要修改我的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 debug控制台中输入这个命令时,上面的命令起作用,但是我需要通过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

但是,它不会编辑文件,而是抛出一个错误:
无法将newtonsoft.json.linq.jobject强制转换为newtonsoft.json.linq.jtoken

cgyqldqp

cgyqldqp1#

这看起来不对:

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

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

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

相关问题