More Auto-Loading, Custom PowerShell Scripts

In this update, you’ll see how I added two or three new scripts to the environment and also changed how most of the scripts work.

One new script that I add was a script that would take CSV data and add the users to a group in Active Directory. You can see this below:

function Get-CSVAddToGroup{
 <#
 .SYNOPSIS
 This function allows you to add usernames from a CSV to a specified Active Directory group.
 It needs confirmation for each addition to a group.

 .EXAMPLE
 Get-CheckCSVAddToGroup -Groupname "all rossendale staff" -path c:\testing\test.csv

 #>
 [cmdletbinding()]
 param(
 [parameter(Mandatory=$true)]
 [string]$groupname,

 [parameter(mandatory=$true)]
 [string]$path
 )

 $csvformembership = Import-Csv -Path $path

 foreach ($b in $csvformembership){
  $name = $b.user
  Add-ADGroupMember -Identity "$groupname" -Members $name -Confirm
 }
}

Another script I added was my script for sending messages to remote computers on the network. You can see this below:

function Send-Message{

 function send-messagewithname{
  $name = Read-Host "Enter a name"
  $msg = Read-Host "enter a message"
  $adcompstocheck = Get-ADComputer -LDAPFilter "(name=$name)" -Properties name

  if ($adcompstocheck -eq $null){
   Write-Host "$name doesn't exist!"
   pause
  }else{
   Invoke-WmiMethod -Path win32_process -Name create -ArgumentList "msg * $msg" -ComputerName "$name"
  }
 }

 function send-messagewithip{
  $ip = Read-Host "enter an IP"
  $msg = Read-Host "enter a message"
  $adcompstocheckip = Get-ADComputer -Filter * -Properties ipv4address, name | select ipv4address
  if ($adcompstocheckip -eq $null){
   write-host "$ip doesn't exist"
   pause
  }else{
   Invoke-WmiMethod -Path win32_process -Name create -ArgumentList "msg * $msg" -ComputerName "$ip"
  }
 }

 do {$nameorip = Read-Host "Do you want to use IP or Name (I or N)?"} while (("i","n") -notcontains $nameorip)
 if ($nameorip -eq "n"){
  send-messagewithname
 }else {
  send-messagewithip
 }
}

Finally, my last script that was added to my custom PowerShell environment allowed me to list all the computers on the network with a specific operating system. For example “2012” or “Professional”. The code for this is below:

function list-OSVersonComputers{
 <#
 .SYNOPSIS
 This function allows you to list all of the computers with the requested OS version.

 .EXAMPLE
 List-OSVersionComputers -OSVersion 2012

 .EXAMPLE
 List-OSVersionComputers -OSVersion standard
 #>
 [cmdletbinding()]
  param(
  [parameter(mandatory=$true)]
  [string]$OSVersion
 )

 $OSVersion2 = '*' + ($OSVersion) + '*'

 Get-ADComputer -Filter {OperatingSystem -like $OSVersion2} -Property * | Format-Table name,operatingsystem,lastlogondate -Wrap -AutoSize
}

I also added help menus to most of my scripts to make them more professional.

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!