SlideShare a Scribd company logo
Windows PowerShell Basics – Remove Item
i | P a g e
Table of Contents
Overview.......................................................................................................................................................1
Applies To..................................................................................................................................................1
Pre-Requisites ...........................................................................................................................................1
Current Execution Policy...........................................................................................................................1
PowerShell Script – Check and Delete File....................................................................................................2
Code Snippet – Check and Delete File ......................................................................................................2
PowerShell Output – Check and Delete File .........................................................................................3
Windows PowerShell Basics – Remove Item
1 | P a g e
Overview
In this guide we will demonstrate as to how to delete a file on a server after checking if the file exists with
Windows PowerShell script.
Applies To
Tested on Windows 10, Windows 2008 R2 and Windows 2012.
Pre-Requisites
Launch PowerShell Command Console or PowerShell ISE.
To run this script, Execution Policy should be set to either of these “AllSigned” or “RemoteSigned” or
“Unrestricted”, you can get current execution policy by running the command; “Get-ExecutionPolicy”.
Each Policy type and its purpose is shown in the below table.
Policy Type Purpose
Restricted No scripts can be run. Windows PowerShell can be used only in interactive mode.
AllSigned Only scripts signed by a trusted publisher can be run.
RemoteSigned Downloaded scripts must be signed by a trusted publisher before they can be run.
Unrestricted No restrictions; all Windows PowerShell scripts can be run.
Current Execution Policy
To know the current run the PowerShell cmdlet; Get-ExecutionPolicy
To list execution policies that can be configured run the PowerShell cmdlet; Get-ExecutionPolicy –List
Windows PowerShell Basics – Remove Item
2 | P a g e
PowerShell Script – Check and Delete File
In this PowerShell script we will have few validations and subsequently delete the file in the folder,
validations as follows.
 Directory / path exists
 File Exists
This script will exit if directory / file doesn’t exists that the user provides for deletion. Also, ensure the file
is NOT in use by any process or application.
Code Snippet – Check and Delete File
The code snippet is for demonstrating “File Deletion”.
Clear-Host
#
# Read Folder
#
$ReadDirectory=Read-Host -Prompt "Enter Directory"
if ( -NOT (Test-Path $ReadDirectory)) {
Write-Host "`nInvalid Directory" -ForegroundColor Green -BackgroundColor Black
[console]::Beep(900,300)
exit 1
} else {
$ReadFileName=Read-Host -Prompt "Enter filename to be deleted"
if ($ReadFileName -eq "") {
Write-Host "`nNo Filename Issued..." -ForegroundColor Green -BackgroundColor Black
[console]::Beep(900,300)
[System.Windows.MessageBox]::Show($ReadDirectory + '' + $ReadFileName + ' No Filename Issued ', "Delete
File Status")
return
}
if (Test-Path $ReadDirectory$ReadFileName) {
Set-Location $ReadDirectory
Push-Location $ReadDirectory
Remove-Item $ReadFileName -ErrorAction Inquire
Write-Host "`n Requested - $ReadDirectory$ReadFileName has been deleted" -ForegroundColor Green -
BackgroundColor Black
# Optional, validating by listing filename
# gci $ReadDirectory$ReadFileName -ErrorAction Ignore
} else {
Write-Host "`nFilename $ReadFileName does not exists!" -ForegroundColor Green -BackgroundColor Black
[console]::Beep(900,300)
[System.Windows.MessageBox]::Show($ReadDirectory + '' + $ReadFileName + ' - File does not exists ',
"Delete File Status")
return
}
}
Windows PowerShell Basics – Remove Item
3 | P a g e
PowerShell Output – Check and Delete File
When script is executed; below output will be displayed, with different messages.
Message – when requested file is “Deleted”.
Windows PowerShell Basics – Remove Item
4 | P a g e
Message – when the “Directory Invalid / Incorrect Directory”.
Message – when requested file is “File Not Found”.
Message – when requested file is “Still in Use by application / process”.

More Related Content

What's hot (20)

PDF
Windows PowerShell Basics - How To List PSDrive Info
VCP Muthukrishna
 
PDF
How To Install and Configure Log Rotation on RHEL 7 or CentOS 7
VCP Muthukrishna
 
PDF
How To Install and Configure GNome on CentOS 7
VCP Muthukrishna
 
PDF
How to Fix Duplicate Packages in YUM on CentOS 7
VCP Muthukrishna
 
PDF
How To Install and Configure SNMP on RHEL 7 or CentOS 7
VCP Muthukrishna
 
PDF
How To Manage Linux User on RHEL 7
VCP Muthukrishna
 
PDF
How To Check IE Enhanced Security Is Enabled Windows PowerShell
VCP Muthukrishna
 
PDF
How To Install and Configure Open SSH Server on Ubuntu
VCP Muthukrishna
 
PDF
How to Install and Configure Cacti on Linux
VCP Muthukrishna
 
PDF
Shell Script Disk Usage Report and E-Mail Current Threshold Status
VCP Muthukrishna
 
PDF
How To Configure Apache VirtualHost on RHEL 7 on AWS
VCP Muthukrishna
 
PDF
How To Install OpenFire in CentOS 7
VCP Muthukrishna
 
PDF
How To Disable IE Enhanced Security Windows PowerShell
VCP Muthukrishna
 
PDF
How To Protect SSH Access with Fail2Ban on RHEL 7
VCP Muthukrishna
 
PDF
How To Install and Configure Apache SSL on CentOS 7
VCP Muthukrishna
 
PDF
How To Check file exists and Delete PowerShell
VCP Muthukrishna
 
PDF
How To Create PowerShell Function
VCP Muthukrishna
 
PDF
How To Install and Configure AWS CLI for Windows
VCP Muthukrishna
 
PDF
How To Install and Configure Screen on CentOS 7
VCP Muthukrishna
 
PDF
How To List Nginx Modules Installed / Complied on CentOS 7
VCP Muthukrishna
 
Windows PowerShell Basics - How To List PSDrive Info
VCP Muthukrishna
 
How To Install and Configure Log Rotation on RHEL 7 or CentOS 7
VCP Muthukrishna
 
How To Install and Configure GNome on CentOS 7
VCP Muthukrishna
 
How to Fix Duplicate Packages in YUM on CentOS 7
VCP Muthukrishna
 
How To Install and Configure SNMP on RHEL 7 or CentOS 7
VCP Muthukrishna
 
How To Manage Linux User on RHEL 7
VCP Muthukrishna
 
How To Check IE Enhanced Security Is Enabled Windows PowerShell
VCP Muthukrishna
 
How To Install and Configure Open SSH Server on Ubuntu
VCP Muthukrishna
 
How to Install and Configure Cacti on Linux
VCP Muthukrishna
 
Shell Script Disk Usage Report and E-Mail Current Threshold Status
VCP Muthukrishna
 
How To Configure Apache VirtualHost on RHEL 7 on AWS
VCP Muthukrishna
 
How To Install OpenFire in CentOS 7
VCP Muthukrishna
 
How To Disable IE Enhanced Security Windows PowerShell
VCP Muthukrishna
 
How To Protect SSH Access with Fail2Ban on RHEL 7
VCP Muthukrishna
 
How To Install and Configure Apache SSL on CentOS 7
VCP Muthukrishna
 
How To Check file exists and Delete PowerShell
VCP Muthukrishna
 
How To Create PowerShell Function
VCP Muthukrishna
 
How To Install and Configure AWS CLI for Windows
VCP Muthukrishna
 
How To Install and Configure Screen on CentOS 7
VCP Muthukrishna
 
How To List Nginx Modules Installed / Complied on CentOS 7
VCP Muthukrishna
 

Similar to How To Check and Delete a File via PowerShell (20)

PPTX
Power Shell for System Admins - By Kaustubh
Kaustubh Kumar
 
PDF
One man loves powershell once he failed
Kazuhiro Matsushima
 
PDF
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
Hitesh Mohapatra
 
PDF
Basic commands for powershell : Configuring Windows PowerShell and working wi...
Hitesh Mohapatra
 
PPTX
PowerShell - Be A Cool Blue Kid
Matthew Johnson
 
PPTX
Power shell training
David Brabant
 
PPT
PowerShell Core Skills (TechMentor Fall 2011)
Concentrated Technology
 
PPTX
Getting Started With PowerShell Scripting
Ravikanth Chaganti
 
PPTX
Get-Help: An intro to PowerShell and how to Use it for Evil
jaredhaight
 
PDF
Windows Powershell Step By Step 3rd Edition Wilson Ed
forsenqenan
 
PDF
Power on, Powershell
Roo7break
 
PDF
Windows Powershell in Action 1st Edition Bruce G. Payette
takabedembe
 
PPTX
Powershell Tech Ed2009
rsnarayanan
 
PDF
Power Shell For Testers
Mca140 software solutions
 
PDF
Windows Powershell in Action 1st Edition Bruce G. Payette
moudenongui20
 
PPSX
Scriptclub1
Sean Kearney
 
PPTX
Introduction to powershell
Salaudeen Rajack
 
PPTX
02Introduction to Power Shell Win Server all in one.pptx
edget1
 
PDF
Windows Powershell in Action 1st Edition Bruce G. Payette
zahithovor
 
PPTX
PowerShell-1
Saravanan G
 
Power Shell for System Admins - By Kaustubh
Kaustubh Kumar
 
One man loves powershell once he failed
Kazuhiro Matsushima
 
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
Hitesh Mohapatra
 
Basic commands for powershell : Configuring Windows PowerShell and working wi...
Hitesh Mohapatra
 
PowerShell - Be A Cool Blue Kid
Matthew Johnson
 
Power shell training
David Brabant
 
PowerShell Core Skills (TechMentor Fall 2011)
Concentrated Technology
 
Getting Started With PowerShell Scripting
Ravikanth Chaganti
 
Get-Help: An intro to PowerShell and how to Use it for Evil
jaredhaight
 
Windows Powershell Step By Step 3rd Edition Wilson Ed
forsenqenan
 
Power on, Powershell
Roo7break
 
Windows Powershell in Action 1st Edition Bruce G. Payette
takabedembe
 
Powershell Tech Ed2009
rsnarayanan
 
Power Shell For Testers
Mca140 software solutions
 
Windows Powershell in Action 1st Edition Bruce G. Payette
moudenongui20
 
Scriptclub1
Sean Kearney
 
Introduction to powershell
Salaudeen Rajack
 
02Introduction to Power Shell Win Server all in one.pptx
edget1
 
Windows Powershell in Action 1st Edition Bruce G. Payette
zahithovor
 
PowerShell-1
Saravanan G
 
Ad

More from VCP Muthukrishna (12)

PDF
How To Construct IF and Else Conditional Statements
VCP Muthukrishna
 
PDF
How To Create PowerShell Function Mandatory Parameter and Optional Parameter
VCP Muthukrishna
 
PDF
How To Create Power Shell Function Mandatory Parameter Value
VCP Muthukrishna
 
PDF
How To Configure Nginx Load Balancer on CentOS 7
VCP Muthukrishna
 
PDF
Nginx bind() to 0.0.0.0:9080 failed
VCP Muthukrishna
 
PDF
How To Install and Configure Salt Master on Ubuntu
VCP Muthukrishna
 
PDF
How To Configure SNMP Logging on RHEL 7
VCP Muthukrishna
 
PDF
How To Find Package Installation Date on RHEL 7
VCP Muthukrishna
 
PDF
How to Upgrade Openfire on CentOS 7
VCP Muthukrishna
 
PDF
How To Reset root Password on CentOS 7
VCP Muthukrishna
 
PDF
How To View Current Execution Policy PowerShell
VCP Muthukrishna
 
PDF
How To Install and Use ABRT CLI on RHEL 7
VCP Muthukrishna
 
How To Construct IF and Else Conditional Statements
VCP Muthukrishna
 
How To Create PowerShell Function Mandatory Parameter and Optional Parameter
VCP Muthukrishna
 
How To Create Power Shell Function Mandatory Parameter Value
VCP Muthukrishna
 
How To Configure Nginx Load Balancer on CentOS 7
VCP Muthukrishna
 
Nginx bind() to 0.0.0.0:9080 failed
VCP Muthukrishna
 
How To Install and Configure Salt Master on Ubuntu
VCP Muthukrishna
 
How To Configure SNMP Logging on RHEL 7
VCP Muthukrishna
 
How To Find Package Installation Date on RHEL 7
VCP Muthukrishna
 
How to Upgrade Openfire on CentOS 7
VCP Muthukrishna
 
How To Reset root Password on CentOS 7
VCP Muthukrishna
 
How To View Current Execution Policy PowerShell
VCP Muthukrishna
 
How To Install and Use ABRT CLI on RHEL 7
VCP Muthukrishna
 
Ad

Recently uploaded (20)

PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
July Patch Tuesday
Ivanti
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
July Patch Tuesday
Ivanti
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 

How To Check and Delete a File via PowerShell

  • 1. Windows PowerShell Basics – Remove Item i | P a g e Table of Contents Overview.......................................................................................................................................................1 Applies To..................................................................................................................................................1 Pre-Requisites ...........................................................................................................................................1 Current Execution Policy...........................................................................................................................1 PowerShell Script – Check and Delete File....................................................................................................2 Code Snippet – Check and Delete File ......................................................................................................2 PowerShell Output – Check and Delete File .........................................................................................3
  • 2. Windows PowerShell Basics – Remove Item 1 | P a g e Overview In this guide we will demonstrate as to how to delete a file on a server after checking if the file exists with Windows PowerShell script. Applies To Tested on Windows 10, Windows 2008 R2 and Windows 2012. Pre-Requisites Launch PowerShell Command Console or PowerShell ISE. To run this script, Execution Policy should be set to either of these “AllSigned” or “RemoteSigned” or “Unrestricted”, you can get current execution policy by running the command; “Get-ExecutionPolicy”. Each Policy type and its purpose is shown in the below table. Policy Type Purpose Restricted No scripts can be run. Windows PowerShell can be used only in interactive mode. AllSigned Only scripts signed by a trusted publisher can be run. RemoteSigned Downloaded scripts must be signed by a trusted publisher before they can be run. Unrestricted No restrictions; all Windows PowerShell scripts can be run. Current Execution Policy To know the current run the PowerShell cmdlet; Get-ExecutionPolicy To list execution policies that can be configured run the PowerShell cmdlet; Get-ExecutionPolicy –List
  • 3. Windows PowerShell Basics – Remove Item 2 | P a g e PowerShell Script – Check and Delete File In this PowerShell script we will have few validations and subsequently delete the file in the folder, validations as follows.  Directory / path exists  File Exists This script will exit if directory / file doesn’t exists that the user provides for deletion. Also, ensure the file is NOT in use by any process or application. Code Snippet – Check and Delete File The code snippet is for demonstrating “File Deletion”. Clear-Host # # Read Folder # $ReadDirectory=Read-Host -Prompt "Enter Directory" if ( -NOT (Test-Path $ReadDirectory)) { Write-Host "`nInvalid Directory" -ForegroundColor Green -BackgroundColor Black [console]::Beep(900,300) exit 1 } else { $ReadFileName=Read-Host -Prompt "Enter filename to be deleted" if ($ReadFileName -eq "") { Write-Host "`nNo Filename Issued..." -ForegroundColor Green -BackgroundColor Black [console]::Beep(900,300) [System.Windows.MessageBox]::Show($ReadDirectory + '' + $ReadFileName + ' No Filename Issued ', "Delete File Status") return } if (Test-Path $ReadDirectory$ReadFileName) { Set-Location $ReadDirectory Push-Location $ReadDirectory Remove-Item $ReadFileName -ErrorAction Inquire Write-Host "`n Requested - $ReadDirectory$ReadFileName has been deleted" -ForegroundColor Green - BackgroundColor Black # Optional, validating by listing filename # gci $ReadDirectory$ReadFileName -ErrorAction Ignore } else { Write-Host "`nFilename $ReadFileName does not exists!" -ForegroundColor Green -BackgroundColor Black [console]::Beep(900,300) [System.Windows.MessageBox]::Show($ReadDirectory + '' + $ReadFileName + ' - File does not exists ', "Delete File Status") return } }
  • 4. Windows PowerShell Basics – Remove Item 3 | P a g e PowerShell Output – Check and Delete File When script is executed; below output will be displayed, with different messages. Message – when requested file is “Deleted”.
  • 5. Windows PowerShell Basics – Remove Item 4 | P a g e Message – when the “Directory Invalid / Incorrect Directory”. Message – when requested file is “File Not Found”. Message – when requested file is “Still in Use by application / process”.