Home > Blockchain >  Cloud not load file or assembly 'System.Management.Automation' while running powershell sc
Cloud not load file or assembly 'System.Management.Automation' while running powershell sc

Time:01-11

So I am trying to run some powershell script on my WPF app to update my IpRules on Azure but even simple script like "Write-Output 'Hello, World!'" gives me this error: Could not load file or assembly 'System.Management.Automation, Version=7.2.8.0, Culture=neutral, PublicKeyToken=token123456'. The system cannot find the file specified. Here is my code:

        public Collection<PSObject> GetExistingFirewallIPRules(string script, Dictionary<string, object> scriptParameters)
        {
            PowerShell ps = PowerShell.Create();
            ps.AddScript(script);
            return ps.Invoke();
        }

And here is .csproj

 <PropertyGroup>
    <TargetFramework>net6.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWPF>true</UseWPF>
      <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Azure.ResourceManager.AppService" Version="1.0.0" />
    <PackageReference Include="Azure.ResourceManager.CosmosDB" Version="1.2.0" />
    <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.3.1" />
    <PackageReference Include="Prism.Core" Version="8.1.97" />
    <PackageReference Include="Prism.Wpf" Version="8.1.97" />
    <PackageReference Include="System.Management.Automation" Version="7.2.8" />
  </ItemGroup>

How can I fix this error or is it any other way to update my CosmosDB IpRules in Azure portal than running powershell (eg. "Update-AzCosmosDBAccount -ResourceGroupName $resourceGroupName -Name $accountName -IpRangeFilter $ipFilter") script?

CodePudding user response:

Using the System.Management.Automation NuGet package directly is not recommended - see this answer for what package to choose for what scenario.

In the context of a .NET (Core) application, use only the Microsoft.PowerShell.SDK package (similarly, all flavors of the PowerShell SDK only require one package).

  • That you mistakenly used both and had conflicting version numbers is likely what caused your problem.

Since you're targeting .NET 6, you must use an older version of that package, given that the version that is current as of this writing, 7.3.1 requires .NET 7; for .NET 6, use a 7.2.x version

In other words:

  • Remove line <PackageReference Include="System.Management.Automation" Version="7.2.8" />

  • Update line <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.3.1" /> to
    <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.8" />

  • Related