I have a script in which Some of the files get deleted...
VERBOSE: Performing the operation "Remove Directory" on target \name1\subitem
VERBOSE: Performing the operation "Remove Directory" on target \name1\subitem1
VERBOSE: Performing the operation "Remove Directory" on target \name1\subitem2
but others throw this error following the other verbose messages:
Cannot remove item d:\temp\name1.db\metadata.sqlitedb: The process cannot access the file 'metadata.sqlitedb' because it is being used by another process.
Directory d:\temp\name1.db cannot be removed because it is not empty.
How can i automatically kill the process used (whichever it is) and attempt to remove the item again as part of my script above?
i tried handle suggestion from this thread PowerShell script to check an application that's locking a file?, but i think our servers dont allow external tools as i either dont get any output or getting access denied...so im looking for some other option that doesnt require external tool
Essentially looking for something like this as part of my script:
$Directory = "d:\temp"
Invoke-Command -Computer $Server -ScriptBlock {
param ($dir, $name)
#Write-Output "dir='$dir', name='$name'"
$f = Get-ChildItem -Path $dir | Where {$_.Name -Match $name} | Select -ExpandProperty FullName
if ($f) {
$f | Foreach {
try
{
Remove-Item $_ -confirm:$false -recurse -Verbose #-WhatIf
}
catch
{
if ($_.Exception.Message -like '*it is being used by another process*')
{ write-host "that process is " $pid + $pname
try{
KILL PROCESS
Remove-Item $_ -confirm:$false -recurse -Verbose #-WhatIf
}
catch
{
$error[0]
}
}
else
{
Write-Host "$($error[0])`r`n" -foregroundcolor magenta -backgroundcolor black
}
}
}
}
else {
Write-Verbose "No file found"
}
} -ArgumentList $Directory, $DB -verbose