首页 > 解决方案 > 如何使用 Powershell 重命名 IIS 网站目录(拒绝访问错误)

问题描述

我正在尝试编写一个 powershell 部署脚本来停止网站,重命名一些目录,然后重新启动网站,但我被困在重命名部分。有时我可以重命名目录,但大多数时候我会收到“拒绝访问路径 'xxx'”。错误。我每次都需要这个脚本才能工作。

我以管理员身份运行,我正在使用 -Force,我什至在停止网站并重试后等待 10 秒。我检查了使用该目录的进程,只显示 w3wp.exe。(FWIW,发生这种情况时,我也无法通过文件资源管理器重命名目录 - “该操作无法完成,因为该文件夹已在另一个程序中打开。”)

相关代码:

#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 和 $tempPath 只是目录名,不是完整路径。它们绝对正确。

我错过了什么?我是否也需要明确停止应用程序池?

标签: powershelldirectoryiis-8powershell-4.0rename-item-cmdlet

解决方案


要回答我自己的问题,是的,除了停止网站之外,您还需要明确停止 AppPool 以释放 w3wp.exe 进程。一旦我添加:

Stop-WebAppPool -Name $stagingAppPoolName

在我停止网站后到我的脚本,它工作得很好。我能够重命名目录而不会出错。感谢您提供有关停止该过程的有用提示。


推荐阅读