简体   繁体   中英

Powershell Delete Locked File But Keep In Memory

Until recently, we've been deploying .exe applications by simply copying them manually to the destination folder on the server. Often though, the file was already running at the time of deployment (the file is called from a SQL Server job)--sometimes even multiple instances. We don't want to kill the process while it's running. We also can't wait for it to finish because it keeps on being invoked, sometimes multiple times concurrently.

As a workaround, what we've done is a "cut and paste" via Windows Explorer on the .exe file into another folder. Apparently, what this does is it moves the file (effectively a delete) but keeps it in RAM so that the processes which are using it can continue without issues. Then we'd put the new files there which would get called when any later program would call it.

We've now moved to an automated deploy tool and we need an automated way of doing this.

Stop-Process -name SomeProcess

in PowerShell would kill the process, which I don't want to do.

Is there a way to do this? (C# would also be OK.)

Thanks,

function moverunningprocess($process,$path)
{
    if($path.substring($path.length-1,1) -eq "\") {$path=$path.substring(0,$path.length-1)}
    $fullpath=$path+"\"+$process
    $movetopath=$path + "--Backups\$(get-date -f MM-dd-yyyy_HH_mm_ss)"
    $moveprocess=$false

    $runningprocess=Get-WmiObject Win32_Process -Filter "name = '$process'" | select CommandLine
    foreach ($tp in $runningprocess)
    {
        if ($tp.commandline -ne $null){
            $p=$tp.commandline.replace('"','').trim()
            if ($p -eq $fullpath) {$moveprocess=$true}
        }
    }

    if ($moveprocess -eq $true)
    {
        New-Item -ItemType Directory -Force -Path $movetopath
        Move-Item -path "$path\*.*" -destination "$movetopath\"
    }
}

moverunningprocess "processname.exe" "D:\Programs\ServiceFolder"

Since you're utilizing a SQL Sever to call the EXE. Why do you add a table that contains the path to the latest version of the file and modify your code that fires the EXE. That way when a new version is rolled out, you can create a new folder, place the file in it, and update the table pointing to it. That will allow any still active threads to have access to the old version and any new threads will pickup up the new executable. You then can delete the old file after it's no longer needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM