Firstly I apologise but I am pretty new to PHP and PowerShell, we all have to start somewhere! I am creating a utility where everyday IT tasks can be performed from a central web based console. I have managed to query and report on things like password expiry by executing PowerShell scripts but have got stuck on unlocking accounts. I query AD and return a list of locked users with a button next to each user to unlock them. This button posts to a php page which runs another powershell script to unlock the user. php page is:
<?php
// Get the variables submitted by POST in order to pass them to the PowerShell script:
$lockeduser = $_POST["unlock"];
// Path to the PowerShell script.
$psScriptPath = "C:\\code\\psphp\\ps\\unlock.ps1 $lockeduser 2>&1";
// Execute the PowerShell script:
exec("powershell -command $psScriptPath",$out,$ret);
echo "<pre>";
print_r ($out);
print_r ($ret);
echo "</pre>";
?>
As you can see I'm trying to capture any output but at the moment the page is just hanging.
PowerShell script is:
param([string]$lockeduser)
Import-Module ActiveDirectory
$adminacc = "*myadminaccount*"
$encrypted = Get-Content c:\password1.txt | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($adminacc, $encrypted)
Unlock-ADAccount -Identity $lockeduser -Credential $credential
If I echo the command before passing it to PS it looks fine and can be executed directly from PS.
Edit: This is something to do with exec (or shell_exec) causing an issue when the PS script is setting credentials. If I remove that part of the script i.e.
param([string]$lockeduser)
Import-Module ActiveDirectory
Unlock-ADAccount -Identity $lockeduser
it runs and returns that the script failed due to
Insufficient access rights to perform the operation
Has anyone come across this before, I have searched for anything on this to no avail. Thanks!
Further edit After a bit more testing it is this PS code that doesn't work
$encrypted = Get-Content c:\password1.txt | ConvertTo-SecureString
If I change the method to
$password = ConvertTo-SecureString "My Password" -AsPlainText -Force
it works with no problems. Plain text passwords in files are obviously not something I want to use. Can someone test and see if they get the same result?
So it turns out that it was all just me being a newb. Executing the script via the php page must not be running it as my account. My account was the one that set the credentials and stored it in the file so is the only one that can decrypt it. I have changed the convertto-securestring method to use keys instead of default and it now works.