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)

PDF
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PPTX
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
PDF
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
Practical Applications of AI in Local Government
OnBoard
 
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 

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”.