Connect-ServiceFabricCluster call fails when called twice
<p>I am working on creating a script that I can use to deploy my Azure Service Fabric Application to my local cluster or to a Azure hosted cluster.  And I am running into an issue if I run the script twice.  The <code>Connect-ServiceFabricCluster</code> command fails when my script is executed the second time.  I can restart the PowerShell console, or PowerShell ISE and the issue is not seen again until the second call.  This results in a cumbersome process to change the script.</p>

<pre><code>function Read-XmlElementAsHashtable
{
    Param (
        [System.Xml.XmlElement]
        $Element
    )

    $hashtable = @{}
    if ($Element.Attributes)
    {
        $Element.Attributes | 
            ForEach-Object {
                $boolVal = $null
                if ([bool]::TryParse($_.Value, [ref]$boolVal)) {
                    $hashtable[$_.Name] = $boolVal
                }
                else {
                    $hashtable[$_.Name] = $_.Value
                }
            }
    }

    return $hashtable
}

function Read-PublishProfile
{
    Param (
        [ValidateScript({Test-Path $_ -PathType Leaf})]
        [String]
        $PublishProfileFile
    )

    $publishProfileXml = [Xml] (Get-Content $PublishProfileFile)
    $publishProfile = @{}

    $publishProfile.ClusterConnectionParameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("ClusterConnectionParameters")
    $publishProfile.UpgradeDeployment = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("UpgradeDeployment")

    if ($publishProfileXml.PublishProfile.Item("UpgradeDeployment"))
    {
        $publishProfile.UpgradeDeployment.Parameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("UpgradeDeployment").Item("Parameters")
        if ($publishProfile.UpgradeDeployment["Mode"])
        {
            $publishProfile.UpgradeDeployment.Parameters[$publishProfile.UpgradeDeployment["Mode"]] = $true
        }
    }

    $publishProfileFolder = (Split-Path $PublishProfileFile)
    $publishProfile.ApplicationParameterFile = [System.IO.Path]::Combine($PublishProfileFolder, $publishProfileXml.PublishProfile.ApplicationParameterFile.Path)

    return $publishProfile
}

$profileSettings = Read-PublishProfile $PublishProfileFile

try
{
    $clusterConnectionParameters = $profileSettings.ClusterConnectionParameters
    [void](Connect-ServiceFabricCluster @clusterConnectionParameters)
}
catch [System.Fabric.FabricObjectClosedException]
{
    Write-Warning "Service Fabric cluster may not be connected."
    throw
}
</code></pre>

<p>If you've looked into the <code>Deploy-FabricApplication.ps1</code> script that Visual Studio creates when you create an Azure Service Fabric Application, this code should look familiar as that is my source for what I used in my script.</p>

<p>The error message I see when I run the script a second time is:</p>

<pre><code>WARNING: Failed to contact Naming Service. Attempting to contact Failover Manager Service...
WARNING: Failed to contact Failover Manager Service, Attempting to contact FMM...
WARNING: Service Fabric cluster may not be connected.
Connect-ServiceFabricCluster : One or more errors occurred.
At MyScript.ps1:218 char:9
+     [void](Connect-ServiceFabricCluster @clusterConnectionParameters)
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-ServiceFabricCluster], AggregateException
    + FullyQualifiedErrorId : CreateClusterConnectionErrorId,Microsoft.ServiceFabric.Powershell.ConnectCluster
</code></pre>

<p>My Local.xml Publish Profile, I've made no changes to it, it is the default file Visual Studio created when I create the project.</p>

<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;PublishProfile xmlns="http://schemas.microsoft.com/2015/05/fabrictools"&gt;
  &lt;ClusterConnectionParameters /&gt;
  &lt;ApplicationParameterFile Path="..\ApplicationParameters\Local.xml" /&gt;
&lt;/PublishProfile&gt;
</code></pre>

<p>Steps I take when I see the issue:</p>

<ol>
<li>Run script to deploy</li>
<li>Verify everything is working</li>
<li>Reset local cluster</li>
<li>Run script to deploy again</li>
<li>Script encounters error</li>
</ol>

<p>I do not see this issue when connecting multiple times to a cluster in Azure, only when connected to my local cluster.</p>

<p>Is there anything I missing as to not encounter the issue on a second run?  I wonder if I'm missing a disconnect command as a restart would clear any state that is kept around, but I've not found anything that appears to be a disconnect from service fabric cluster command.</p>

<p>I did find <a href="https://stackoverflow.com/questions/36587940/connect-servicefabriccluster-fails-to-contact-naming-server-on-remote-azure-serv">this post</a> as well on SO which appears to be the same error, but the path to reproduce the issue is different.</p>