"IIS: Cannot create a file when that file already exists.Exception.Message" 通过 SSL 证书和 powershell 创建 https 绑定时

"IIS: Cannot create a file when that file already exists.Exception.Message" when creating a https binding through SSL certificate and powershell

我已经写了这个方法来使用安装的 SSL 证书并在 IIS 中启用 https 绑定。但是当我调用这个方法时,我从 Powershell 中得到了这个错误。

IIS: Cannot create a file when that file already exists.Exception.Message

这是开启绑定的功能。我正在从 .json 文件

中读取的所有必需变量
function IIS-SSL-SETUP {
    
    $Global:iisStatus = $started
    try {
        $pwd = ConvertTo-SecureString -String $PFX_PASSWORD -Force -AsPlainText
        Import-PfxCertificate -FilePath $PFX_FILE_LOCATION Cert:\LocalMachine\My -Password $pwd
        $pfx.import($PFX_FILE_LOCATION, $PFX_PASSWORD, "Exportable,PersistKeySet") 
        $store = new-object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::Root, "localmachine")
        $store.open("MaxAllowed") 
        $store.add($pfx) 
        $store.close()
        Import-Module WebAdministration
        Set-Location IIS:\
        if ($null -eq (Get-WebBinding "MyServer" | Where-Object { $_.bindingInformation -eq "*:$($IIS_SSS_HTTPS_PORT):" })) {
            New-WebBinding -Name "MyServer" -IP "*" -Port $IIS_SSS_HTTPS_PORT -Protocol https
            Get-WebBinding -Port $IIS_SSS_HTTP_PORT -Name "MyServer" | Remove-WebBinding
            cd SslBindings
            dir
            $pfx.Import($PFX_FILE_LOCATION, $PFX_PASSWORD, 'DefaultKeySet')
            $certThumbprint = "\LocalMachine\My$($pfx.Thumbprint)"
            get-item Cert:$certThumbprint | new-item 0.0.0.0!$($IIS_SSS_HTTPS_PORT) //I am getting this error at this line
            $Global:iisStatus = "Passed"
        }
        else {
            $Global:iisStatus = "Failed"
            $Global:iisMsg = "Port $($IIS_SSS_HTTPS_PORT) is already in use, please mention some different port number in sslConfig.json."
            $Global:iisMsgColor = "Yellow"
        }
    }
    catch {
        $Global:iisStatus = "Failed"
        $Global:iisMsgColor = "Red"
        $Global:iisMsg = "IIS: $_.Exception.Message"
    }
}

@Mehul Parmar,如您所问,我已删除我的评论并将其移至答案中:

dir 命令是否列出了一些内容?它可能应该在你的情况下。我的测试没有结果并且运行良好没有错误。您可以测试该元素是否已存在:

if (-not (Test-Path 0.0.0.0!$($IIS_SSS_HTTPS_PORT)))

"MyServer" 是一个奇怪的网站名称,不要忘记绑定是绑定到站点而不是服务器。还有一件事:如果未定义 $IIS_SSS_HTTP_PORTGet-WebBinding -Port $IIS_SSS_HTTP_PORT -Name "MyServer" | Remove-WebBinding 将删除所有绑定。也许你应该更喜欢这个:

Get-WebBinding -Protocol http -Name "MyServer" | Remove-WebBinding