Friday, December 16, 2016

How To Check File Exists and Delete PowerShell

Overview

In this post / snippet we will demonstrate, deleting a file on the system if the file exists.
  • If the file exists it will be deleted.
  • If the file doesn’t exist a message box will be displayed.
  • If the user doesn’t key any file, an error message will be displayed.

Applies To

Tested on Windows 10, Windows 2008 R2, Windows 2012.

Pre-Requisites

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

Policy 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
Image here...

PowerShell Script Info – Delete File

This script read filename from user input, check if file exists and delete it.

PowerShell Snippet

Copy and paste the below PowerShell script to delete a file from current location.

#
# Delete if file Exits
#
Clear-Host
#
# Read filename
#
$ReadFileName=Read-Host -Prompt "Enter file to be deleted"
if ($ReadFileName -eq "") {
Write-Host "No Filename Issued..."
[console]::beep(900,300)
[System.Windows.MessageBox]::Show($ReadFileName + ' - No Filename Issued ', "Delete File Status")
return
}
if (Test-Path $ReadFileName) {
 del $ReadFileName
 }
 else {
 Write-Host $ReadFileName does not exists!
 [console]::beep(900,300)
 [System.Windows.MessageBox]::Show($ReadFileName + ' - File does not exists.
 ', "Delete File Status")
 }

PowerShell Script – Result

When the script is executed, if the file exists file will be deleted or an error message will be shown.


Slideshare Information

Step by step guide with screenshots is uploaded.

No comments:

Post a Comment