PowerShell Modules Part 2

There are dozens of powershell tool writeups, and I don’t want to just rehash what they say, so I will summarize what I use, and why.

First of all, there is a limited functionality that comes with Powershell. The PSE (powershell editor) works – but it’s limited. So I prefer third party editors like PowerGui Script Editor

Once you have an editor of choice you can start coding. However there may come a time when you need something… more. Third party sets of commandlets are available to enhance your abilities.

So what modules do you already have? To find out – run the Get-Module cmdlet with the -ListAvailable switch to list all the modules already installed.

Get-Module -ListAvailable

The cmdlet outputs too much information for me, so If like me you want to see just the names and their descriptions. So the trick is to pass the output via a “format-table” command:

Get-Module -ListAvailable | Format-Table Name, Description

Which gives us something like this:

Name Description
—- ———–
ActiveDirectory
NetworkController Powershell cmdlets to manage a NetworkControll…
AppvClient Microsoft Application Virtualization Client Mo…
Microsoft.EnterpriseManagement.Core.Cmdlets System Center Cmdlets Module
Microsoft.EnterpriseManagement.ServiceManager.Cmdlets System Center Service Manager 2010 R2 Cmdlets …
Microsoft.MonitoringAgent.PowerShell
SMLets CodePlex Service Manager Cmdlets
ActiveRolesManagementShell ActiveRoles Management Shell

Now you can search for the modules you want to install.

Powershell – Modules

Powershell is great. but if you really want to do something with an app other than base active directory… you need something more. People write modules to add functionality to Powershell. You can install these and then load them in your code.

Modules are loaded with “Import-Module”

Examples:

Import-Module SMlets

Import-Module ActiveDirectory

Import-Module SQLServer


https://www.powershellgallery.com/packages/SMLets/
https://www.powershellgallery.com/packages/SqlServer/

Note: The AD tools are incorporated in Server 2012 R2 and later.

Of course you are not limited to third party modules – you can also stick all your common functions that you write into a file and call it a PSM1 file. Load it when you need it so that all your scripts don’t need to contain the functions.

les – you can also stick all your common functions that you write into a file and call it a PSM1 file. Load it when you need it so that all your scripts don’t need to contain the functions.

For example, your ” lots of function script” could be saved as FunctionScript.psm1 and then loaded as needed:

Code:

Import-Module ./path/FunctionScript.psm1



A list of user info..

One of the things we commonly need is a list of user info. Putting that together in code is easy – but if we want a nice output to send to users? This does that.

$InputSAM = "SAMACCOUNTNAME"

############################
##
## Get user object
##
############################
$ObjUser = Get-ADUser -Identity $InputSAM -Properties *

############################
##
## Get user's manager Object
##
############################

$UserManager = $ObjUser.Manager
$ObjUserManager = Get-ADUser -Identity $UserManager -Properties OfficePhone,title

############################
##
## Zig the Zagged Data
##
############################

$DCS = Get-ADDomainController -Filter *
$NOW = Get-Date

#######################################
##
## HTML Stuff
##
######################################
$Goodgreen = "LimeGreen"
$name = $ObjUser.DisplayName

# TABLE

$tableHeader = "

"
$tableEnd = "
User Information for: " + $name + "

"
$line = "

"
$TableRow = "

"

# Cell

$CellStart = "

"
$defaultcolorCell = $TableBody + $CellStart + $Goodgreen + $cellMiddle1

### example
# $DistinguishedNameTitle = "Distinguished Name:"
# $DistinguishedNameColor = $Goodgreen
# $DistinguishedNamedata = $DistinguishedName
# $DistinguishedNameCells = $CellStart + $DistinguishedNameColor + $cellMiddle1 + $DistinguishedNameTitle + $Cellmiddle2 + $DistinguishedNamedata + $cellend

# $TableBody = $TableBody + $CellStart + $DistinguishedNameColor + $cellMiddle1 + $DistinguishedNameTitle + $Cellmiddle2 + $DistinguishedNamedata + $cellend

############################
##
## Data to return
##
############################

# start our Table body with a new line and a row

[string]$TableBody = $line + $TableRow

##################################################
# Who info

$name = $ObjUser.DisplayName
$nametitle = "Display Name: "
$namedata = $ObjUser.DisplayName
$TableBody = $TableBody + $defaultcolorCell + $NameTitle + $Cellmiddle2 + $Namedata + $cellend

$UserSAM = $objuser.SamAccountName
$UserSAMtitle = "Login: "
$UserSAMdata = $UserSAM
$TableBody = $TableBody + $defaultcolorCell + $UserSAMtitle + $Cellmiddle2 + $UserSAMdata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$title = $objuser.Title
$titletitle = "Title: "
$titledata = $title
$TableBody = $TableBody + $defaultcolorCell + $titletitle + $Cellmiddle2 + $titledata + $cellend

$Description = $ObjUser.Description
$Descriptiontitle = "Prefered Title: "
$Descriptiondata = $Description
$TableBody = $TableBody + $defaultcolorCell + $Descriptiontitle + $Cellmiddle2 + $Descriptiondata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$employeedepartment = $ObjUser.Department
$employeedepartmenttitle = "Department: "
$employeedepartmentdata = $employeedepartment
$TableBody = $TableBody + $defaultcolorCell + $employeedepartmenttitle + $Cellmiddle2 + $employeedepartmentdata + $cellend

$Company = $ObjUser.Company
$Companytitle = "Company: "
$Companydata = $Company
$TableBody = $TableBody + $defaultcolorCell + $Companytitle + $Cellmiddle2 + $Companydata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$DistinguishedName = $ObjUser.DistinguishedName
$DistinguishedNameTitle = "Distinguished Name: "
$DistinguishedNamedata = $ObjUser.DistinguishedName
$TableBody = $TableBody + $defaultcolorCell + $DistinguishedNameTitle + $Cellmiddle2 + $DistinguishedNamedata + $cellend

##################################################
# Employee Details

#new Line
$TableBody = $TableBody + $line

#Section header
$TableBody = $TableBody + "

"

#new Line
$TableBody = $TableBody + $line

#new Row
$TableBody = $TableBody + $TableRow

$officephone = $objuser.OfficePhone
$officephonetitle = "Office Phone: "
$officephonedata = $officephone
$TableBody = $TableBody + $defaultcolorCell + $officephonetitle + $Cellmiddle2 + $officephonedata + $cellend

$homephone = $ObjUser.HomePhone
$homephonetitle = "Home or Cell: "
$homephonedata = $homephone
$TableBody = $TableBody + $defaultcolorCell + $homephonetitle + $Cellmiddle2 + $homephonedata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$employeeID = $objuser.EmployeeID
$employeeIDtitle = "Employee ID: "
$employeeIDdata = $employeeID
$TableBody = $TableBody + $defaultcolorCell + $employeeIDtitle + $Cellmiddle2 + $employeeIDdata + $cellend

$employeetype = $ObjUser.employeeType
$employeetypetitle = "Account Type: "
$employeetypedata = $employeetype
$TableBody = $TableBody + $defaultcolorCell + $employeetypetitle + $Cellmiddle2 + $employeetypedata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$location = $ObjUser.Office
$locationtitle = "Office: "
$locationdata = $location
$TableBody = $TableBody + $defaultcolorCell + $locationtitle + $Cellmiddle2 + $locationdata + $cellend

$email = $ObjUser.EmailAddress
$emailtitle = "Email: "
$emaildata = $email
$TableBody = $TableBody + $defaultcolorCell + $emailtitle + $Cellmiddle2 + $emaildata + $cellend

###########################################
###
### We need to pause and Get the multi DC stuff
###
##############################################

$LastLogintime = 0
$DefenderLastLogintime = 0
$DCLastFailedLogintime = 0
$BadLogins = 0
$accountchangedtime = 0

foreach($dc in $dcs)
{
$hostname = $dc.HostName
$LocalDCuser = Get-ADUser $UserSAM -Server $hostname | Get-ADObject -Properties *

if($LocalDCuser.'defender-lastLogon' -gt $DefenderLastLogintime)
{
$DefenderLastLogintime = $LocalDCuser.'defender-lastLogon'
}
if($LocalDCuser.LastLogon -gt $LastLogintime)
{
$LastLogintime = $LocalDCuser.LastLogon
}
if($LocalDCuser.BadPasswordTime -gt $DCLastFailedLogintime)
{
$DCLastFailedLogintime = $LocalDCuser.BadPasswordTime
}

if($LocalDCuser.whenChanged -gt $accountchangedtime)
{
$accountchangedtime = $LocalDCuser.whenChanged
}

if($LocalDCuser.BadLogonCount -gt $BadLogins)
{
[string]$BadLogins = $LocalDCuser.BadLogonCount
}
}
$LastSuccessfulLogin = [DateTime]::FromFileTime($LastLogintime)
$DefenderLastSuccessfulLogin = [DateTime]::FromFileTime($DefenderLastLogintime)
$lastfailedlogin = [DateTime]::FromFileTime($DCLastFailedLogintime)
$Acctchanged = $accountchangedtime

# Echo $username
# Echo "last logged on at: " $LastSuccessfulLogin
# Echo "last logged on with Defender token at: " $DefenderLastSuccessfulLogin
# Echo "last FAILED log on at: " $lastfailedlogin
# Echo "Recent Bad Logins: " $BadLogins
#

###################################################
# Oddball Account Properties
#new Line
$TableBody = $TableBody + $line

#new Row
$TableBody = $TableBody + $TableRow

$AcctCreated = $ObjUser.whenCreated
$AcctCreatedtitle = "Account Creation Date: "
$AcctCreateddata = $ObjUser.whenCreated
$TableBody = $TableBody + $defaultcolorCell + $AcctCreatedtitle + $Cellmiddle2 + $AcctCreateddata + $cellend

$Acctchangedtitle = "Account Last Changed: "
$Acctchangeddata = $Acctchanged
$TableBody = $TableBody + $defaultcolorCell + $Acctchangedtitle + $Cellmiddle2 + $Acctchangeddata + $cellend

###################################################
# Login times and Status

#new Line
$TableBody = $TableBody + $line

#Section header
$TableBody = $TableBody + "

"

#new Line
$TableBody = $TableBody + $line

#new Row
$TableBody = $TableBody + $TableRow

$LastSuccessfulLogintitle = "Last Successful Login: "
$LastSuccessfulLogindata = $LastSuccessfulLogin
$TableBody = $TableBody + $defaultcolorCell + $LastSuccessfulLogintitle + $Cellmiddle2 + $LastSuccessfulLogindata + $cellend

$DefenderLastSuccessfulLogintitle = "Last Defender Token Login: "
$DefenderLastSuccessfulLogindata = $DefenderLastSuccessfulLogin
$TableBody = $TableBody + $defaultcolorCell + $DefenderLastSuccessfulLogintitle + $Cellmiddle2 + $DefenderLastSuccessfulLogindata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$lastfailedlogintitle = "Last Failed Login: "
$lastfailedlogindata = $lastfailedlogin
$TableBody = $TableBody + $defaultcolorCell + $lastfailedlogintitle + $Cellmiddle2 + $lastfailedlogindata + $cellend

################################################################
## account status

#new Line
$TableBody = $TableBody + $line

#Section header
$TableBody = $TableBody + "

"

#new Line
$TableBody = $TableBody + $line

#new Row
$TableBody = $TableBody + $TableRow

########## Account locked processing
$AcctLocked = $ObjUser.LockedOut
switch($AcctLocked)
{
True
{
$AccountLockedColor = "Red"
}
False
{
$AccountLockedColor = "LimeGreen"
}
}

$AcctLockedtitle = "Account Locked: "
$AcctLockeddata = $AcctLocked
$TableBody = $TableBody + $CellStart + $AccountLockedColor + $cellMiddle1 + $AcctLockedtitle + $Cellmiddle2 + $AcctLockeddata + $cellend

######### account control processing

$AccountControl = $ObjUser.userAccountControl
switch($AccountControl)
{
512
{
$accountDisabled = "False"
$accountDisabledColor = "LimeGreen"
$passwordexpires = "True"
$passwordexpirescolor = "LimeGreen"
}
514
{
$accountDisabled = "True"
$accountDisabledColor = "Red"
$passwordexpires = "True"
$passwordexpirescolor = "LimeGreen"
}
66048
{
$accountDisabled = "False"
$accountDisabledColor = "LimeGreen"
$passwordexpires = "false"
$passwordexpirescolor = "DarkOrange"
}
66050
{
$accountDisabled = "True"
$accountDisabledColor = "Red"
$passwordexpires = "false"
$passwordexpirescolor = "DarkOrange"
}
}

$accountDisabledtitle = "Account Disabled: "
$accountDisableddata = $accountDisabled
$TableBody = $TableBody + $CellStart + $accountDisabledColor + $cellMiddle1 + $accountDisabledtitle + $Cellmiddle2 + $accountDisableddata + $cellend

################################################################
## password status

#new Line
$TableBody = $TableBody + $line

#Section header
$TableBody = $TableBody + "

"

#new Line
$TableBody = $TableBody + $line

#new Row
$TableBody = $TableBody + $TableRow

$pwdlastChanged = $ObjUser.PasswordLastSet
$pwdlastChangedtitle = "Password Last Set: "
$pwdlastChangeddata = $pwdlastChanged
$TableBody = $TableBody + $defaultcolorCell + $pwdlastChangedtitle + $Cellmiddle2 + $pwdlastChangeddata + $cellend

