EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial Useful PowerShell Scripts
Secondary Sidebar
PowerShell Tutorial
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Useful PowerShell Scripts

By Priya PedamkarPriya Pedamkar

Useful PowerShell Scripts

Introduction to PowerShell Scripts

In this article, we will learn about Useful PowerShell Scripts. For any user or administrator, there are certain tasks that need to be performed daily. There are also tasks that are simpler to do and can be done without human intervention. To save time for the users, the tasks can be automated with the help of PowerShell scripts. The tasks can be anything from downloading a file from a location, fetching the details of a computer, deleting files that are older than a certain day, rebooting a system at an hour. Once the script is ready, it can be run manually or even can be run using a task scheduler.

For example: To free up space in a drive, we can write a PowerShell script to delete files that are older than 90 days and schedule a task that will run daily at a time so that an adequate amount of space on the driver is maintained.

Examples of Useful PowerShell Scripts

Below we explain examples of how PowerShell Scripts are used:

Script to Fetch Information Related to System

The following script is used to fetch important and basic information related to systems such as the model of the system, the available disk space, the BIOS information, processors configuration, memory details, Operating System details, the list of users and owners of the system, current user session and the status of the various running processes and various hotfixes that are installed.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Example #1

Code:

Write-Host "Welcome to the script of fetching computer Information"
Write-host "The BIOS Details are as follows"
Get-CimInstance -ClassName Win32_BIOS

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,650 ratings)

Output:

Useful PowerShell Scripts - 1

Example #2

Code:

Write-Host "The systems processor is"
Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object -Property SystemType

Output:

Useful PowerShell Scripts - 2

Example #3

Code:

Write-Host "The computer Manufacture and physical memory details are as follows"
Get-CimInstance -ClassName Win32_ComputerSystem

Output:

Useful PowerShell Scripts - 3

Example #4

Code:

Write-Host "The installed hotfixes are"
Get-CimInstance -ClassName Win32_QuickFixEngineering

Output:

Useful PowerShell Scripts - 4

Example #5

Code:

Write-Host "The OS details are below"
Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -Property Build*,OSType,ServicePack*

Output:

Useful PowerShell Scripts - 5

Example #6

Code:

Write-Host "The following are the users and the owners"
Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -Property *user*

Output:

Useful PowerShell Scripts - 6

Example #7

Code:

Write-Host "The disk space details are as follows"
Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3" |Measure-Object -Property FreeSpace,Size -Sum |Select-Object -Property Property,Sum

Output:

The disk space details are as follows

Example #8

Code:

Write-Host "Current user logged in to the system"
Get-CimInstance -ClassName Win32_ComputerSystem -Property UserName

Output:

Current user logged in to the system

Example #9

Code:

Write-Host "Status of the running services are as follows"
Get-CimInstance -ClassName Win32_Service | Format-Table -Property Status,Name,DisplayName -AutoSize -Wrap

Output:

Status of the running services

Examples to Implement in PowerShell Scripts

The examples to be implemented in PowerShell Scripts are explained below:

Example #1: Adding Users to AD

The following script will add each user present in a CSV to the AD. The CSV will have all the user-related properties that need the script to create a user in AD. In case of an error, the script will log the error details in a text file. After successful creation, a message will appear in the console saying that the user has been created in Active Directory. The first line is used to import the csv document and loop through each record. The subsequent lines are used to assign the records values to the user’s attributes in the AD. The last line is used to add the user to an Active Directory group. The code is enclosed in a try-catch block to catch any exception if any error occurs it is printed on the console using the catch statement.

Code:

try
{
Import-Csv “C:\test\test.csv” | ForEach-Object {
$Name = $_.Name + “test.com”
New-ADUser `
-DisplayName $_.”Dname” `
-Name $_.”Name” `
-GivenName $_.”GName” `
-Surname $_.”Sname” `
-SamAccountName $_.”Name” `
-UserPrincipalName $UPName `
-Office $_.”off” `
-EmailAddress $_.”EAddress” `
-Description $_.”Desc” `
-AccountPassword (ConvertTo-SecureString “vig@123” -AsPlainText -force) `
-ChangePasswordAtLogon $true `
-Enabled $true `
Add-ADGroupMember “OrgUsers” $_.”Name”;
Write-Host "User created and added in the AD group"
}
}
catch
{
$msge=$_.Exception.Message
Write-Host "Exception is" $msge
}

Sample Input of the CSV file:

Name Dname GName Sname UPName off EAddress Desc
test1 test1 test1 test1 test1 test test@test.com test1
test2 test2 test2 test2 test2 test2 test2@test.com test2
test3 test3 test3 test3 test3 test3 test3@test.com test3
test4 test4 test4 test4 test4 test4 test4@test.com test4
test5 test5 test5 test5 test5 test5 test5@test.com test5

Example #2: Delete Files Older than 30 Days from A Path

The following script is used to delete files that are created 30 days or more from the current date. The path to be checked for files are mentioned in a csv. First, the csv file is imported. Then, for each path, the files that are older than 30 days are checked and deleted.

Code:

Write-Host "Welcome to the archive example"
$csv = Import-Csv "C:\Vignesh\test.csv"
foreach($row in $csv)
{
$Path=$row.Path
write-host "The path to be archived is" $row.Path
$DaysTOBeArchived = "-30"
$CurrentDate = Get-Date
$DatetoBeDeleted = $CurrentDate.AddDays($DaysTOBeArchived)
Get-ChildItem $Path -Recurse  | Where-Object { $_.CreationTime  -lt $DatetoBeDeleted } | Remove-Item
Write-Host "Cleared the files is the path "$row.path
}

Sample Input:

Path

C:\Vignesh\Test\Test1
C:\Vignesh\Test\Test2
C:\Vignesh\Test\Test3
C:\Vignesh\Test\Test1
C:\Vignesh\Test\Test4
C:\Vignesh\Test\Test5

Output:

30 Days from A Path

Example #3: Send an Email if The Disk Space Is Less than 5%

The following example will send an automated mail when the disk space is less than 5%.

Code:

$cname="Mycomputer"
ForEach ($c in $cname)
{
$disk=Get-WmiObject win32_logicaldisk -ComputerName $c -Filter "Drivetype=3" -ErrorAction SilentlyContinue | Where-Object {($_.freespace/$_.size) -le '0.05'}
If ($disk)
{
$EmailToAdd = "test@test.com"
$EmailFromAdd = "test@test.com"
$userdet = 'testuser'
$passworddet = "testpwd"
$Subjectdet = "Disk space alert"
$Bodydet = "low space in the system"
$SMTPServerdet = "testswer"
$SMTPMessagedet = New-Object System.Net.Mail.MailMessage($EmailFromAdd,$EmailToAdd,$Subjectdet,$Bodydet)
$SMTPClientdet = New-Object Net.Mail.SmtpClient($SMTPServerdet, 587)
$ SMTPClientdet.EnableSsl = $true
$ SMTPClientdet.Credentials = New-Object System.Net.NetworkCredential($userdet, $passworddet)
$ SMTPClientdet.Send($SMTPMessagedet)
}
}

Running a Script via Task Scheduler

The above script can be run daily without user intervention by creating a task. That task will run the script at a specified time daily. The advantage with this approach is that there can’t be the risk of missing the running of the script and it saves the users time. Following are the steps to run a ps script via task scheduler

  • Open task scheduler and create a task
  • In the trigger tab, set when this task needs to be run and the frequency of the job like whether it should be run daily or hourly and the time at which it needs to be run
  • In the action tab, specify the file location
  • Finally, click on OK.

Conclusion

Thus, the article covered various useful scripts that can be used to automate the tasks performed. The advantage of the scripts is that they reduce human effort and the need for monitoring. It also showed how a script can be run using a task scheduler. Scripts can also be used to send emails or alerts to the user whenever an issue occurs. To get expertise with scripts, it is advisable to write sample programs and practice them.

Recommended Articles

This is a guide to Useful PowerShell Scripts. Here we discuss various useful scripts, examples to implement with appropriate codes and outputs and using a task scheduler. You can also go through our other related articles to learn more –

  1. PowerShell Versions
  2. PowerShell Sort-Object
  3. Hashtable in PowerShell
  4. Variable in PowerShell
  5. Parameters of PowerShell ForEach Object
Popular Course in this category
All in One Data Science Bundle (360+ Courses, 50+ projects)
  360+ Online Courses |  1500+ Hours |  Verifiable Certificates |  Lifetime Access
4.7
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
Data Visualization Training (15 Courses, 5+ Projects)4.8
1 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more