首页 > 解决方案 > 将命令作为脚本的一部分运行但单独运行时不会出错

问题描述

当我将命令作为脚本的一部分运行或在 Powershell ISE 和 Powershell 终端中进行调试时,出现以下错误。我在两者中都以管理员身份运行。

Rename-Item -Path IIS:\AppPools\webdba2 -NewName WEBDBA

重命名项目:索引超出范围。必须是非负数且小于集合的大小。参数名称:索引

powershell中的实际代码是

Rename-Item -Path "IIS:\Sites\$CurrentWebsiteName" -NewName $OrgUrl

现在在脚本之外运行变量或硬编码工作。我在 try catch 语句中运行它。

脚本:

$MassSiteData = Import-Csv $strPath -Header url,apppool,shorturl 
$intRowMax = $MassSiteData.count
$intRow = 0

ForEach($WebSite in $MassSiteData) 
{
    $intRow++

    $OrgAppPool = $WebSite.apppool
    $OrgUrl = $WebSite.url
    $OrgShortUrl = $WebSite.shorturl

    $AppPoolSearchVar = $WebSite.apppool + "*"
    $ShortUrlSearchVar = $WebSite.shorturl + "*"

    [Void][Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration")

    $sm = New-Object Microsoft.Web.Administration.ServerManager 
    $site = Get-Website | Where-Object {$_.Name -like $ShortUrlSearchVar}
    $CurrentWebsiteName = $site.Name 
    $CurrentWebPath = $site.PhysicalPath

    $CurrentAppPool = ($sm.ApplicationPools | Where-Object {$_.Name -like $AppPoolSearchVar}).Name
    $CurrentAppPath = split-path -parent $CurrentWebPath

    try {
        ##Rename AppPool
        Rename-Item -Path "IIS:\AppPools\$CurrentAppPool" -NewName $OrgAppPool
        $logMsg = "Renamed App Pool to $OrgAppPool"
        Write-Host "Renamed App Pool to $OrgAppPool"
        $logMsg | Out-File $logfilelocation -Append
    } catch {
        $logMsg = "App Pool didnt need updated"
        write-host "App Pool Errored out. Most likely didnt need updated"
        $logMsg | Out-File $logfilelocation -Append
    }
}

标签: powershelliis

解决方案


推荐阅读