In this lab we will:
- Add to our Gen_Users.ps1 script so that when we add a ‘switch’ to the command, it will remove all the users that exists in our .json file.
In order to remove users from the system, we’ll utilize the cmdlet Remove-LocalUser. Fortunately it’s a really simple command to run, which mean the ‘function’ we’ll create to handle this operation will also be fairly easy.
Here’s an example of how you might run Remove-LocalUser. (This is just an example.)
Remove-LocalUser -MyUser
We’re going to need a function that looks at each user object and executes this command for each username in the .json file.
Let’s insert this function right underneath our CreateNewUser() function. Again, I’ll give you the code this time.
function RemoveUsers() {
param ([Parameter(Mandatory = $true)] $userObject)
$name = $userObject.name
Remove-LocalUser -name $name
}

We won’t want to run this function every time the program runs. Instead, we’ll create a ‘switch’ that the user can add when they run the command that will trigger this function only when it is needed.
To start, we’ll change the very first line of our script so it will now look like this:
param ([Parameter(Mandatory = $true)] $JSONFile, [switch]$Undo)

This switch will be an optional parameter that we can now check for.
Next, we’ll want to check to see if the user has supplied the -Undo parameter. If it has been supplied, we’ll utilize the RemoveUsers() function.
Let’s change the code at the bottom of our script to look like this:
foreach ($new_object in $users) {
if ($Undo)
{
RemoveUsers($new_object)
}
else {
CreateNewUser($new_object)
}

Now if we run our script like this:
.\\Gen_Users.ps1 .\\userlist.json -Undo