Link to home
Start Free TrialLog in
Avatar of cawasaki
cawasaki

asked on

script to check if process is locked file on specific folderbefore delete folder

hello,

i need to delete some folder on server (windows 2008 or 2012).
but some times process blocked some folder or file to be deleted.

i need a script or command to check if any process is use specific folder and kill them so i can delete the folder.

i need a script because i have many folder to delete every day.

thanks for help
Avatar of Dmitri Farafontov
Dmitri Farafontov
Flag of Canada image

You can do something like this in PowerShell:

function Test-IsFileLocked
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [string[]$Files
    )

    Process
    {
        # Foreach loop to accept arrays either from pipeline or Files parameter
        foreach ($file in $Files)
        {
            $Locked = $false

            try
            {
                # Try to open file
                $Test = [System.IO.File]::Open($file, 'Open', 'ReadWrite', 'None')

                # Close file and dispose object if succeeded
                $Test.Close()
                $Test.Dispose()
            }
            catch
            {
                # File is locked!
                $Locked =  $true
            }

            # Write file status to pipeline
            $Locked
        }
    }
}
Avatar of cawasaki
cawasaki

ASKER

hello,

how i use this?
hello,

any other solution plz?
ASKER CERTIFIED SOLUTION
Avatar of Dmitri Farafontov
Dmitri Farafontov
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial