microsoftgraph / msgraph-sdk-powershell

Powershell SDK for Microsoft Graph
https://www.powershellgallery.com/packages/Microsoft.Graph
Other
696 stars 168 forks source link

Could not find the module 'Microsoft.Graph.Identity.SignIns' #763

Closed stvpwrs closed 3 years ago

stvpwrs commented 3 years ago

Hello,

I'm seeing the following error PowerShell 7.1.3 when trying to use the using module keyword:

Could not find the module 'Microsoft.Graph.Identity.SignIns'

This works: (but does not load classes to my knowledge) #requires -Modules @{ModuleName = "Microsoft.Graph.Identity.SignIns" ; RequiredVersion = "1.5.0"}

This works: (but does not load classes to my knowledge) Import-Module -Name Microsoft.Graph.Identity.SignIns

This fails: using module Microsoft.Graph.Identity.SignIns

In addition the classes in Microsoft.Graph.PowerShell.Models are also unable to be found, but often will load after some number of attempts or after running parts of a script.

Is there a way to make sure all of the classes in in Microsoft.Graph.PowerShell.Models are loaded into as script, and is there something different about Microsoft.Graph.Identity.SignIns that doesn't allow for using module?

AB#10218

stvpwrs commented 3 years ago

To expand on this a little more. In Azure Functions, I get Could not find the module 'Microsoft.Graph.Identity.SignIns' even though it's reported on being installed with Get-Module -ListAvailable to "Path": "C:\\home\\data\\ManagedDependencies\\210712190843508.r\\Microsoft.Graph.Identity.SignIns\\1.5.0\\Microsoft.Graph.Identity.SignIns.psd1"

On my local PC I'm also having issues finding it with Get-Module is there something special I should be doing to load this module?

peombwa commented 3 years ago

@stvpwrs This could be an issue with your installation. Please upgrade to the latest version of the SDK using Update-Module Microsoft.Graph then try again.

I'm able to import and use the latest version of Microsoft.Graph.Identity.SignIns in PowerShell 7.1.3 on my PC and in Azure Functions without any issues. See the log below:

# TestScript.ps1
using module Microsoft.Graph.Identity.SignIns

Write-Host "Authenticating..."
Connect-MgGraph

Write-Host "Calling 'Get-MgIdentityConditionalAccessPolicy'..."
$AccessPolicy = Get-MgIdentityConditionalAccessPolicy
Write-Host "Fetched $($AccessPolicy.count) CA policies of type $($AccessPolicy[0].GetType())."

$NewPolicy = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphConditionalAccessPolicy1
$NewPolicy.DisplayName = $AccessPolicy[0].DisplayName
Write-Host "Created new object with display name of: $($NewPolicy.DisplayName)."
Executing script in a PowerShell 7.1.3 session.

image

Running the same script as a HTTP trigger in Azure Functions.

image

Could you please share a script that we can use to reproduce this on our end?

stvpwrs commented 3 years ago

@peombwa thanks for the reply. I could understand that being an issue on my PC. I'm currently running into issues updating, but I don't know how that would happen in Azure Functions when I'm using the Managed Dependencies to get the Microsoft. Graph module.

The Azure Function code is:

using module Microsoft.Graph.Identity.SignIns
using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Information "PowerShell HTTP trigger function processed a request."

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $(Get-Module -ListAvailable | Select-Object Name, Path)
})

The result I get:

Connected!
2021-07-16T03:05:19  Welcome, you are now connected to log-streaming service. The default timeout is 2 hours. Change the timeout with the App Setting SCM_LOGSTREAM_TIMEOUT (in seconds).
2021-07-16T03:05:19.530 [Information] Executing 'Functions.New-ExternalGuestUserClassTest' (Reason='This function was programmatically called via the host APIs.', Id=95844cd8-7d4f-4c1f-93a3-37c0c61abf31)
2021-07-16T03:05:19.646 [Error] Executed 'Functions.New-ExternalGuestUserClassTest' (Failed, Id=95844cd8-7d4f-4c1f-93a3-37c0c61abf31, Duration=77ms)Result: FailureException: The script file 'C:\home\site\wwwroot\New-ExternalGuestUserClassTest\run.ps1' has parsing errors:Could not find the module 'Microsoft.Graph.Identity.SignIns'.Stack:    at Microsoft.Azure.Functions.PowerShellWorker.AzFunctionInfo.GetParameters(String scriptFile, String entryPoint, ScriptBlockAst& scriptAst) in /home/vsts/work/1/s/src/FunctionInfo.cs:line 170at Microsoft.Azure.Functions.PowerShellWorker.AzFunctionInfo..ctor(RpcFunctionMetadata metadata) in /home/vsts/work/1/s/src/FunctionInfo.cs:line 73at Microsoft.Azure.Functions.PowerShellWorker.FunctionLoader.LoadFunction(FunctionLoadRequest request) in /home/vsts/work/1/s/src/FunctionLoader.cs:line 52at Microsoft.Azure.Functions.PowerShellWorker.RequestProcessor.ProcessFunctionLoadRequest(StreamingMessage request) in /home/vsts/work/1/s/src/RequestProcessor.cs:line 222
2021-07-16T03:07:19  No new trace in the past 1 min(s).

The requirements.psd1 file:

# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
    # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'.
    # To use the Az module in your function app, please uncomment the line below.
    'Az.Accounts' = '2.*'
    'Microsoft.Graph.Authentication'= '1.*'
    'Microsoft.Graph.Identity.SignIns'= '1.*'
}

I have tried removing the current modules in the Azure Function and having them reinstalled by the Managed Dependencies feature. Same result.

I'm a bit at a loss on what could be getting corrupted across systems and causing this.

stvpwrs commented 3 years ago

Hey @peombwa I made a brand new Azure Function today. Entirely in the portal. Did not do any deployment from the local PC.

Made 2 change to 2 files.

Change 1 - Added using module Microsoft.Graph.Identity.SignIns to the top of the default run.ps1 file on an HttpTrigger.

using module Microsoft.Graph.Identity.SignIns
using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

# Interact with query parameters or the body of the request.
$name = $Request.Query.Name
if (-not $name) {
    $name = $Request.Body.Name
}

$body = "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."

if ($name) {
    $body = "Hello, $name. This HTTP triggered function executed successfully."
}

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $body
})

Change 2 - Added 'Microsoft.Graph.Authentication'= '1.*' and 'Microsoft.Graph.Identity.SignIns'= '1.*' to the requirements.psd1 file.

# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
    # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. 
    # To use the Az module in your function app, please uncomment the line below.
    # 'Az' = '6.*'
    'Microsoft.Graph.Authentication'= '1.*'
    'Microsoft.Graph.Identity.SignIns'= '1.*'
}

Starting the script in Test/Run resulted in the following error:

2021-07-16T14:01:21.699 [Information] Executing 'Functions.Test-Class' (Reason='This function was programmatically called via the host APIs.', Id=d657cf40-9e2a-4065-b301-e958dc8f4241)
2021-07-16T14:01:21.751 [Error] Executed 'Functions.Test-Class' (Failed, Id=d657cf40-9e2a-4065-b301-e958dc8f4241, Duration=9ms)Result: FailureException: The script file 'C:\home\site\wwwroot\Test-Class\run.ps1' has parsing errors:Could not find the module 'Microsoft.Graph.Identity.SignIns'.Stack:    at Microsoft.Azure.Functions.PowerShellWorker.AzFunctionInfo.GetParameters(String scriptFile, String entryPoint, ScriptBlockAst& scriptAst) in /home/vsts/work/1/s/src/FunctionInfo.cs:line 170at Microsoft.Azure.Functions.PowerShellWorker.AzFunctionInfo..ctor(RpcFunctionMetadata metadata) in /home/vsts/work/1/s/src/FunctionInfo.cs:line 73at Microsoft.Azure.Functions.PowerShellWorker.FunctionLoader.LoadFunction(FunctionLoadRequest request) in /home/vsts/work/1/s/src/FunctionLoader.cs:line 52at Microsoft.Azure.Functions.PowerShellWorker.RequestProcessor.ProcessFunctionLoadRequest(StreamingMessage request) in /home/vsts/work/1/s/src/RequestProcessor.cs:line 222

