Search code examples
powershelldirectoryiis-8powershell-4.0rename-item-cmdlet

How to rename IIS website directory with Powershell (Access denied error)


I'm trying to write a powershell deployment script to stop a website, rename a few directories, and restart the website but I'm stuck on the renaming part. Sometimes I'm able to rename the directory but most of the time I get an "Access to the path 'xxx' is denied." error. I need this script to work every time.

I'm running as Administrator, I'm using -Force, I'm even waiting 10 seconds after stopping the website and retrying. I've checked for processes using the directory and only w3wp.exe shows up. (FWIW, when this happens I'm not able to rename the directory through File Explorer either - "The action can't be completed because the folder is open in another program.")

Relevant code:

#rename the IIS directory
$renamed = $false
if($success -and $status.value -eq "Stopped")
{
    Write-Host ("renaming " + $stagingPath)
    try
    {
        Rename-Item -Path $stagingPath -NewName $tempPath -ErrorAction Stop
    } 
    catch
    {
        Write-Host("An error occurred during renaming. Retrying ...")
        Start-Sleep -s 10
        Rename-Item -Path $stagingPath -NewName $tempPath -Force -ErrorAction Stop
    }

    if(Test-Path $tempPath)
    {
        $renamed = $true
        Get-ChildItem
        Write-Host("IIS site renamed to " + $tempPath)
    }
    else
    {
        Write-Host("ERROR: Renaming to temp failed")
    }
}

($stagingPath and $tempPath are directory names only, not full paths. They are definitely correct.)

What am I missing? Do I need to explicitly stop the app pool as well?


Solution

  • To answer my own question, yes, you need to explicitly stop the AppPool in addition to stopping the Website in order to release the w3wp.exe process. Once I added:

    Stop-WebAppPool -Name $stagingAppPoolName
    

    to my script after I stop the Website, it's working great. I'm able to rename the directory without errors. Thanks for the helpful hints about stopping the process.