Php exec Powershell 脚本 Azure AZ 命令不执行 运行,所有其他功能执行

Php exec Powershell script Azure AZ commands do not run, all the other functions do

我的PHP脚本

exec('powershell.exe -ExecutionPolicy Unrestricted -NoProfile -InputFormat none -file "..\..\scripts\addcustomer.ps1"', $output);

脚本中的AZ函数:

$file = “$PSScriptRoot\Azure\pass.txt”
$azureuser = “user@contoso.com”
$Password = Get-Content $file | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($azureuser, $Password)
Login-AzAccount -Credential $credential
New-AzDnsRecordSet -Name "$name" -RecordType A -ZoneName "contoso.co" -ResourceGroupName "RG" -Ttl 3600 -DnsRecords (New-AzDnsRecordConfig -IPv4Address "$ipaddress")

$output 不显示此函数的任何输出。我确认如果我手动 运行 脚本,一切正常。

非常感谢。

使用 exec($your_command, $output, $error_code) 并查看 $error_code 包含的内容。可能只是因为 powershell.exe 不在 PHP.

的 PATH 环境变量中

尝试将完整路径放入您的 PowerShell 可执行文件,通常是这样的:

<?php

// A default powershell path in case "where powershell" doesn't work.
define('POWERSHELL_EXE', 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe');

// Find the path to powershell with the "where" command.
$powershell_exe = exec('where powershell');
if ($powershell_exe === false) {
  $powershell_exe = POWERSHELL_EXE;
}

// Also check that the path to your script can be found.
// If it doesn't then you can use realpath() to get the
// full path to your script.
$cmd = $powershell_exe .
       ' -ExecutionPolicy Unrestricted -NoProfile -InputFormat none' .
       ' -file "..\..\scripts\addcustomer.ps1"';

$last_line = exec($cmd, $full_output, $error_code);

// Then check if $last_line !== false and check $error_code to see
// what happened.
var_export([
  '$cmd' => $cmd,
  '$last_line' => $last_line,
  '$full_output' => $full_output,
  '$error_code' => $error_code,
]);

另一个重点:用户运行使用您的PHP代码是否有足够的权限来执行您在PS1脚本中所做的事情?

您可能需要 运行 您的 PowerShell 脚本具有提升权限或其他用户。我从来没有这样做过,但也许这个话题会有所帮助: