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!