简体   繁体   中英

Calling PowerShell Azure module and creating resource group from C#

I have the following PowerShell script that 1) installs Azure PowerShell SDK 2) logs in to Azure using the service principle and 3) creates a resource group. I am trying to call this script from C# .NET 6 but I am getting this error:

New-AzResourceGroup -name $recoveryResourceGroupName -location $locat …
     |  ~~~~~~~~~~~~~~~~~~~
     | The term 'New-AzResourceGroup' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I think it's not running the PowerShell script code at all.

Note that the actual script does a lot more than just creating a resource group, but this is just an example.

// The difference between CreateDefault and CreateDefault2 is that
// CreateDefault includes engine snap-ins, while CreateDefault2 does not.
var initialState = InitialSessionState.CreateDefault2();
using var ps = PowerShell.Create(initialState);
var results = await ps.AddScript(@"
[string][ValidateNotNullOrEmpty()] $applicationId = """"
[string][ValidateNotNullOrEmpty()] $secret = """"
[string][ValidateNotNullOrEmpty()] $subscriptionId = """"
[string][ValidateNotNullOrEmpty()] $tenantId = """"

# Install Azure Powershell modules
Write-Output "Installing Modules..."
if (Get-Module -ListAvailable -Name 'Az*') {
    Write-Output "  Az Already Installed"
} 
else {
    Install-Module -Name 'Az' -Scope CurrentUser -Repository PSGallery -Force
    Write-Output "Installed AZ"
}

# Import Azure module
Import-Module 'Az'

# Login to azure using credentials from the KeyVault
$secretAsSecureString = ConvertTo-SecureString -String $secret -AsPlainText -Force
$pscredential = New-Object -TypeName System.Management.Automation.PSCredential($applicationId, $secretAsSecureString)
Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId

# Select Right subscription
Set-AzContext $subscriptionId

New-AzResourceGroup -Name 'TestRg123' -Location 'eastus2euap'
").InvokeAsync();

foreach (PSObject outputItem in results)
{
    Debug.WriteLine(outputItem);
}

UPDATE #1 : I updated the script and added -AllowClubber to make Az is installed but this is what I am getting in the output:

在此处输入图像描述

I think Az is not getting installed and for some reason it think Az is already installed

And then

New-AzResourceGroup: 
Line |
  97 |  New-AzResourceGroup -name $recoveryResourceGroupName -location $locat …
     |  ~~~~~~~~~~~~~~~~~~~
     | The term 'New-AzResourceGroup' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

UPDATE #2 : I modified the PowerShell script to unconditionally install the Az and I am still getting the same error that New-AzResourceGroup is not defined

I have got similar error when i am using command

New-AzResourceGroup

Then i have used Azure cli commands then i get the resource group created in azure

My powershell script(Updated your script):

using System.Diagnostics;
using System.Management.Automation.Runspaces;
using System.Management.Automation;

var initialState = InitialSessionState.CreateDefault2();
initialState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

using var ps = PowerShell.Create(initialState);
var results = ps.AddScript(@"
Install-PackageProvider -Name Nuget -Scope CurrentUser –Force

Install-Module –Name PowerShellGet -Scope CurrentUser –Force

Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force
Install-Module -Name Az.Resources -AllowClobber -Scope CurrentUser

# Import Azure module

Import-Module 'Az'
Import-Module 'Az.Accounts'
Import-Module 'Az.RecoveryServices'

az login

try {
    az account set --subscription ""XXX"
    az group create --name rithDemo --location eastus
}
catch
{
    $string_err = $_ | Out-String
    Write-Output ""Failed to run test $testname because $string_err""
}
").Invoke();

XXX- Subscription name

rithDemo- resource group name

  • In script I have first login into azure using az login . Then you will be redirected to azure login page there you can login.
  • Then I set the subscription using az account set command
  • Then I created a resource group using az group create
  • Also added AllowClobber in script By this process the resource group got created.

Output:

在此处输入图像描述

Check your powershell version and try to download latest: https://github.com/PowerShell/PowerShell

In your script you should be able to use:

Import-Module Az.Resources

#Just in case

Az Upgrade 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM