Verb Guessing Game in PowerShell

Verb guesser Featured image

Another game today. In PowerShell of all things. Who would have thought?

Anyway, in this blog post I will be showing you the code I used to create a random word guessing in PowerShell. The script works by taking all the verb information from the

Get-Verb

command and selecting only the verb part of each one.

The script then selects on at random, does some formatting and removes the vowels. That part is important. Pretty much is the single defining feature that makes this thing a game. With the vowels now removed, the user has to guess the verb. If they get it correct then a point is added to their score. If they get it wrong then the game resets and they start again from 0 points. (Well, 1 point if you’re being technical)

Here the code:

function verbguessinggame{
 $getverbs = Get-Verb | select verb
 [int]$verbamount = $getverbs.count
 $score = 0
 do{
  $random = Get-Random -Minimum 0 -Maximum $verbamount
  $selectedword = $getverbs[$random] -replace "@{verb=","" -replace "}",""
  $selectedwordlength = $selectedword.length
  $vowelsremoved = $selectedword -replace '[aeiou]',""

  $score = $score + 1
  Clear-Host
  Write-Host $vowelsremoved -ForegroundColor Red -BackgroundColor Black
  $guess = Read-Host "What is the word?"
 }until($guess -ne $selectedword)
 Clear-Host
 Write-Host "incorrect, the verb was $selectedword"
 Write-Host "Your score was $score"
 Start-Sleep -Seconds 1.5
 Clear-Host

 do {$playagainselection = Read-Host "Do you want to play again? (Y or N)"} while (("y","n") -notcontains $playagainselection)
 if ($playagainselection -eq "y"){
  verbguessinggame
 }elseif ($playagainselection -eq "n"){
  exit
 }
}

verbguessinggame

I will be updating my Games in PowerShell project with this game as well as making some custom changes to this game and others in the project.

Quick Fire Character Counting Game In PowerShell

Another pointless activity in PowerShell. The premis of this game is that you have a short amount of time to look at a word, you then have to guess how many letters are in the word.

If you get the number correct, the game continues and your score increases. If you input and incorrect number, then the game ends, shows your score and exits.

As always I have added this to my “Games In PowerShell” project. Below is the code for the game:

function quickfirecounting{
 $getverbs = Get-Verb | select verb
 [int]$verbamount = $getverbs.count
 $scoreforquickfire = 0
 do{
  $random = Get-Random -Minimum 0 -Maximum $verbamount
  $selectedword = $getverbs[$random] -replace "@{verb=","" -replace "}",""
  $selectedwordlength = $selectedword.Length

  $scoreforquickfire = $scoreforquickfire + 1
  Clear-Host
  Write-Host "$selectedword"
  Start-Sleep -Milliseconds 550
  Clear-Host
  $guess = Read-Host "how many letters are in the word?"
 }until ($guess -ne $selectedwordlength)
 Clear-Host
 Write-Host "Incorrect! There were $selectedwordlength letters"
 Start-Sleep -Seconds 1
 Clear-Host
 Write-Host "Your score was $scoreforquickfire"
 Start-Sleep -Seconds 1
 Clear-Host

 do {$playagainselection = Read-Host "do you want to play again? (Y or N)"} while (("y","n") -notcontains $playagainselection)
 if ($playagainselection -eq "y"){
  ####GO TO GAME FUNCTION TO PLAY AGAIN####
 }elseif ($playagainselection -eq "n"){
  ####GO TO THE MAIN MENU####
 }
}

As you can probably see, I am using the verb section of PowerShell to get the random words. This is better and easier than inputting my own words individually.

Enjoy!

My Custom, Auto-Loading PowerShell Scripts

Wanted to add onto a post I made about 10 days ago about creating a custom PowerShell environment. I currently have 3 custom commands for user management, 2 custom commands for group management and 1 command to list these (and the “homepage”) for my PowerShell prompt. So for my first example below, in the custom PowerShell prompt I would use “list-users”.

Users

I suppose I will kick off an just start with my custom commands for user management. By the way, if you didn’t know the name of the function in the PowerShell custom command is the actual commandlet you use in the custom PowerShell prompt.

First of all, I wanted a simple and quick way of getting the all users that are enabled and sorting them, then outputting them to the OGV. The following is what I used:

function list-users{
 Get-ADUser -Filter {enabled -eq $true} | sort | select name, samaccountname | ogv
}

Nice and simple, right…?

Next, I wanted to get the actual location within Active Directory as to where the user account is stored. I also wanted to be able to use a username or a full name in order to search for this information. You can see my code below:

function list-userlocation{

 function list-useragainstusername{
  $username = Read-Host "Input a username"

  $checkingAD = Get-ADUser -LDAPFilter "(samaccountname=$username)"
  if ($checkingAD -eq $null){
   Write-Host "$username does not exist!"
   pause
  }else{Get-ADUser -Identity $username | select distinguishedname }
 }

 function list-useragainstfullname{
  $fullname = read-host "input a full name"
  $checkingAD = get-aduser -ldapfilter  "(name=$fullname)"
  if ($checkingad -eq $null){
   write-host "$fullname does not exist!"
   pause
  }else{get-aduser -ldapfilter "(name=$fullname)" | select Distinguishedname}
 }

 do {$selection = read-host "check against full name or username (F or U)?"} while (("f","u") -notcontains $selection)
 if ($selection -eq "f"){
  list-useragainstfullname
 }elseif ($selection -eq "u"){
  list-useragainstusername
 }
}

Just in case you want to know, the output for the above command will look something like this “CN=NAME,OU=First OU,OU=Second OU,DC=sanderson,DC=lan”.

Finally, I have a command which allows me to get the the group membership of a user and then output that to a file. I have also made this one so that I can use the full name of a user as well as their username.

function list-usermembership{

 function list-usermembershipfromusername{
  $username = read-host "Input a username"

  $checkingAD = Get-ADUser -LDAPFilter "(samaccountname=$username)"
  if ($checkingAD -eq $null){
   Write-Host "$username does not exist!"
   pause
  }else{
   Write-Host "File with membership has been output to the desktop"
   Get-ADPrincipalGroupMembership $username | sort | select name | Out-File -FilePath  "c:\users\YOU!\desktop\$username Group Membership List.txt" -Append
  }
 }

 function list-usermembershipfromfullname{
  $fullname = Read-Host "Input a fullname"

  $checkingAD = Get-ADUser -LDAPFilter "(name=$fullname)"
  if ($checkingAD -eq $null){
   write-host "$fullname does not exist!"
   pause
  }else{
   $fullnameresolved = Get-ADUser -LDAPFilter "(name=$fullname)";
   $filename = $fullnameresolved.SamAccountName;
   Get-ADPrincipalGroupMembership -Identity $fullnameresolved | sort | select name | Out-File "c:\users\YOU!\desktop\$filename Group Membership List.txt" -Append;
   Write-Host "file with membership has been output to the desktop"
  }
 }

 do {$selection = Read-Host "Do you want to use fullnames or usernames? (F or U)"} while (("F","u") -notcontains $selection)
 if($selection -eq "f"){
  list-usermembershipfromfullname
 }elseif ($selection -eq "u"){
  list-usermembershipfromusername
 }else {}

}

Again, just in case you wanted to know, this outputs to a text document that will roughly ressemble the following:

name

—–

Group #1

Group #2

This allows me to quickly see if multiple users are part of a group and also to get a reference of group membership before disabling a user and removing them from all of their groups.

Groups

Lets move onto group management automation. This area is a little less sparse because, well… in my experience atleast, users are dumber than groups.

Again, a very simple one to start off with. This one simply lists all of the groups on the domain, selects certain attributes of the groups, sorts them and then ouputs them to OGV.

Below is the code for that:

function list-groups{

 Get-ADGroup -Filter * | select distinguishedname, name | sort | ogv

}

As I said, the group side of things is a little sparse. As in I only have two custom commands for them.

My other custom command for Active Directory groups collects me the membership information for that group. Like the users, I also make sure that my input matches a group within AD. Below is my code:

function list-groupmembership{
 $groupname = Read-Host "What group do you want to check?"

 $adlistforgroupcheck = Get-ADGroup -LDAPFilter "(name=$groupname)"

 if ($adlistforgroupcheck -eq $null){
  Write-Host "$groupname does not exist"
  pause
 }else {
  Get-ADGroupMember -Identity $groupname | select name, samaccountname | sort name | ogv
 }
}

Re-Displaying the Custom Commands

Now, an issue I ran into when I added these to my PowerShell environment was that when I had ran a command, or used clear-host or something along those lines. It meant that I could no longer see my custom commands, making them useless since I couldn’t remember what I had called the bloody things πŸ™‚

That’s why I create a new command that would imitate what the prompt looks like when I first load it up. You can see my code below:

function list-customcommands{

 write-host @"
Custom PowerShell Environment Loaded
Go to '$profile' for config changes
go to 'documents\windowspowershell\scripts\autoload to add new scripts'

List of commands:             |
USERS                    |   GROUPS
List-users | ogv            |   list-groups | ogv
list-usermembership | file to desktop     |   list-groupmembership | ogv
list-userlocation            |
|
"@

}

Bit of a long post I know, but necessary background on some examples for custom PowerShell environments and Active Directory automation.

Enjoy!

Custom PowerShell Environment and Modules

To add custom PowerShell modules to your PowerShell environment, you first need to find out where you PowerShell profile is. You can do this by typing in:

$profile

into a PowerShell prompt. It should look like the following:

$profile

Now we need to test if the path actually exists. To do this type:

Test-Path $profile

If the prompt returns $true, your good. If it returns $false then you will need to run the following command:

New-Item -Path $profile -Itemtype file -Force

Now that is done we should be able to open the file in notepad. You can either browse to it following the path in $profile or type in:

notepad $profile

This should open a blank text file:

$profile empty

In here is where you specify PowerShell to look for custom modules and can even add text to the PowerShell prompt. For example, if I had the following to the notepad, it will also be displayed when I open a new PowerShell window:

custom $profile (write-host)

But we can also use this to load custom functions into our PowerShell environment. To do this, got to the $profile location, here you should find a folder called “Scripts”

Scripts folder

Go into the folder and create a new folder, mine is called “autoload”

autoload

Here is where you create your custom functions/ scripts. For example, here is what I have:

list-example

where each file contains a single function.

Now that were done with the easy part. You want to go back into your $profile notepad and add the following in order for PowerShell to load your customer functions:

$psdir="C:\users\YOU!\documents\windowspowershell\scripts\YOURSCRIPTFILENAME"

get-childitem "${psdir}\*.ps1" | %{.$_}

You can see from my file. I have multiple files to make for easier sorting of my functions. I also have a custom start screen to list all of my current commands so that I don’t forget them. You can see that below:

$profile example

Just so that you can see, this is what my PowerShell prompts look like:

My prompt

For a list on verbs and commands that you can use, visit the Microsoft website and forums. You DON’T want to use verbs or commands that are used else where or that have a unique purpose. Choose verbs that are different. Good luck. Enjoy!

Secure Password Generation In PowerShell

Nice simple one today. Very short and easy. Just made a big post to my job automation project which is why I made the following script in PowerShell. Basically what I needed was to be able to reset multiple user account passwords in Active Directory. This meant that I needed to generate secure passwords, this was to ensure that they would meet the minimum requirements, and also convert them to something that PowerShell and Active Directory “liked”.

The below 3 lines of code should do the trick:

[string]$initialpassword = ([char[]](Get-Random -input $(47..57 + 65..90 +97..122) -count 8)) + (Get-Random -minimum 0 -maximum 10)

$passwordwithspacesremoved = $initialpassword.Replace(' ','')

$convertedpassword = ConvertTo-SecureString -AsPlainText $passwordwithspacesremoved -Force

I had the add the extra “Get-Random -Minimum 0 -Maximum 10” because, since its randomly generated, sometimes it didn’t include a single number. This obviously would make the password not secure enough to be used within Active Directory. So rather than waste time trying to define the randomness to include some sort of number, I simply made damn sure that there would always be a random digit at the end. Both ensuring sufficient security to be used in Active Directory and also still being random. (Wouldn’t be good if all the passwords ended in 3 :p )

How I used this code, only if you’re interested though is like this:

Set-ADAccountPassword -Identity $USERNAME$ -Reset - NewPassword $convertedpassword -PassThru | Enables-ADAccount | Unlock-ADAccount

As you can see, I have passed the secure string password into the account reset command. Works like a charm. Some of the other parameters (such as -PassThru) stops the process being weird /breaking.

Enjoy!

More Games In PowerShell

This is, yet again, another improvement to a script I created earlier, you can find this here.

What I have done is added some new games (3 to be exact) and also created some unnecessary “fancy” bits such as a loading screen and a “Goodbye” exiting message. I have also changed the menu to be a single “echo” command instead of the multiple “write-host” which makes the code look cleaner.

The three games I have added are pretty much all the same game. I was getting sick of guessing games and since making actual games in PowerShell is VERY complex. I decided to make a math game. Specifically one that give the user a math question and the user has to work out the correct answer. An example would be “4 * ? = 12”. Where the user would have to work out “?”.

I made three difficulties of this, easy (1-10), medium (1-20) and hard (1-50). This means that the answers in the easy section are from 1 to 10, the answers in the medium are from 1 to 20 and so on…

I also added a function to change the size of the window to something more appropriate and changed the window title to something more…fun.

Anyway, below is the code for this. Unfortunately, I didn’t break the “300 lines of code” achievement I had set for myself:

function changescreensizeforgames{
 $pshost = get-host
 $pswindow = $pshost.ui.rawui
 $newsize = $pswindow.buffersize
 $newsize.height = 500
 $newsize.width = 500
 $pswindow.buffersize = $newsize
 $newsize = $pswindow.windowsize
 $newsize.height = 15
 $newsize.width = 51
 $pswindow.windowsize = $newsize
 $pswindow.WindowTitle = "Games Galore!"
}
changescreensizeforgames

function fakeloadingbar{
 cls
 echo "-....."
 Start-Sleep -Milliseconds 150
 cls
 echo ".-...."
 Start-Sleep -Milliseconds 150
 cls
 echo "..-..."
 Start-Sleep -Milliseconds 150
 cls
 echo "...-.."
 Start-Sleep -Milliseconds 150
 cls
 echo "....-."
 Start-Sleep -Milliseconds 150
 cls
 echo ".....-"
 Start-Sleep -Milliseconds 150
 cls
 echo "....-."
 Start-Sleep -Milliseconds 150
 cls
 echo "...-.."
 Start-Sleep -Milliseconds 150
 cls
 echo "..-..."
 Start-Sleep -Milliseconds 150
 cls
 echo ".-...."
 Start-Sleep -Milliseconds 150
 cls
 echo "-....."
 Start-Sleep -Milliseconds 150
 cls
}
fakeloadingbar

function exitscreenforgames{
 cls
 echo @"
####   #    # #####  ##
#   #   #  #  #      ##
#####    ##   ####   ##
#    #   ##   #      ##
#    #   ##   #
#####    ##   #####  ##
"@
 Start-Sleep -Seconds 1
 exit
}

#Window size change

#INTRO (Start Menu)
function menu2{

function Show-Menu{
 param (
 [string]$Title = 'My Menu'
 )
 Clear-Host
 write-host @"
================ $Title ================

Guessing Games------------
1: Press '1' to play 1-10 with 1 guess
2: Press '2' for 1-100 with unlimited guesses

Multiplication Games------
3: Press '3' for easy mulitplication game (1-10)
4: Press '4' for medium multiplication game (1-20)
5: Press '5' for hard multiplication game (1-50)

Q: Press 'Q' to quit.
"@
 }

 Show-Menu -Title 'Select an option'
 $selection = read-host "please make a selection"

 if ($selection -eq "1"){
  write-host "You chose option one" (1to10guessgame)
 }elseif ($selection -eq "2"){
 Write-Host "you chose option two" (1to100guessgame)
 }elseif ($selection -eq "3"){
  write-host "You chose option three" (easymathgame)
 }elseif ($selection -eq "4"){
  write-host "You chose option four" (mediummathgame)
 }elseif ($selection -eq "5"){
  write-host "You chose option four" (hardmathgame)
 }elseif ($selection -eq "q"){
  clear-host
 Do {$areyousuremessage = Read-Host "Are you sure you want to quit? Y or N?"} while (("y","n") -notcontains $areyousuremessage)
  switch ($areyousuremessage){

   "y" {exitscreenforgames}
   "n" {menu2}

  }

 }else {
  (menu2)
 }
}

#Single guess game
function 1to10guessgame{

 clear-host
 Write-Host "You only have one guess!"
 Start-Sleep -Seconds 1
 Write-Host "Are you ready?"
 start-sleep -Seconds 1

 $random =  Get-Random -Minimum 1 -Maximum 11

 do {
  try {
   $numOk = $true
   [int]$input1 = Read-host "Make a guess between 1 and 10"
  }catch {$numOK = $false}
 }until (($input1 -ge 1 -and $input1 -lt 11) -and $numOK)

 if ($input1 -eq $random){
  Write-Host "You got it right!"
 }else{
  Write-Host "You got it wrong! the number was $random"
 }

 Start-Sleep -Seconds 2

 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  (1to10guessgame)
 }elseif ($playagain1 -eq "n"){
  (menu2)
 }

}

#1-100 Guess game
function 1to100guessgame{

 clear-host

 [int]$random100 = Get-Random -Minimum 1 -Maximum 101

 Write-Host "Try and guess my number between 1 and 100"

 while ($input100 -ne $random100){
  Write-Host "enter your guess below"
  $input100 = [int] (Read-Host)

  $option1 = if ($input100 -gt $random100) {Write-Host "$input100 was too high"}
  $option2 = if ($input100 -lt $random100) {Write-Host "$input100 was too low"}
  $option3 = if ($input100 -gt [int](100) -or $input -lt [int](0)) {Write-Host 'between 1 and 100!'}

 } Write-Host "Correct! the number was $input100"

 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  (1to100guessgame)
 }elseif ($playagain1 -eq "n"){
  (menu2)
 }
}

#easy math game 1-10
function easymathgame{
 $easynewnumber1 = get-random -minimum 1 -maximum 11
 $easynewnumber2 = Get-Random -Minimum 1 -Maximum 11

 $easynumbermultiplied = $easynewnumber1 * $easynewnumber2
 Clear-Host
 Write-Host "Here is your question, can you work out '?'"
 write-host "$easynewnumber2 * ? = $easynumbermultiplied"

 do{
  try{
   $numOk = $true
   [int]$easynewnumberinput = Read-Host "Enter your answer here..."
  }catch {$numOk = $false}
 }until (($easynewnumberinput -ge 1 -and $easynewnumberinput -lt 11) -and $numOk)

 if ($easynewnumberinput -eq $easynewnumber1){
  Write-Host "You got it right!"
 }elseif ($easynewnumberinput -ne $easynewnumber1){
  Write-Host "You got it wrong, the answer was $easynewnumber1"
 } Start-Sleep -Seconds 1

 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  easymathgame
 }elseif ($playagain1 -eq "n"){
  (menu2)
 }
}

#medium math game 1-20
function mediummathgame{ 
 $mediumnewnumber1 = get-random -minimum 1 -maximum 20
 $mediumnewnumber2 = Get-Random -Minimum 1 -Maximum 20

 $mediumnumbermultiplied = $mediumnewnumber1 * $mediumnewnumber2
 Clear-Host
 Write-Host "Here is your question, can you work out '?'"
 write-host "$mediumnewnumber2 * ? = $mediumnumbermultiplied"

 do{
  try{
   $numOk = $true
   [int]$mediumnewnumberinput = Read-Host "Enter your answer here..."
  }catch {$numOk = $false}
 }until (($mediumnewnumberinput -ge 1 -and $mediumnewnumberinput -lt 20) -and $numOk)

 if ($mediumnewnumberinput -eq $mediumnewnumber1){
  Write-Host "You got it right!"
 }elseif ($mediumnewnumberinput -ne $mediumnewnumber1){
  Write-Host "You got it wrong, the answer was $mediumnewnumber1"
 } Start-Sleep -Seconds 1
 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  mediummathgame
 }elseif ($playagain1 -eq "n"){
  (menu2)
 }
}

#Difficult math game 1-50
function hardmathgame{
 $hardnewnumber1 = get-random -minimum 1 -maximum 50
 $hardnewnumber2 = Get-Random -Minimum 1 -Maximum 50

 $hardnumbermultiplied = $hardnewnumber1 * $hardnewnumber2
 Clear-Host
 Write-Host "Here is your question, can you work out '?'"
 write-host "$hardnewnumber2 * ? = $hardnumbermultiplied"

 do{
  try{
   $numOk = $true
   [int]$hardnewnumberinput = Read-Host "Enter your answer here..."
  }catch {$numOk = $false}
 }until (($hardnewnumberinput -ge 1 -and $hardnewnumberinput -lt 51) -and $numOk)

 if ($hardnewnumberinput -eq $hardnewnumber1){
  Write-Host "You got it right!"
 }elseif ($hardnewnumberinput -ne $hardnewnumber1){
  Write-Host "You got it wrong, the answer was $hardnewnumber1"
 } Start-Sleep -Seconds 1
 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  hardmathgame
 }elseif ($playagain1 -eq "n"){
  (menu2)
 } 
}
menu2

Hopefully you’re as happy with this code as I am, if you have any improvements please let me know πŸ™‚

Enjoy!

Number Guessing Games in PowerShell

CLICK HERE TO SEE THESE GAMES AND A MENU IN A SINGLE FILE.

This guide will show you how to make a two types of number guessing games in the coding language of PowerShell.

——————–1-10 With A Single Guess———————

Below is my code for a 1 to 10 guessing game in which the player has a single try to guess the number correctly:

function single-guess{

 clear
 Write-Host "You only have one guess!"
 Start-Sleep -Seconds 1
 Write-Host "Are you ready?"
 start-sleep -Seconds 1

 $random1to10 =  Get-Random -Minimum 1 -Maximum 11

 do {
  try {
   $numOk = $true
   [int]$input1 = Read-host "Make a guess between 1 and 10"
   }catch {$numOK = $false}
 }until (($input1 -ge 1 -and $input1 -lt 11) -and $numOK)

 if ($input1 -eq $random1to10){
  Write-Host "You got it right!"
 }elseif ($input1 -ne $random1to10){
  Write-Host "You got it wrong! the number was $random1to10"

 Start-Sleep -Seconds 2
 }
}

From this you can see that I start with a little intro of “Are you ready?” and other various starting lines. I then create a random number between 1 and 11 (Actually between 1 and 10 as the -maximum in this case signifies the highest amount the number cannot be), and then put that intoΒ  a variable. I then ask the user for a number (guess) between 1 and 10 and then use an if statement to test whether the guess was the same as the randomly generated number.

Now that you have the basic 1 to 10 game, we will move onto a 1 to 100 guess game with unlimited guesses.

——————1-100 With Unlimited Guesses——————

This code is a bit different since the user can have unlimited guesses. You can see how I made this possible in the code below:

function 1to100guessgame{

 clear

 [int]$random100 = Get-Random -Minimum 1 -Maximum 101

 Write-Host "Try and guess my number between 1 and 100"

 while ($input100 -ne $random100){
  Write-Host "enter your guess below"
  $input100 = [int] (Read-Host)

  $option1 = if ($input100 -gt $random100) {Write-Host "$input100 was too high"}
  $option2 = if ($input100 -lt $random100) {Write-Host "$input100 was too low"}
  $option3 = if ($input100 -gt [int](100) -or $input -lt [int](0)) {Write-Host 'between 1 and 100!'}

 } Write-Host "Correct! the number was $input100"
}

In this code I still created a random number and put it into a variable. But I used a “while” statement instead of an “if” statement, meaning that it loops until the user has guessed the correct number. I still haven’t figured out how to make sure that the user inputted date is an actual number, which if it’s not then it will output an error.

The 1 to 100 guessing game also informs the user whether the number they entered is too high or too low, this helps the user guess the number quicker.

——————————–CONCLUSION——————————–

These games a fun and all but they aren’t very well accessible or re-run-able (if that’s even a word). So I think I will create a menu for these and any future games I make so that they can all be played in one place and in one file. Till then!

Remember! If you want to be able to run scripts then you need to change you execution policy. You can see how to do that here!

Adding Signatures In Mimecast

Bit different from, the now usual, Powershell guides. Thought I’d do something different. This guide will show you how to add a custom signature to a user, multiple users’ or even globally.

Lets start off. You’ll want to log into your Mimecast administrative console, go to Service-Gateway-Policies. In here you should see “Stationary”. We want to create a new definition, so click on the “Definition” button on the “Stationary” listing.

Here you can click the “New Item” button. For the Description, obviously, enter a brief description of the new definition. The “Unique Identification Text” is used to scan an email that the definition is applied to to determine if the signature has already been added, so you want to add something that is in the signature and something that is unique to this signature. For the short code, enter a unique name. Below is an example of mine:

1

Now we want to edit the HTML so that there actually is a signature to put onto the emails. Click on the “Edit HTML” button and enter your signature. This is the code I added to mine:

<html>
 <head>
 </head>
  <body>
    <mc type="body">

    <font size="2" color="gray">
    This is a test email signature for marketing
    </font>

    <img src="IMAGE LINK" alt="ALTERNATIVE IMAGE NAME" style="width:214px;height:24px:" />

 </body>
</html>

So in my signature I have the message “This is a test email signature for marketing” and also a company logo.

Now we have that, we need to add it to an actual policy, otherwise it simply won’t be used by anything. Navigate back after saving your definition to the “Policies” page and click on the “Stationary” row. You now want to click “New Policy” which should open up a new policy creation window.

For the “Policy Narrative” enter a name for the policy, for the “Select Stationary”, select “lookup”, find your newly created definition and click “Select”. Since I created mine as a test and my Mimecast access is on my business email address, I configured an individual send and to email address for the policy to apply to. On this page you can also select when the policy will be active or even a range of source IP addresses.

Below are the values that I entered. The emails are removed for obvious reasons:

2

Finally, below is an example of an email with the newly added signature:

3

You should now have a custom signature that applies to every user defined in the policy instead of individual users.

File & Folder Creation with File Sorting in Powershell

Long post today. Definitely my most complex and longest script. Basically what this does it is looks at two separate CSV files, one has a list of locations and the other has a list of users/ people with a location assigned to them as well as some other attributes. WARNING! this script is variables center!

First of all, lets import our locations and create a folder with that location name. This is the code I used for this:

$get_Location_csv = Import-Csv -path 'C:\#PATH TO LOCATIONS CSV FILE'
[string]$root_dir = 'C:\#PATH TO ROOT FOLDER'
try{
 foreach ($location_data in $get_Location_csv){
  $location = $location_data.location #obtain location info
  if(Test-Path -Path $root_dir$location){
   Write-Host "Path already exists!"
  }else{
   New-Item -path $root_dir -Name "$location" -ItemType directory -ErrorAction SilentlyContinue
  }
 }

So from this you can see that we import the folder with the CSV values, check if where the folder will be created already exists, if so then output text, if not then create the folder with the location name. In case you were wondering, here is the value from my CSV file for the locations:

1 location CSV entries

Now that the files have been created, we want to import the other CSV file which contains a list of the users we need sorting and where they need sorting to. Below is the code I used to get the values I wanted, create the file, name it, put data in it and then put it into the relevant folder based on the users location.

$get_user_data = Import-Csv -Path "$root_dir\#USER INFO CSV"

foreach ($i in $get_user_data){
 $first = $i.first
 $last = $i.last
 $username = $i.username
 $location = $i.location
 $datetime = [datetime] (Get-Date)
 $district = $i.district
 foreach($l in $location){
  New-Item -Path "$root_dir$location" -Value "$first $last $location District = $district $datetime" -Name "$username .txt" -ErrorAction Stop
 }
}

To end the code off so that it worked more cleanly in the case of an error I added the following:

}catch{
 $_.exception.message
 Write-Warning 'location:'$i 'was not created successfull!'
}

This catches any errors that might occur during the scripts operation

Again, in case your wondering what is actually in the users CSV file, you can see that in the below screenshot:

Users CSV file

 

This is the output of the script

Here you can see the folders the script created:Folders createdYou can see that the script created all of the locations in the location CSV file. (Leeds, Newcastle, Rotherham, Sheffield, York)

Here you can see the files that are in one of the folders (I chose Leeds):

Users created in leedsHere is what is in each of the files:

User information

From these screenshots you can see that the script has successfully created and sorted the files by the location defined to each user in the users CSV file. You could probably make this work from just the one CSV file, but I went for the long way round πŸ™‚

Here is the entire script!

$get_Location_csv = Import-Csv -path 'C:\#PATH TO LOCATIONS CSV FILE'
[string]$root_dir = 'C:\#PATH TO ROOT DIRECTORY'
try{
 foreach ($location_data in $get_Location_csv){
  $location = $location_data.location
  if(Test-Path -Path $root_dir$location){
   Write-Host "Path already exists!"
  }else{
   New-Item -path $root_dir -Name "$location" -ItemType directory -ErrorAction SilentlyContinue
  }
 }

$get_user_data = Import-Csv -Path "$root_dir\Users.csv"

foreach ($i in $get_user_data){
 $first = $i.first
 $last = $i.last
 $username = $i.username
 $location = $i.location
 $datetime = [datetime] (Get-Date)
 $district = $i.district
 foreach($l in $location){
  New-Item -Path "$root_dir$location" -Value "$first $last $location District = $district $datetime" -Name "$username .txt" -ErrorAction Stop
 }
}
}catch{
 $_.exception.message
 Write-Warning 'location:'$i 'was not created successfull!'
}

Drive Name Checker Against Variable

Before you can use scripts, see my post on how to allow them to be run here

This script gets the name of a drive specified by the drive letter and then compares this to a variable. In my script I compared the drive to the day of the week and the actual name of the drive.

First we need to get the name of the drive and put it into a variable. This is the code I used:

$drive = Get-Wmiobject -Class win32_volume -Filter "Driveletter = 'D:'"

Now we need a something to compare the drive name to. Here you can see that I have used both the day of the week and the actual name of the drive. I did this because you might have daily back-ups and want to make sure that the right drive is inserted for that day. Here’s the code I used:

$compareto = ( "Back-Up Drive" )

or you could compare the drive name to the day of the week:

$compareto = ( (Get-Date).DayOfWeek )

Here is the actual function that compares the drive name to the variable “$compareto” that we just created:

function usb-check {

 if ( (($drive).Label -eq $compareto) ){

  Write-Host "The drive is the same as the variable"

 }elseif ( (($drive).Label -eq $compareto) ){

  Write-host "The drive is NOT the same as specified"

 } 
}

Here is the full code for you to use:

$drive = Get-WmiObject -Class win32_volume -Filter "DriveLetter = 'D:'"
$compareto = ( "Back-Up Drive")
## ( (Get-Date).DayOfWeek )
##

function usb-check {
 if ( (($drive).Label -eq $compareto) ){
  Write-Host "The drive is the same as specified"
 }elseif ( (($drive).Label -ne $compareto) ){
  Write-Host "The drive is not the same as specified"
 } 
}

usb-check

pause

You can see that I have two variables, one commented out and another in use. This is just to give me and you more options to switch between quickly. If your wondering below are the two outputs from the function:

1

2

Hope you enjoyed!