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

标签 powershell azure cmd azure-web-app-service kudu

我需要修改 Azure Web App 的文件内容,例如 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 Command 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"

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

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

关于powershell - 通过 Kudu 命令 API 运行 PowerShell 来编辑文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44766365/

相关文章:

powershell - Powershell从文件名中删除前导零

powershell - PowerShell启动之前的PSModulePath变量要求

windows - 如何将Invoke-RestMethod的输出提取到不同的变量中

azure - WebJob 未加载 SendGridMail 程序集

c# - 尝试替换 connectionStrings 元素以在 Visual Studio Team Services 中进行持续部署

powershell - 从子文件夹复制文件并重命名

if-statement - cmd:如果存在A和B,则

批处理文件中的 PHPUnit 设置

windows - 使用 EXIF 增加序列号

c# - 我可以在没有 AzureWebJobsStorage 连接字符串的情况下执行 Azure webjobs 吗?