PowerShell: Remove Remote Folder

PowerShell: Remove Remote Folder

PowerShell: Remove Remote Folder

In this post, you will see how to remove a specific folder from a remote machine. This would work on remote shares that run Windows 2003, XP, Windows 2008 and Windows 2012.

$comp = Read-Host "Enter Computer Name:"
$share = Read-Host "Enter folder name that needs to be deleted"

$verify = Read-Host "Deleting \$compc$$share permanently. Are you sure (y/n)?"

If ($verify -eq 'y')
{
    $testping = Test-Connection -ComputerName $comp -Quiet -Count 1
    if ($testping)
    {
           $testpath = Test-Path "\$compc$$share"
           if($testpath)
           {
                Write-Host "Deleting Folder. Please be patient" -ForegroundColor Cyan
                Remove-Item "\$compc$$share" -Recurse -Force -Confirm:$False
                $testpath = Test-Path $"\$compc$$share"
                if (!$testpath)
                {
                       Write-Host "Share doesn't exists. Looks like it was successfully removed." -ForegroundColor Cyan
                }
                else
                {
                    Write-Host "Strangely Share still exists. This needs to be checked manually." -ForegroundColor White
                }
            }
            else
            {
		Write-Host $testpath
                Write-Host "Path \$compc$$share doesn't exist. Please check the values entered" -ForegroundColor Yellow
            }
    }
    else
    {
        Write-Host "$comp doesn't apprear to be on Network. Exiting" -ForegroundColor Yellow
    }
}
else
{
    Write-Host "Script has not made any change, because it was directed to Terminate. Exiting" -ForegroundColor Yellow
}

About The Author

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *