0% found this document useful (0 votes)
17 views13 pages

Most Used Powershell Command

The document outlines essential PowerShell scripts and cmdlets for system administration tasks, highlighting automation techniques for user management, software installation, and system monitoring. It includes detailed examples of scripts for bulk user creation, password resets, service health checks, and disk space monitoring. The report emphasizes PowerShell's role in reducing manual labor and minimizing errors in administrative processes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views13 pages

Most Used Powershell Command

The document outlines essential PowerShell scripts and cmdlets for system administration tasks, highlighting automation techniques for user management, software installation, and system monitoring. It includes detailed examples of scripts for bulk user creation, password resets, service health checks, and disk space monitoring. The report emphasizes PowerShell's role in reducing manual labor and minimizing errors in administrative processes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Automatization with PowerShell

My Most Used PowerShell Scripts & Cmdlets for System Administration


By Avinash Raj

Automatization with PowerShell................................................................................................ 1


My Most Used PowerShell Commands and Scripts for System Administrator Tasks..........1
Introduction............................................................................................................................2
My most used PowerShell Scripts for System Administration......................................... 2
Before proceed.................................................................................................................. 2
My most used Scripts.........................................................................................................2
● Bulk to monitor the disk space and alert if disk usage exceeds the 85%................. 2
● Software installation in multiple machines................................................................ 3
● Network Connectivity Report.................................................................................... 3
● Testing multiple domain Connection:........................................................................ 4
● Bulk Automate the creation of users using a text file................................................4
● Bulk Automate the creation of users using a csv file................................................ 5
● Bulk automate the password reset for a list of users using a CSV file..................... 5
● Service Health Check and Auto-Restart................................................................... 6
● Inventory Installed Software..................................................................................... 6
● Bulk to remove disabled accounts............................................................................ 7
My most used PowerShell Cmdlets..................................................................................... 7
● Get information about users..................................................................................... 7
● Adding a new user (enabled by default)................................................................... 7
● Changing the user's password without needing the old one.....................................8
● Updating an user’s department and info, then sending them an email notice.......... 8
● Remove an User....................................................................................................... 8
● Creating a new group............................................................................................... 8
● Adding new users to a group.................................................................................... 8
● Creating a computer account when adding a new computer to the network............ 9
● Creating a new organizational unit........................................................................... 9
● Create Active Directory Objects................................................................................9
Cmdlets For Active Directory Users Management............................................................. 9
Cmdlets For Active Directory Group Management.......................................................... 10
Cmdlets for Computer management in Active directory................................................. 10
Top Useful Cmdlets in PowerShell Scripting.................................................................... 11
Introduction
With its robust command-line shell and scripting environment based on the.NET framework,
PowerShell has emerged as a crucial tool for contemporary system administrators.
Administrators can automate complicated tasks, enforce configuration standards, and manage
infrastructure at scale thanks to its extensive set of cmdlets, object-oriented output model, and
close integration with Windows—and now Linux and macOS.

Beyond basic task automation, PowerShell's scripting features minimize human error and
manual labor by enabling modular code, error handling, and reusable functions. In this report, I
present to you my Top 10 powershell commands/scripts that I have used and developed in my
career.

My most used PowerShell Scripts for System Administration

Before proceed
The structure of a script depends on its intended purpose. Scripts execute in a top-down order,
so lines at the beginning run before those that follow. First, prepare all objects, data, and
variables for processing; then build the script’s logic.

For example, suppose you have a list of names you want to add to a group. The most
convenient approach is to store those names in a text file and then use the Get-Content cmdlet
to read them into a variable: “$names = Get-Content .\name_list.txt”

My most used Scripts

●​ Bulk to monitor the disk space and alert if disk usage exceeds the 85%
This script uses a list of hosts (servers) and declares a threshold to iterate over the host’s list
and check each disk. The “Where-object” cmdlet receives the Get-WmiObject output and if the
free volume is less than 100 - threshold (15%) it pipes it to the Select-Object to prepare the
object using calculated fields, and rounded values. All this is allocated in the “alerts” variable.
The second part is the condition, if the alert object contains data: write the alert to a .csv file,
then send an email to the sysadmin.

$servers = '<server1>','<server2>','<server3>,...'
$threshold = 85

$alerts = foreach ($s in $servers) {


Get-WmiObject Win32_LogicalDisk -ComputerName $s -Filter
"DriveType=3" |
Where-Object { ($_.FreeSpace/$_.Size)*100 -lt (100 -
$threshold) } |
Select-Object @{Name='Server';Expression={$s}},
DeviceID,
@{Name='PercentFree';Expression={[math]::Round(($_.FreeSpace/$_.Size)
*100,2)}}
}

if ($alerts) {
$alerts | Export-Csv C:\Reports\LowDiskSpace.csv
-NoTypeInformation
Send-MailMessage -To '[email protected]' `
-From '[email protected]' `
-Subject 'Disk Space Alert' `
-Attachments C:\Reports\LowDiskSpace.csv `
-SmtpServer 'smtp.contoso.com'
}

●​ Scheduled Backup
The variable “source” stores the source path. “destination” allocates the designated name for
the backup object, it includes the datetime stamp as a name complement to avoid duplicated
names and maintain chronological order in the registry. Once the source and destination name
are set, it’s time to do the actual backup: the “Copy-Item” cmdlet copies the files and paste it in
the designated location. The “-Recurse” is the parameter that specifies that the copy is
recursively over the content.

$source = "C:\ImportantData"
$destination = "D:\Backups\$(Get-Date -Format 'yyyyMMdd_HHmmss')"

Copy-Item -Path $source -Destination $destination -Recurse

●​ Software installation in multiple computers


This script reads a .txt file with the list of computernames to install the software in. the software
to be installed must be in .msi format.

$computers = Get-Content .\ComputerList.txt

foreach ($c in $computers) {


Invoke-Command -ComputerName $c -ScriptBlock {
Start-Process "msiexec.exe" -ArgumentList "/i
\\server\share\app.msi /quiet /norestart" -Wait }
}

●​ Network Connectivity Report


Test TCP port connectivity ( in this case RDP/3389) against a host list (hosts) and log the
results.

$hosts = @('<hostIP1>','<hostIP2>','<server.domainname.com>')
$results = foreach ($h in $hosts) {
$test = Test-NetConnection -ComputerName $h -Port 3389
-WarningAction SilentlyContinue
[PSCustomObject]@{
Host = $h
Reachable = $test.TcpTestSucceeded
RoundTrip = $test.PingReplyDetails.RoundTripTime
}
}
$results | Format-Table -AutoSize
$results | Export-Csv C:\Reports\RDPConnectivity.csv
-NoTypeInformation

●​ Testing multiple domain Connection:


Before running this command, we need to create a text file that contains the list of domains to
test. Each domain needs to be separated by a jumpline and must be written exactly as is it.

$domains = Get-Content -Path C:\path\domains.txt


$domains | ForEach-object {
Write-Host "Testing Host: $($_)"
Test-NetConnection -ComputerName $_ -Port XX
Write-Host ""
}

●​ Bulk Automate the creation of users using a text file.


This script automates the creation of users by parsing a text file containing the list of user
names to create an account for each. This uses the cmdlet Get-Content to get the content and
process the lines and names in a “foreach” loop. The Script also checks if there already exists
an user with the username and let the admin know by displaying it on the powershell terminal

$users = Get-Content .\names.txt


$passwordString = "Initial12345#"
$password = ConvertTo-SecureString $passwordString -AsPlainText
-Force

# New-ADOrganizationalUnit -Name _USERS


-ProtectedFromAccidentalDeletion $false

foreach ($i in $users) {


$firstname = $i.Split(" ")[0].ToLower()
$lastname = $i.Split(" ")[1].ToLower()
$username =
"$($firstname.Substring(0,1))$($lastname)".ToLower()

# Check if the username already exists


$existingUser = Get-ADUser -Filter "SamAccountName -eq
'$username'" -ErrorAction SilentlyContinue
if (-not $existingUser) {
New-ADUser -AccountPassword $password `
-GivenName $firstname `
-Surname $lastname `
-DisplayName $username `
-Name $username `
-EmployeeID $username `
-PasswordNeverExpires $true `
-Path "ou=_USERS,$(([ADSI]`“”).distinguishedName)"
`
-Enabled $true

Write-Host "Created user: $username" -BackgroundColor


Green -ForegroundColor White
}
else {
Write-Host "User already exists: $username"
-BackgroundColor DarkRed -ForegroundColor White
}
}

●​ Bulk Automate the creation of users using a csv file

must have the following columns


GivenName,Surname,SamAccountName,UPN,Department,OU

Import-Module ActiveDirectory

# CSV columns: GivenName,Surname,SamAccountName,UPN,Department,OU


$users = Import-Csv C:\Scripts\NewUsers.csv
foreach ($u in $users) {
$pwd = ConvertTo-SecureString 'P@ssw0rd123!' -AsPlainText -Force
New-ADUser `
-Name "$($u.GivenName) $($u.Surname)" `
-GivenName $u.GivenName `
-Surname $u.Surname `
-SamAccountName $u.SamAccountName `
-UserPrincipalName $u.UPN `
-Department $u.Department `
-AccountPassword $pwd `
-Enabled $true `
-ChangePasswordAtLogon $true `
-Path $u.OU
}
●​ Bulk automate the password reset for a list of users using a CSV file
This script receives a .csv file containing the names of the users that request a password
change. Once parched, it iterates and updates the passwords of each. Once the password is
changed, the script sends an email letting the user know that the password has being changed.
The csv file must have the following columns SamAccountName,NewPassword,Email

Import-Module ActiveDirectory

$records = Import-Csv C:\Scripts\ResetPasswords.csv


foreach ($r in $records) {
$securePwd = ConvertTo-SecureString $r.NewPassword -AsPlainText
-Force
Set-ADAccountPassword -Identity $r.SamAccountName `
-NewPassword $securePwd -Reset
Unlock-ADAccount -Identity $r.SamAccountName

Send-MailMessage `
-To $r.Email `
-From '[email protected]' `
-Subject 'Your password has been reset' `
-Body "Your new password is: $($r.NewPassword)" `
-SmtpServer 'smtp.contoso.com'
}

●​ Service Health Check and Auto-Restart


This script uses a list of hostnames (servers) and services (services) offered by those hosts and
iterates over them to check if it is running, in case of not running, it restarts it and logs the
action.

$servers = '<host1>','<host1>’,'<host1>’
$services = 'W3SVC','MSSQLSERVER','WinRM'

foreach ($s in $servers) {


Invoke-Command -ComputerName $s -ScriptBlock {
param($svcList)
foreach ($svc in $svcList) {
$status = Get-Service -Name $svc
if ($status.Status -ne 'Running') {
Restart-Service -Name $svc -Force
"$($env:COMPUTERNAME): Restarted $svc" | Out-File
C:\Logs\ServiceRestarts.log -Append
}
}
} -ArgumentList ($services)
}
●​ Inventory Installed Software
Collect a list of installed applications from a fleet of servers and output to CSV.

$servers = Get-Content C:\Scripts\ServerList.txt


$results = foreach ($s in $servers) {
Get-ItemProperty
"HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" `
-ErrorAction SilentlyContinue |
Where-Object DisplayName |
Select-Object @{Name='Server';Expression={$s}},
DisplayName, DisplayVersion, Publisher,
InstallDate
}

$results | Export-Csv C:\Reports\InstalledSoftware.csv


-NoTypeInformation

●​ Bulk to remove disabled accounts


Find and remove AD accounts disabled for over 90 days. Exports a report before deletion.

Import-Module ActiveDirectory

$stale = Get-ADUser -Filter "Enabled -eq `$false -and LastLogonDate


-lt (Get-Date).AddDays(-90)" `
-Properties LastLogonDate

$stale | Select-Object Name,SamAccountName,LastLogonDate |


Export-Csv C:\Reports\StaleDisabledAccounts.csv -NoTypeInformation

$stale | Remove-ADUser -Confirm:$false

My most used PowerShell Cmdlets


●​ Get information about users
Get-ADUser -Identity <username> -Properties
<Property1>,<Property2>,...
With this simple command, powershell will return the user’s information related to the specified
properties.

●​ Adding a new user (enabled by default)


$securePwd = Read-Host <initial password> –AsSecureString

# Create and enable the user in one shot


New-ADUser `
-Name "<username>" `
-GivenName "<name>" `
-Surname "<last name>" `
-Department "<department" `
-AccountPassword $securePwd `
-Enabled $true `
-ChangePasswordAtLogon $true `
-Path "OU=<organizational unit>,DC=<AD domain name>,DC=<domain
extension>"

●​ Changing the user's password without needing the old one.


This has to be one of the most recurrent issues with users. In my experience, users that come
back from vacations need to reset their passwords 98% of the time.
# Secure the new password
$newPwd = ConvertTo-SecureString '<newPassword>' -AsPlainText -Force

# Reset password without needing the old one


Set-ADAccountPassword -Identity '<username>' `
-NewPassword $newPwd `
-Reset

#Unlock the account


Unlock-ADAccount -Identity '<username>'

●​ Updating an user’s department and info, then sending them an email notice.
Set-ADUser’
-Identity <username>’
-Department “<new-department>” ’
-Title “<new-title>”

Send-MailMessage ‘
-To <emailname[@]domain.com> ‘
-Subject “Profile Updated” ‘
-Body “Congratulations for your promotion” ‘
-SmtpServer <smtp.domainname.com>

●​ Remove an User
The fastest and common way to do this is:
Remove-ADUser -Identity <username> -Confirm

●​ Creating a new group


New-ADGroup’
-Name <groupName>’
-GroupScope <Global, DomainLocal, or Universal>’
-ManagedBy <managerName>’

●​ Adding new users to a group


Add-ADGroupMember -Identity "<groupname" `
-Members <name1>, <name2>, <name3>

●​ Creating a computer account when adding a new computer to the network


New-ADComputer’
-Name <COMPUTER-NAME>’
-Path "ou=department,dc=domainname,dc=com"’
-Enabled $true

●​ Creating a new organizational unit


New-ADOrganizationalUnit’
-Name <Name>
-Path’ "ou=department,dc=domainname,dc=com"’
-ProtectedFromAccidentalDeletion $true

●​ Create Active Directory Objects


Object creation is implemented when needed to create entities that are not managed through
specific Cmdlets. Some object examples are: Contacts, Configuration partitions, DNS partitions,
etc.
New-ADObject -Name "<objectname" -Type contact

Cmdlets For Active Directory Users Management

Cmdlet Description

New-ADUser Creates a user account

Get-ADUser Retrieves a user account

Set-ADUser Modifies properties of a user account

Remove-ADUser Deletes a user account


Set-ADAccountPassword Resets the password of a user account

Unlock-ADAccount Unlocks a user account that's been locked


after exceeding the permitted number of
incorrect sign-in attempts

Enable-ADAccount Enables a user account

Disable-ADAccount Disables a user account

Cmdlets For Active Directory Group Management

Cmdlet Description

New-ADGroup Creates a new group

Set-ADGroup Modifies properties of a group

Get-ADGroup Displays properties of a group

Remove-ADGroup Deletes a group

Add-ADGroupMember Adds members to a group

Get-ADGroupMember Displays members of a group

Remove-ADGroupMember Removes members from a group

Add-ADPrincipalGroupMembership Adds group membership to an object

Get-ADPrincipalGroupMembership Displays group membership of an object

Remove-ADPrincipalGroupMembership Removes group membership from an object

Cmdlets for Computer management in Active directory

Cmdlet Description
New-ADComputer Creates a new computer account

Set-ADComputer

Get-ADComputer Displays properties of a computer account

Remove-ADComputer Deletes a computer account

Test-ComputerSecureChannel Verifies or repairs the trust relationship


between a computer and the domain

Reset-ComputerMachinePassword Resets the password for a computer account

Top Useful Cmdlets in PowerShell Scripting

Cmdlet Description Example

Get-Content Opens a File and access to $variable = Get-Content


its content text_file.txt

ForEach-Object Iterates over a collection of a $iterable_variable |


objects ForEach-Object { do
something
}

Out-File Sends the string to an “Some string” | Out-File


specific file filename.txt

Test-NetConnection Tests connectivity to a remote Test-NetConnection


host/port and returns network -ComputerName
diagnostics such as ping, www.domain.com
traceroute, and TCP port
status.

ConvertTo-Json When piped after an object, it $object | ConvertTo-Json


registers each object’s
property separately in Json
format.

Get-Date Returns the date object $(Get-Date)

Start-Sleep Used for flow control. It stops …Some code…


or starts the execution of Start-Sleep -Seconds 5
commands in a script …Continue code…

Write-Host Allows to format the output. Write-Host -BackgroundColor


Blue -ForegroundColor Red
“string”

Get-Command Helps to find the name of a Get-Command *file*


cmdlet using regular
expressions or strings

Get-Help Return the manual Get-Help CmdLet -online


instructions for cmdlets

You might also like