Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Executing PowerShell script from PHP HTML web server

Recently I was reading some Advanced Python coding books, I was especially fascinated by the Flask module. This project is an outcome of the same, If similar can be achieved with PowerShell and HTML, I wrote some code in HTML, PHP and PowerShell and it is working well after testing. Here in this project I used PHP code to get HTML input. Pass that information from PHP to PowerShell as a parameter to execute PowerShell ps1 script.

Basically this will reset user account passwords in Active Directory. 

With this project I can host my PowerShell Scripts using HTML GUI, instead of Windows Forms or WPF xaml. (Sometimes I find it time consuming to maintain and modify if your not working on it frequently)

This is the complete PHP PowerShell code your can download here or it is also available on github.com/janviudapi.

Microsoft PowerShell pwsh php execute ps1 script html website web server css active directory ad account password reset tool user account reset password windows active directory php connection domain controller.jpg

To host this project on Web Server I am using XAMPP application from https://www.apachefriends.org/download.html. (Use XAMPP control to start apache httpd service) Keeping all the project files under folder location C:\xampp\htdocs\psscript. Also make sure you install the PowerShell module for ActiveDirectory as well.

Microsoft xampp php jquery powershell html website htdocs apache index wrap.php html5 css loading gif png files webserver project windows github.jpg

This is the video how it looks and works once hosted on web server.

Below is the index.html file content. Line no 117 will took userID input and forward it as name variable to wrap.php.

# index.html - Code contains HTML 5, CSS, JAVAScript - Ajax

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<!doctype html>
<html lang=en>
	<head>
		<meta charset=utf-8>
		<title>PowerShell with PHP demo</title>
		<style>
			body {
				font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
				text-align: center;	
			}
			 
			div {
				margin: auto;
				width: 50%;
				border: 3px solid coral;				
				padding: 10px;
				border-radius: 0.3cm;
			}
			table {
				margin: 0 auto; /* or margin: 0 auto 0 auto */
				color: #606060;
			}
			.toolheader {
				font-size: x-large;
				font-weight: 600;
			}
			
			input[type=text] {
				width: 100%;
				padding: 12px 20px;
				margin: 8px 0;
				box-sizing: border-box;
				border: 1px solid gray;
				outline: none;
				color: #606060;
			}
			input[type=text]:focus {
				background-color: coral;
				color: white;
				border: 1px solid gray;
			}
			.button {
				background-color: coral; /* Green */
				border: none;
				color: white;
				padding: 15px 32px;
				text-align: center;
				text-decoration: none;
				display: inline-block;
				font-size: 16px;
				margin: 4px 2px;
				cursor: pointer;
				-webkit-transition-duration: 0.4s; /* Safari */
				transition-duration: 0.4s;
			}
			.button:hover {
				box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
			}
			.loading {
				margin-left: auto;
				margin-right: auto;
				width: 128px;
				height: 128px;
				display: none;
			}
		</style>
		<script>
			function ClearFields() {
				// document.getElementById("searchBox").value = '';
				document.getElementById("phpBox").style.display = "none";
			}
		</script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	</head>
	<body>
		<div>
			<table class="toolheader">
				<tr>
					<td style="text-align: center; vertical-align: middle;">AD account password</td>
					<td><img src="reset.png" alt="reset.icon" width="48" height="48"></td>
					<td style="text-align: center; vertical-align: middle;">tool</td>
				</tr>
			</table>			
			<br>			
			<table>
				<tr>
					<th>UserID &nbsp &nbsp</th>
					<td><input id="searchBox" type="text" name="name" value="localhost"></td>
				</tr>
			</table>
			<button class="button searchButton">Reset Password</button> <!-- //instead of Class if id is used use #searchButton -->
			<input class="button clearButton" type="reset" name="Clear" value="Clear" onclick="ClearFields();"><br>
			<br>
			<br>			
			<img class="loading" id="loading" src="loading.gif" alt="Loading, Waiting, Spinner">
		</div>
		<p class="showData"></p>  <!--Show data from php here -->

<!--
		# Written By: http://vcloud-lab.com
		# Date: 19 January 2022
		# Env: Powershell 5.1, PHP (latest), JQuery (latest), HTML 5, CSS, XAMPP		
-->

		<script>
			$(document).ready(function(){
				$("button.searchButton").click(function(){	//instead of Class if id is used use #searchButton
					//document.getElementById("loading").style.display = 'block';
					$("#loading").css("display", "block")
					$("p.showData").html('')
					//document.getElementClassNyName("showData").innerHTML = "";
					$.ajax({
						method: "POST",
						url: "wrap.php",
						data: { 
							//text: $("p.unbroken").text(), //keep adding parameters here with comma
							name: $("input:text").val(), //keep adding parameters here with comma
						}
					})
					.done(function( response ) {
						$("p.showData").html(response); //class showData reference
						//document.getElementById("loading").style.display = "none";
						$("#loading").css("display", "none")
					});
				});
			});		  
		</script>
	</body>
</html>

Once wrap.php gets post request (name variable) from HTML. It passes the same information ot PowerShell script parameter in line number 17.

# wrap.php - PHP code to execute PowerShell script

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?php
	/*
	$text = $_POST['text'];
	$output = wordwrap($text, 60, "<br>");
	echo $output; 
	*/
	    $name = isset($_POST['name']) ? $_POST['name'] : '';
	
	    echo "<div id='phpBox' class='phpData' style='background-color: coral; color: white'>";
	    $userName = shell_exec('powershell -ExecutionPolicy Unrestricted -Command $env:USERNAME');
	    echo "<p class='maintext' style='display: block;'> '<strong>$userName</strong>' requested user account password reset for '<strong>$name</strong>' </p><br/>"; 
	
//    # Written By: http://vcloud-lab.com
//    # Date: 19 January 2022
//    # Env: Powershell 5.1, PHP (latest), JQuery (latest), HTML 5, CSS, XAMPP
	
	    $psfileoutput = shell_exec("PowerShell -ExecutionPolicy Unrestricted -NonInteractive -File Reset-UserPassword.ps1 -UserAccount $name");
	    echo '<pre>' . $psfileoutput . '</pre>';
	echo "</div>";
?>

This is the last piece of the project. It is a PowerShell script to reset user account password in Active Directory. Make sure you install Active Directory module for PowerShell on the web server where you will host this script. 

# Reset-UserPassword.ps1 - PowerShell Reset Password in AD, Set Change it at logon and Unlock it

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
param(
    [string]$UserAccount
)

Import-Module ActiveDirectory

# Written By: http://vcloud-lab.com
# Date: 19 January 2022
# Env: Powershell 5.1, PHP (latest), JQuery (latest), HTML 5, CSS, XAMPP

#$userAccount = 'user10'

$passwordLenght = 18
Add-Type -AssemblyName System.Web
$password = [System.Web.Security.Membership]::GeneratePassword($passwordLenght,1)
$encryptedPassword = ConvertTo-SecureString $password -AsPlainText -Force

try {
    $userInfo = Get-ADUser -Identity $UserAccount -Properties LockedOut -ErrorAction Stop
    $htmlReport = "<h3>User account '$UserAccount' found in AD</h3>`n"
    Set-ADAccountPassword -Identity $UserAccount -NewPassword $encryptedPassword -Reset -ErrorAction Stop
    $htmlReport += "<h2>New password is:</h2> <h1 style='color: black;'>$password</h1>`n"
    Set-ADUser -Identity $UserAccount -ChangePasswordAtLogon $true -ErrorAction Stop
    
    if (!$userInfo.LockedOut)
    {
        Unlock-ADAccount -Identity $UserAccount -ErrorAction Stop
        $htmlReport += "<h3>User account is unlocked</h3>`n"
    }
    $htmlReport 
    #$htmlReport | Out-File c:\temp\logs.txt -Append
}
catch {
    "<h3>User $UserAccount Password Reset failed`n</h3>"
    #$htmlReport | Out-File c:\temp\logs.txt -Append
}

Useful Articles
Powershell GUI encode decode images
Powershell GUI format text on TextBox and RichTextBox
Powershell PoshGUI: Convert user to SID and vice versa using
Microsoft Powershell GUI: Change Internet Options connections Lan settings proxy server grayed out
Powshell GUI Date and Time converter tool
Powershell adding leading zeros to string or int
PowerShell convert string to base64 value
PowerShell Encode or Decode an WebURL
Create an interactive HTML report with PowerShell data

Go Back

Comment

Blog Search

Page Views

12056439

Follow me on Blogarama