Going into KUDO I can confirm the modules were installed:

C:\home>
C:\home\data>
C:\home\data\ManagedDependencies>
C:\home\data\ManagedDependencies\210716135436371.r>
C:\home\data\ManagedDependencies\210716135436371.r\Microsoft.Graph.Identity.SignIns>
C:\home\data\ManagedDependencies\210716135436371.r\Microsoft.Graph.Identity.SignIns\1.6.1>
C:\home\data\ManagedDependencies\210716135436371.r\Microsoft.Graph.Identity.SignIns>
C:\home\data\ManagedDependencies\210716135436371.r>
C:\home\data\ManagedDependencies\210716135436371.r\Microsoft.Graph.Authentication>
C:\home\data\ManagedDependencies\210716135436371.r\Microsoft.Graph.Authentication\1.6.0> 
stvpwrs commented 3 years ago

Hey, trying to add more data points here. On a new Windows Server 2016 VM with a fresh install of PowerShell 7.1.3, Visual Studio Code, and Microsoft.Graph produces the same error.

Edition    Windows Server 2016 Standard
Version    1607
OS Build   14393.3750
Name                           Value
----                           -----
PSVersion                      7.1.3
PSEdition                      Core
GitCommitId                    7.1.3
OS                             Microsoft Windows 10.0.14393
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
Version: 1.58.2 (user setup)
Commit: c3f126316369cd610563c75b1b1725e0679adfb3
Date: 2021-07-14T22:10:15.214Z
Electron: 12.0.13
Chrome: 89.0.4389.128
Node.js: 14.16.0
V8: 8.9.255.25-electron.0
OS: Windows_NT x64 10.0.14393
    Directory: C:\Users\username\Documents\PowerShell\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Manifest   1.6.1                 Microsoft.Graph                     Core,Desk