########## password age calculation
$PwdAge = ($NOW - $pwdlastChanged).days

switch($PwdAge)
{
{$_ -ge 0 -and $_ -le 45}
{
$PwdAgeColor = "LimeGreen"
}
{$_ -ge 46 -and $_ -le 55}
{
$PwdAgeColor = "Yellow"
}
{$_ -ge 56 -and $_ -le 60}
{
$PwdAgeColor = "DarkOrange"
}
{$_ -ge 61}
{
$PwdAgeColor = "Red"
}
}

$PwdAgetitle = "Password Age: "
$PwdAgedata = $PwdAge
$TableBody = $TableBody + $CellStart + $PwdAgeColor + $cellMiddle1 + $PwdAgetitle + $Cellmiddle2 + $PwdAgedata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$passwordexpirestitle = "Password Expires Policy: "
$passwordexpiresdata = $passwordexpires
$TableBody = $TableBody + $CellStart + $passwordexpiresColor + $cellMiddle1 + $passwordexpirestitle + $Cellmiddle2 + $passwordexpiresdata + $cellend

$PwdExpired = $ObjUser.PasswordExpired
switch($PwdExpired)
{
False
{
$pwdExpiredColor = "LimeGreen"
}
True
{
$pwdExpiredColor = "Red"
}
}

$PwdExpiredtitle = "Password Expired?: "
$PwdExpireddata = $PwdExpired
$TableBody = $TableBody + $CellStart + $PwdExpiredColor + $cellMiddle1 + $PwdExpiredtitle + $Cellmiddle2 + $PwdExpireddata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$UserchangePwd = $ObjUser.CannotChangePassword

switch($UserchangePwd)
{
False
{
$UserChangepwdColor = "LimeGreen"
$UserchangePwdStatus = "Yes"
}
True
{
$UserChangepwdColor = "Yellow"
$UserchangePwdStatus = "No"
}
}

$UserchangePwdtitle = "User can change password?: "
$UserchangePwddata = $UserchangePwdStatus
$TableBody = $TableBody + $CellStart + $UserchangePwdColor + $cellMiddle1 + $UserchangePwdtitle + $Cellmiddle2 + $UserchangePwddata + $cellend

# Domain Password Policy stuff
$ADDomainPasswordPolicy = Get-ADDefaultDomainPasswordPolicy

#new Row
$TableBody = $TableBody + $TableRow

[string]$maxattempts = $ADDomainPasswordPolicy.LockoutThreshold
[string]$Remainingattempts = $maxattempts - $BadLogins

$maxattemptstitle = "Max/Remaining Password Attempts: "
[string]$maxattemptsdata = $maxattempts + " / " + $Remainingattempts
$TableBody = $TableBody + $defaultcolorCell + $maxattemptstitle + $Cellmiddle2 + $maxattemptsdata + $cellend

########## calculate account unlock policy
$LockoutDuration = $ADDomainPasswordPolicy.LockoutDuration
if ($LockoutDuration -le 0)
{
$Autounlock = "Manual Unlock Only"
}
if ($LockoutDuration -gt 0)
{
$Autounlock = "[Days:Hours:Minutes] " + $LockoutDuration
}

$Autounlocktitle = "Auto Unlock Duration: "
$Autounlockdata = $Autounlock
$TableBody = $TableBody + $defaultcolorCell + $Autounlocktitle + $Cellmiddle2 + $Autounlockdata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$MinPwdlength = $ADDomainPasswordPolicy.MinPasswordLength
$MinPwdlengthtitle = "Minimum Password Length: "
$MinPwdlengthdata = $MinPwdlength
$TableBody = $TableBody + $defaultcolorCell + $MinPwdlengthtitle + $Cellmiddle2 + $MinPwdlengthdata + $cellend

$MinPwdHistory = $ADDomainPasswordPolicy.PasswordHistoryCount
$MinPwdHistorytitle = "Minimum Password History: "
$MinPwdHistorydata = $MinPwdHistory
$TableBody = $TableBody + $defaultcolorCell + $MinPwdHistorytitle + $Cellmiddle2 + $MinPwdHistorydata + $cellend

################################################################
## Profile Information

#new Line
$TableBody = $TableBody + $line

#Section header
$TableBody = $TableBody + "

"

#new Line
$TableBody = $TableBody + $line

#new Row
$TableBody = $TableBody + $TableRow

$Script = $ObjUser.ScriptPath
$Scripttitle = "Login Script: "
$Scriptdata = $Script
$TableBody = $TableBody + $defaultcolorCell + $Scripttitle + $Cellmiddle2 + $Scriptdata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$homeLocation = $ObjUser.l
$HomeDirectory = "\\microsoft.com\user\" + $homeLocation + "\" + $UserSAM + "\"
$HomeDirectorytitle = "Home Drive: "
$HomeDirectorydata = $HomeDirectory
$TableBody = $TableBody + $defaultcolorCell + $HomeDirectorytitle + $Cellmiddle2 + $HomeDirectorydata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$CitrixProfile = "\\micosoft.com\citrix\Profiles\TS\" + $UserSAM +"
" + "\\microsoft.com\citrix\Profiles\TS-x64\" + $UserSAM
$CitrixProfiletitle = "Citrix Profiles: "
$CitrixProfiledata = $CitrixProfile
$TableBody = $TableBody + $defaultcolorCell + $CitrixProfiletitle + $Cellmiddle2 + $CitrixProfiledata + $cellend

################################################################
## Exchange information

#new Line
$TableBody = $TableBody + $line

#Section header
$TableBody = $TableBody + "

"

#new Line
$TableBody = $TableBody + $line

#new Row
$TableBody = $TableBody + $TableRow

$ExchangeAccount = $ObjUser.msExchWhenMailboxCreated
$ExchangeAccounttitle = "Mailbox Created: "
$ExchangeAccountdata = $ExchangeAccount
$TableBody = $TableBody + $defaultcolorCell + $ExchangeAccounttitle + $Cellmiddle2 + $ExchangeAccountdata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$proxyaddresses = $ObjUser.proxyAddresses

Foreach ($mailitem in $proxyaddresses)
{
$mailitemlist = $mailitemlist + "
" + $mailitem
}

$proxyaddressestitle = "Messaging Addresses: "
$proxyaddressesdata = $mailitemlist
$TableBody = $TableBody + $defaultcolorCell + $proxyaddressestitle + $Cellmiddle2 + $proxyaddressesdata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$AssignedDelegates = $ObjUser.publicDelegatesBL

Foreach ($mailbox in $AssignedDelegates)
{
$objmailbox = Get-ADUser -Identity $mailbox
$mailboxname = $objmailbox.name
$Publicmailbox = $publicmailbox + "
" + $mailboxname
}

$AssignedDelegatestitle = "Assigned Delegates: "
$AssignedDelegatesdata = $Publicmailbox
$TableBody = $TableBody + $defaultcolorCell + $AssignedDelegatestitle + $Cellmiddle2 + $AssignedDelegatesdata + $cellend

$mailboxmanager = $ObjUser.msExchDelegateListBL

Foreach ($mailbox in $mailboxmanager)
{
$objmailbox = Get-ADUser -Identity $mailbox
$mailboxname = $objmailbox.name
$mailboxlist = $mailboxlist + "
" + $mailboxname
}

$mailboxmanagertitle = "Delegate Access: "
$mailboxmanagerdata = $mailboxlist
$TableBody = $TableBody + $defaultcolorCell + $mailboxmanagertitle + $Cellmiddle2 + $mailboxmanagerdata + $cellend

############################
##
## Managers Data to return
##
############################

################################################################
## Manager information

#new Line
$TableBody = $TableBody + $line

#Section header
$TableBody = $TableBody + "

"

#new Line
$TableBody = $TableBody + $line

#new Row
$TableBody = $TableBody + $TableRow

$manager = $ObjUserManager.Name
$managertitle = "Manager Name: "
$managerdata = $manager
$TableBody = $TableBody + $defaultcolorCell + $managertitle + $Cellmiddle2 + $managerdata + $cellend

#new Row
$TableBody = $TableBody + $TableRow

$managertitle = $ObjUserManager.title
$managertitletitle = "Manager Title: "
$managertitledata = $managertitle
$TableBody = $TableBody + $defaultcolorCell + $managertitletitle + $Cellmiddle2 + $managertitledata + $cellend

$managerphone = $ObjUserManager.OfficePhone
$managerphonetitle = "Manager Office Phone: "
$managerphonedata = $managerphone
$TableBody = $TableBody + $defaultcolorCell + $managerphonetitle + $Cellmiddle2 + $managerphonedata + $cellend

###################################
##
## Message
##
#############################################################################

$Message = $Message + $tableHeader + $Tablebody + $tableend

This gives us pretty output we can send to users. I hope it helps.


"
$Cellmiddle2 = "
"
$cellend = "
EMPLOYEE DETAILS
LOGIN DATES
ACCOUNT STATUS
PASSWORD INFORMATION
PROFILE INFORMATION
EXCHANGE INFORMATION
LINE MANAGER