My PHP script
exec('powershell.exe -ExecutionPolicy Unrestricted -NoProfile -InputFormat none -file "..\..\scripts\addcustomer.ps1"', $output);
AZ function in the script:
$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")
The $output does not display any output of this function. I confirm that if I run the script manually, everything works.
Many thanks.
Use exec($your_command, $output, $error_code)
and see what $error_code
contains. It may just be because powershell.exe
isn't in the PATH env variable in PHP.
Try to put the full path to your PowerShell executable, typically something like this:
<?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,
]);
Another important point: Has the user running your PHP code enought rights to do what you are doing in your PS1 script?
You may need to run your PowerShell script with elevation privilege or another user. I never did that but perhaps this topic could help: PHP command to execute powershell script as admin