Script     1.6.1                 Microsoft.Graph.Applications        Core,Desk {Add-MgApplicationKey, Add-MgApplicationPassword, Add-MgServicePrincipalKey, Add-MgServicePrincipalPassword…}
Script     1.6.0                 Microsoft.Graph.Authentication      Core,Desk {Connect-MgGraph, Disconnect-MgGraph, Get-MgContext, Get-MgProfile…}
Script     1.6.0                 Microsoft.Graph.Bookings            Core,Desk {Get-MgBookingBusiness, Get-MgBookingBusinessAppointment, Get-MgBookingBusinessCalendarView, Get-MgBookingBusinessCustomer…}
Script     1.6.0                 Microsoft.Graph.Calendar            Core,Desk {Get-MgGroupCalendar, Get-MgGroupCalendarMultiValueExtendedProperty, Get-MgGroupCalendarPermission, Get-MgGroupCalendarSingleValueExtendedProper…
Script     1.6.0                 Microsoft.Graph.ChangeNotifications Core,Desk {Get-MgSubscription, New-MgSubscription, Remove-MgSubscription, Update-MgSubscription}
Script     1.6.1                 Microsoft.Graph.CloudCommunications Core,Desk {Clear-MgCommunicationPresence, Get-MgCommunicationCall, Get-MgCommunicationCallAudioRoutingGroup, Get-MgCommunicationCallOperation…}
Script     1.6.1                 Microsoft.Graph.Compliance          Core,Desk {Add-MgComplianceEdiscoveryCaseReviewSetQueryTag, Add-MgComplianceEdiscoveryCaseReviewSetToReviewSet, Close-MgComplianceEdiscoveryCase, Export-M…
Script     1.6.0                 Microsoft.Graph.CrossDeviceExperie… Core,Desk {Get-MgUserActivity, Get-MgUserActivityHistoryItem, Get-MgUserActivityHistoryItemActivity, Get-MgUserActivityHistoryItemActivityByRef…}
Script     1.6.1                 Microsoft.Graph.DeviceManagement    Core,Desk {Get-MgDeviceManagement, Get-MgDeviceManagementAdvancedThreatProtectionOnboardingStateSummary, Get-MgDeviceManagementAdvancedThreatProtectionOnb…
Script     1.6.1                 Microsoft.Graph.DeviceManagement.A… Core,Desk {Add-MgDeviceManagementGroupPolicyUploadedDefinitionFileLanguageFile, Approve-MgDeviceManagementAndroidManagedStoreAccountEnterpriseSettingApp, …
Script     1.6.1                 Microsoft.Graph.DeviceManagement.A… Core,Desk {Get-MgDeviceManagementApplePushNotificationCertificate, Get-MgDeviceManagementAuditEvent, Get-MgDeviceManagementCartToClassAssociation, Get-MgD…
Script     1.6.0                 Microsoft.Graph.DeviceManagement.E… Core,Desk {Get-MgDeviceManagementAndroid, Get-MgDeviceManagementAndroidDeviceOwnerEnrollmentProfile, Get-MgDeviceManagementAppleUserInitiatedEnrollmentPro…
Script     1.6.0                 Microsoft.Graph.DeviceManagement.F… Core,Desk {Compare-MgDeviceManagementIntent, Compare-MgDeviceManagementTemplate, Compare-MgDeviceManagementTemplateMigratableTo, Confirm-MgDeviceManagemen…
Script     1.6.1                 Microsoft.Graph.Devices.CloudPrint  Core,Desk {Get-MgPrint, Get-MgPrintConnector, Get-MgPrintOperation, Get-MgPrintPrinter…}
Script     1.6.1                 Microsoft.Graph.Devices.CorporateM… Core,Desk {Clear-MgDeviceAppMgtWindowInformationProtectionDeviceRegistration, Get-MgDeviceAppMgt, Get-MgDeviceAppMgtAndroidManagedAppProtection, Get-MgDev…
Script     1.6.0                 Microsoft.Graph.DirectoryObjects    Core,Desk {Confirm-MgDirectoryObjectMemberGroup, Confirm-MgDirectoryObjectMemberObject, Get-MgDirectoryObject, Get-MgDirectoryObjectAvailableExtensionProp…
Script     1.6.1                 Microsoft.Graph.Education           Core,Desk {Get-MgEducationClass, Get-MgEducationClassAssignment, Get-MgEducationClassAssignmentCategory, Get-MgEducationClassAssignmentDefault…}
Script     1.6.1                 Microsoft.Graph.Files               Core,Desk {Add-MgDriveListContentTypeBaseTypeCopy, Add-MgDriveListContentTypeCopy, Add-MgShareListContentTypeBaseTypeCopy, Add-MgShareListContentTypeCopy…}
Script     1.6.0                 Microsoft.Graph.Financials          Core,Desk {Get-MgFinancial, Get-MgFinancialCompany, Get-MgFinancialCompanyAccount, Get-MgFinancialCompanyAgedAccountPayable…}
Script     1.6.1                 Microsoft.Graph.Groups              Core,Desk {Add-MgGroupFavorite, Add-MgGroupToLifecyclePolicy, Confirm-MgGroupGrantedPermission, Confirm-MgGroupMemberGroup…}
Script     1.6.1                 Microsoft.Graph.Identity.Directory… Core,Desk {Confirm-MgAdministrativeUnitMemberGroup, Confirm-MgAdministrativeUnitMemberObject, Confirm-MgContactMemberGroup, Confirm-MgContactMemberObject…}
Script     1.6.1                 Microsoft.Graph.Identity.Governance Core,Desk {Add-MgAccessReviewDecision, Get-MgAccessReview, Get-MgAccessReviewDecision, Get-MgAccessReviewInstance…}
Script     1.6.1                 Microsoft.Graph.Identity.SignIns    Core,Desk {Confirm-MgRiskyUserCompromised, Get-MgDataPolicyOperation, Get-MgIdentityConditionalAccessAuthenticationContextClasserenceByRef, Get-MgIdentity…
Script     1.6.0                 Microsoft.Graph.Mail                Core,Desk {Get-MgUserInferenceClassification, Get-MgUserInferenceClassificationOverride, Get-MgUserMailFolder, Get-MgUserMailFolderChildFolder…}
Script     1.6.0                 Microsoft.Graph.Notes               Core,Desk {Get-MgGroupOnenoteNotebook, Get-MgGroupOnenoteNotebookSection, Get-MgGroupOnenoteNotebookSectionGroup, Get-MgGroupOnenoteOperation…}
Script     1.6.0                 Microsoft.Graph.People              Core,Desk {Get-MgUserActivityStatistics, Get-MgUserLastSharedMethodInsight, Get-MgUserPerson, Get-MgUserProfile…}
Script     1.6.0                 Microsoft.Graph.PersonalContacts    Core,Desk {Get-MgUserContact, Get-MgUserContactExtension, Get-MgUserContactFolder, Get-MgUserContactFolderChildFolder…}
Script     1.6.0                 Microsoft.Graph.Planner             Core,Desk {Get-MgGroupPlanner, Get-MgGroupPlannerPlan, Get-MgGroupPlannerPlanBucket, Get-MgGroupPlannerPlanBucketTask…}
Script     1.6.0                 Microsoft.Graph.Reports             Core,Desk {Get-MgAuditLogDirectoryAudit, Get-MgAuditLogDirectoryProvisioning, Get-MgAuditLogProvisioning, Get-MgAuditLogRestrictedSignIn…}
Script     1.6.0                 Microsoft.Graph.SchemaExtensions    Core,Desk {Get-MgSchemaExtension, New-MgSchemaExtension, Remove-MgSchemaExtension, Update-MgSchemaExtension}
Script     1.6.1                 Microsoft.Graph.Search              Core,Desk {Get-MgExternal, Get-MgExternalConnection, Get-MgSearchEntity, Invoke-MgQuerySearch…}
Script     1.6.1                 Microsoft.Graph.Security            Core,Desk {Get-MgSecurityAction, Get-MgSecurityAlert, Get-MgSecurityCloudAppSecurityProfile, Get-MgSecurityDomainSecurityProfile…}
Script     1.6.1                 Microsoft.Graph.Sites               Core,Desk {Add-MgSiteContentTypeBaseTypeCopy, Add-MgSiteContentTypeCopy, Add-MgSiteListContentTypeBaseTypeCopy, Add-MgSiteListContentTypeCopy…}
Script     1.6.1                 Microsoft.Graph.Teams               Core,Desk {Add-MgChatMember, Add-MgTeamChannelMember, Add-MgTeamMember, Add-MgTeamPrimaryChannelMember…}
Script     1.6.1                 Microsoft.Graph.Users               Core,Desk {Get-MgUser, Get-MgUserCreatedObject, Get-MgUserCreatedObjectByRef, Get-MgUserDirectReport…}
Script     1.6.1                 Microsoft.Graph.Users.Actions       Core,Desk {Add-MgUserInsightSharedLastSharedMethodMicrosoftGraphWorkbookRange, Add-MgUserInsightSharedLastSharedMethodMicrosoftGraphWorkbookRangeSort, Add…
Script     1.6.1                 Microsoft.Graph.Users.Functions     Core,Desk {Export-MgUserDeviceAndAppManagementData623C, Export-MgUserDeviceAndAppManagementDataD390, Find-MgUserRoomAc49, Find-MgUserRoomD266…}
Script     1.6.0                 Microsoft.Graph.WindowsUpdates      Core,Desk {Add-MgWindowsUpdatesDeploymentAudienceMember, Add-MgWindowsUpdatesDeploymentAudienceMemberById, Add-MgWindowsUpdatesUpdatableAssetMember, Add-M…
stvpwrs commented 3 years ago

Edit; Added a few other observations. Update - So if I try to load the module from the .psm1 file I get the following error:

Import-Module 'C:\Users\username\OneDrive\Documents\PowerShell\Modules\Microsoft.Graph.Identity.SignIns\1.6.1\Microsoft.Graph.Identity.SignIns.psm1'

PS C:\Users\username> InvalidOperation: C:\Users\username\Documents\PowerShell\Modules\Microsoft.Graph.Identity.SignIns\1.6.1\Microsoft.Graph.Identity.SignIns.psm1:7:27
Line |
   7 |  … ofileName = [Microsoft.Graph.PowerShell.Authentication.GraphSession]: …   
     |                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      
     | Unable to find type [Microsoft.Graph.PowerShell.Authentication.GraphSession].

This following code works


Select-MgProfile -Name beta
Import-Module 'C:\Users\username\OneDrive\Documents\PowerShell\Modules\Microsoft.Graph.Identity.SignIns\1.6.1\Microsoft.Graph.Identity.SignIns.psm1'

This seems to be a dependency import issue? I have never seen a PowerShell module behave like this so I'm a bit lost.

stvpwrs commented 3 years ago

Trying to get an update on this. Is this expected behavior for module importing? I would expect that Import-Module and using module would handle required modules during the import process.

peombwa commented 3 years ago

I'll address the issues above in three parts:

Azure Function

You don't need to import a module that has already been specified in your requirements.psd1 unless you need to load a specific version of a module. Installed modules are automatically imported to the session when you use any commands in the module. If you need to import a module explicitly, then use Import-Module Microsoft.Graph.Identity.SignIns and it to your profile.ps1 file, see https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-powershell?tabs=portal#target-specific-versions.

Use of using module statement

A using module statement specifies the namespaces used in your session by importing classes from the root module. It doesn't import classes that are defined in the nested modules hence the error message, see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_using?view=powershell-7.1#module-syntax. Always use Import-Module {MODULE_NAME} when loading PowerShell modules.

Import-Module "PATH/.psm1" (script module)

Our modules specify their dependency in the module manifest (.psd1), which PowerShell uses to load all the required modules - https://github.com/microsoftgraph/msgraph-sdk-powershell/blob/dev/src/Identity.SignIns/Identity.SignIns/Microsoft.Graph.Identity.SignIns.psd1#L54. Trying to import a module using a .psm1 isn't recommended since it bypasses the module manifest. It would be best if you ideally used Import-Module {MODULE_NAME} to import modules instead. Always use a .psd1 if you have to import a module from a path. See https://docs.microsoft.com/en-us/powershell/scripting/developer/module/how-to-write-a-powershell-module-manifest?view=powershell-7.1#module-manifest-elements.

By using Import-Module Microsoft.Graph.Identity.SignIns, I've been able to use the module in both Windows Server 2016 and Azure Functions without any issue.

Windows Server 2016

image

Azure Functions

image

stvpwrs commented 3 years ago

@peombwa Thank you for the long and detailed reply. This information has been very helpful. I've also been able to help solve some of my experienced issues by better configuring the profile.ps1 both in Azure and locally.

It is unfortunate that using module is not feasible with this module. I would think even #requires would also have issues with the way a profile switch is used for the beta API. There are certainly times when using module is the ideal way of loading a module into a script.

I understand the amount of work that goes into a module like this is not insignificant. It would be ideal if the module could be treated like any other PowerShell module and use all the features available to PowerShell.