Delete files and folders

The most of us had to delete files or folders in our scripts. This is truly simple task with powershell. There is cmdlet Remove-Item to delete files and folders. Example for delete file in PowerShell.

remove-item c:\Temp\text.txt -force

Switch -Force is used to delete protected files. But what will happend if file doesn’t exist? You’ll get an error message.


This is the reason to do check if file exist first. To accomplish this, we will use test-path cmdlet.

$strFileName = "c:\temp\test.txt"
If (Test-Path $strFileName)
{
    Remove-Item $strFileName -Force
}

The similar code can be used for folders. But there is little difference in folders. There can be additional content in folder, you want to remove. So you should use switches -recurse -force.

$strFolderName = "c:\temp"
If (Test-Path $strFolderName)
{
    Remove-Item $strFolderName -recurse -force
}


This code will remove, folder with all content! So be careful!
In real life, I am using -Whatif switch first. Just for sure…


Switch -Whatif at the end of command is used for testing mode. Powershell will not make any permanent changes.

Komentáře

Populární příspěvky z tohoto blogu

Copy Group Membership to another user

Set up Auto Logon in Windows using PowerShell

Lync 2013 Persistent Chat Service not starting