Azure / CloudShell

Container Image for Azure Cloud Shell (https://azure.microsoft.com/en-us/features/cloud-shell/)
https://shell.azure.com
MIT License
256 stars 105 forks source link

Connect-AzureAD command does not work inside CloudShell if it is in a .ps1 script #72

Open Srijith-Seetharaman opened 3 years ago

Srijith-Seetharaman commented 3 years ago

Whenever I run a powershell script with this in the first lines ( Refer [(a)] for code I am trying to save and run ), I keep seeing the following error:

PS /home/srijith> ./azureRapidOnboarding.ps1
InvalidOperation: /opt/microsoft/powershell/7/profile.ps1:60
Line |
  60 |      & ($script:PSCloudShellUtilityModuleInfo){param([string]$Label, [ …
     |        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | The expression after '&' in a pipeline element produced an object that was not valid. It must result in a command name, a script
     | block, or a CommandInfo object.

InvalidOperation: /opt/microsoft/powershell/7/profile.ps1:167
Line |
 167 |          $azureADParameters = @{'Identity' = $true; 'TenantId' = $env: …
     |          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot index into a null array.

This is the code I am trying to run: [(a)]

Connect-AzureAD

How do I proceed? This command works from Azure powershell command prompt, and the issue is when executing the command from a file. Here is a video recording of the same:

https://user-images.githubusercontent.com/78795366/107461209-8f0dd880-6b7f-11eb-9958-3df0e882b30c.mp4

edyoung commented 3 years ago

The issue is that within Cloud Shell we provide a function which overrides the default Connect-AzureAD so that it uses the custom authentication mechanism Cloud Shell uses to avoid you having to re-enter credentials.

Changing the script to

import-module AzureAD.Standard.Preview
AzureAD.Standard.Preview\Connect-AzureAD -Identity -TenantID $env:ACC_TID

Should work as a workaround. I'll have to look into how we can make this more seamless.

PS try code azure.ps1 as an alternative to editing the file locally and uploading it...

edyoung commented 3 years ago

I believe this workaround works, leaving the issue open so other people who encounter this can see it

judedaryl commented 3 years ago

i got it to work with the preview import but when i try get-azureaduser i this error

Get-AzureADUser: Error occurred while executing GetUsers
Code: Request_BadRequest
Message: Invalid domain name in the request url.
edyoung commented 3 years ago

@judedaryl sounds like your issue is a different one. Could you create a separate bug and include the output from

$DebugPreference="Continue"
Get-AzureADUser -Verbose -Debug
Mrunamii218 commented 2 years ago

Trying to execute powershell command New-AzureADGroup -DisplayName "mrunamigroup" -MailEnabled $false -SecurityEnabled $true -MailNickName "NotSet" by adding in Bicep file through Deployment script .

Please Note:The workaround which is mentioned in this above was also added Import-module AzureAD.Standard.Preview AzureAD.Standard.Preview\Connect-AzureAD -Identity -TenantID $env:ACC_TID

This Powershell script executes successfully when manually executed on cloud shell also on local Powershell.

az-aad (3).zip

Powershell Script $moduleStatus = Get-Module -Name AzureAD if (!$moduleStatus){ Write-Output "AzureAD has not installed, trying to install" Install-Module -Name AzureAD -Force Import-Module -Name AzureAD } if(!$moduleStatus) { Write-Output "AzureAD module is installed" Import-module AzureAD.Standard.Preview AzureAD.Standard.Preview\Connect-AzureAD -Identity -TenantID $env:ACC_TID Get-AzureADGroup New-AzureADGroup -DisplayName "mrunamigroup" -MailEnabled $false -SecurityEnabled $true -MailNickName "NotSet" } else { Write-Output "Unable to install Azure AD module" }

Bicep File-

param location string = 'uksouth' //param utcValue string = utcNow() param identity string = '/subscriptions/79f012d0-9384-49a2-ae1d-b1e58b5fba05/resourceGroups/rg-hub-uksouth-002/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myid' resource runBashWithOutputs 'Microsoft.Resources/deploymentScripts@2020-10-01' = { name: 'runPowershellWithOutputs' location: location kind: 'AzurePowerShell' identity: { type: 'UserAssigned' userAssignedIdentities: { '${identity}': {} } } properties: { azPowerShellVersion: '3.0' scriptContent: loadTextContent('ADGroup.ps1') retentionInterval: 'P1D' } }

Facing this Error- {"code":"DeploymentFailed","message":"At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.","details":[{"code":"DeploymentScriptError","message":"The provided script failed with the following error:\r\nSystem.IO.FileNotFoundException: Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.\n\nFile name: 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'\n at System.Reflection.RuntimeAssembly.GetExportedTypes()\n at System.Reflection.Assembly.get_ExportedTypes()\n at System.Management.Automation.Runspaces.PSSnapInHelpers.GetAssemblyTypes(Assembly assembly, String name)\n at System.Management.Automation.Runspaces.PSSnapInHelpers.AnalyzeModuleAssemblyWithReflection(Assembly assembly, String name, PSSnapInInfo psSnapInInfo, PSModuleInfo moduleInfo, String helpFile, Dictionary2& cmdlets, Dictionary2& aliases, Dictionary2& providers)\n at System.Management.Automation.Runspaces.PSSnapInHelpers.AnalyzePSSnapInAssembly(Assembly assembly, String name, PSSnapInInfo psSnapInInfo, PSModuleInfo moduleInfo, Dictionary2& cmdlets, Dictionary2& aliases, Dictionary2& providers, String& helpFile)\n at System.Management.Automation.Runspaces.InitialSessionState.ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadBinaryModule(PSModuleInfo parentModule, Boolean trySnapInName, String moduleName, String fileName, Assembly assemblyToLoad, String moduleBase, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, String prefix, Boolean loadTypes, Boolean loadFormats, Boolean& found, String shortModuleName, Boolean disableFormatUpdates)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadBinaryModule(Boolean trySnapInName, String moduleName, String fileName, Assembly assemblyToLoad, String moduleBase, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, String prefix, Boolean loadTypes, Boolean loadFormats, Boolean& found)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModule(PSModuleInfo parentModule, String fileName, String moduleBase, String prefix, SessionState ss, Object privateData, ImportModuleOptions& options, ManifestProcessingFlags manifestProcessingFlags, Boolean& found, Boolean& moduleFileFound)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModuleNamedInManifest(PSModuleInfo parentModule, ModuleSpecification moduleSpecification, String moduleBase, Boolean searchModulePath, String prefix, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, Boolean loadTypesFiles, Boolean loadFormatFiles, Object privateData, Boolean& found, String shortModuleName, Nullable1 manifestLanguageMode)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModuleManifest(String moduleManifestPath, ExternalScriptInfo manifestScriptInfo, Hashtable data, Hashtable localizedData, ManifestProcessingFlags manifestProcessingFlags, Version minimumVersion, Version maximumVersion, Version requiredVersion, Nullable1 requiredModuleGuid, ImportModuleOptions& options, Boolean& containedErrors)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModuleManifest(ExternalScriptInfo scriptInfo, ManifestProcessingFlags manifestProcessingFlags, Version minimumVersion, Version maximumVersion, Version requiredVersion, Nullable1 requiredModuleGuid, ImportModuleOptions& options)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModule(PSModuleInfo parentModule, String fileName, String moduleBase, String prefix, SessionState ss, Object privateData, ImportModuleOptions& options, ManifestProcessingFlags manifestProcessingFlags, Boolean& found, Boolean& moduleFileFound)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadUsingExtensions(PSModuleInfo parentModule, String moduleName, String fileBaseName, String extension, String moduleBase, String prefix, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, Boolean& found, Boolean& moduleFileFound)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadUsingExtensions(PSModuleInfo parentModule, String moduleName, String fileBaseName, String extension, String moduleBase, String prefix, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, Boolean& found)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadUsingMultiVersionModuleBase(String moduleBase, ManifestProcessingFlags manifestProcessingFlags, ImportModuleOptions importModuleOptions, Boolean& found)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadUsingModulePath(PSModuleInfo parentModule, Boolean found, IEnumerable1 modulePath, String name, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, PSModuleInfo& module)\n at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadUsingModulePath(Boolean found, IEnumerable`1 modulePath, String name, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, PSModuleInfo& module)\n at Microsoft.PowerShell.Commands.ImportModuleCommand.ImportModule_LocallyViaName(ImportModuleOptions importModuleOptions, String name)\n at Microsoft.PowerShell.Commands.ImportModuleCommand.ImportModule_LocallyViaName_WithTelemetry(ImportModuleOptions importModuleOptions, String name)\n at Microsoft.PowerShell.Commands.ImportModuleCommand.ProcessRecord()\n at System.Management.Automation.Cmdlet.DoProcessRecord()\n at System.Management.Automation.CommandProcessor.ProcessRecord()\n\n\r\nat , /mnt/azscripts/azscriptinput/userscript.ps1: line 5\r\nat , : line 1\r\nat , /mnt/azscripts/azscriptinput/DeploymentScript.ps1: line 237. Please refer to https://aka.ms/DeploymentScriptsTroubleshoot for more deployment script information."}]}

Mrunamii218 commented 2 years ago

@edyoung Can i get an update on the above??

gui28347 commented 2 years ago

+1 facing same issue

Rich5 commented 2 years ago

+1 same issue