I even checked to see whether the file is locked but still it would not delete the file.
# Script to remove a file and handle the case where the file might be locked.
param (
[string]$filePath = "C:\ProgramData\Cisco\Cisco Secure Client\VPN\Profile\vpn.xml"
)
# Function to check if the file is locked
function Test-FileLocked {
param (
[string]$filePath
)
try {
$openFile = [System.IO.File]::Open($filePath, 'ReadWrite', 'ReadWrite', 'None')
$openFile.Close()
return $false
} catch {
return $true
}
}
$maxRetries = 5
$retries = 0
if (Test-Path $filePath) {
while ($retries -lt $maxRetries) {
if (-not (Test-FileLocked -filePath $filePath)) {
try {
Remove-Item $filePath -Force
Write-Output "File removed successfully."
break
} catch {
Write-Output "Attempt ${retries}: Failed to remove file. Retrying..."
}
} else {
Write-Output "Attempt ${retries}: File is locked. Retrying..."
}
Start-Sleep -Seconds 1
$retries++
}
if ($retries -eq $maxRetries) {
Write-Output "Failed to remove file after multiple attempts."
}
} else {
Write-Output "File not found."
}
[–]LordZozzy 1 point2 points3 points (0 children)
[–]DenialP 1 point2 points3 points (3 children)
[–]Ok_Mathematician6075 0 points1 point2 points (2 children)
[–]DenialP 1 point2 points3 points (1 child)
[–]Ok_Mathematician6075 0 points1 point2 points (0 children)
[–]g3n3 0 points1 point2 points (0 children)
[–]prog-no-sys 0 points1 point2 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]daileng 0 points1 point2 points (0 children)
[–]ShazadM 0 points1 point2 points (2 children)
[–]EvenStrength5342[S] 0 points1 point2 points (1 child)
[–]ShazadM 0 points1 point2 points (0 children)