Powershell脚本无法删除目录

时间:2017-03-10 06:21:40

标签: powershell locking

我编写了一个powershell脚本来卸载服务,然后删除安装该服务的文件夹。 该脚本卸载服务没有任何问题,但它无法删除目录...它说该目录正在使用中。当我尝试手动删除目录时它会删除就好....我已经尝试了各种方法来完成这项工作,但没有任何工作。服务安装在$ INSTALL_DIR \ server

function env_check () 
{
Try
{   
    Start-Transcript -Path C:\Deployment_Script.txt.log -ErrorAction Stop

    if (Get-Service "ESL_SERVICE" -ErrorAction Continue)
    {

        $arrService = Get-Service -Name ESL_SERVICE
        if ($arrService.Status -eq 'Running')
        {
            Stop-Service ESL_SERVICE
        }

        cd $INSTALL_DIR\server
        sc.exe delete "ESL_Service" -ErrorAction Stop
    }
    Remove-Item "$INSTALL_DIR\server" -Force -Recurse
    Remove-Item "$INSTALL_DIR\client" -Force -Recurse
    Remove-Item "$INSTALL_DIR\DB Migration" -Force -Recurse
}
Catch
{
    Write-Output $_.Exception.Message
    New-Item -Path $LOG_PATH  -ItemType directory -ErrorAction Stop
    Copy-Item -Force C:\Deployment_Script.txt.log $LOG_PATH\. -ErrorAction Stop
    exit
}
}

1 个答案:

答案 0 :(得分:2)

您正在通过cd $INSTALL_DIR\server

阻止自己

作为概念证明,您可以尝试以下

New-Item $env:temp\server -ItemType Directory
# by navigating to the folder we wish to delete we get an 'in use' error message
cd $env:temp\server
Remove-Item "$($env:temp)\server" -force -recurse

明确导出文件夹允许删除

New-Item $env:temp\server -ItemType Directory
cd $env:temp
Remove-Item "$($env:temp)\server" -force -recurse