Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

M365DSC Azure Automation Account Runbook - The term 'Connect-M365Tenant' is not recognized #5350

Open
dergint opened this issue Nov 6, 2024 · 5 comments

Comments

@dergint
Copy link

dergint commented Nov 6, 2024

Description of the issue

Hi,

I have an Azure Automation Account runbook and it runs the following command. I have not included all the variables but all certs etc all working fine.
The runtime environment is Powershell 5.1 and installed the powershell module M365DSC 1.24.1016.1 on the runbook environment.

It fails on the following line
Export-M365DSCConfiguration -Components @("SCDLPComplianceRule") -ApplicationId $AppId -CertificateThumbprint $Cert.Thumbprint -TenantId $TenantId -path $path -filename "purviewdlpconfig_$Date.ps1"

with below error. Not sure why it is not recognising this command assuming it would be part of the M365DSC module.
Write-Error: Failed to export M365DSC configuration: The term 'Connect-M365Tenant' is not recognized as a name of a cmdlet

Any help would be appreciated.

Microsoft 365 DSC Version

1.24.1016.1

Which workloads are affected

Security & Compliance Center

The DSC configuration

#AutomationAccountConnection
try {
"Logging in to Azure..."
Connect-AzAccount -Identity
}
catch {
Write-Error -Message $.Exception
throw $
.Exception
}

Define storage account and container details

$storageAccountName = "azuresssssss"
$containerName = "automasssss"

Get the storage account context using the managed identity

$storageAccount = Get-AzStorageAccount -ResourceGroupName "Azurexxxxxx" -Name $storageAccountName
$storageContext = $storageAccount.Context

#Variables for Certificate
$cert = Get-AutomationCertificate -Name 'Azusdfsafasdfasdf'
$CertName = "Azurssssssss"

Retrieve the certificate from Azure Automation

try {
Write-Output "Getting Certificate Thumbprint"
$Cert = Get-AutomationCertificate -Name $CertName
Write-Output "Certificate Thumbprint: $($Cert.Thumbprint)"
Write-Output "Has Private Key: $($Cert.HasPrivateKey)"
}
catch {
Write-Error "Failed to connect to Certificate Thumbprint: $_"
exit
}

Variables for Files and Folders

$path = "$env:TEMP"
$Date = $(Get-Date -f yyyy-MMM-dd-HHMMtt)

Variables for App Registration

$AppId = "18a34eeww-d5sdafasdfasdfadsf"
$OrgName = "xxxxxx.onmicrosoft.com"
$TenantID = "xxxxxx.onmicrosoft.com"

#Start Exporting M365DSC Configuration and creating file
try {
"Exporting M365DSC Configuration"
Export-M365DSCConfiguration -Components @("SCDLPComplianceRule") -ApplicationId $AppId -CertificateThumbprint $Cert.Thumbprint -TenantId $TenantId -path $path -filename "purviewdlpconfig_$Date.ps1"
}
catch {
Write-Error "Failed to export M365DSC configuration: $_"
exit
}

$fileName = "$path\purviewdlpconfigreport_$Date.json"

#Start creating M365DSC report file from configuration file stored in Temp
try {
"Creating M365DSC report from the configuration file and store to temp file as json"
New-M365DSCReportFromConfiguration -Type JSON -ConfigurationPath "$path\purviewdlpconfig_$Date.ps1" -OutputPath "$fileName"
}
catch {
Write-Error "Failed to generate DSC report: $_"
exit
}

$tempFilePath = $fileName

Check if file exists and upload JSON file to Blob Storage

if (Test-Path -Path $tempFilePath) {
try {
Set-AzStorageBlobContent -File $tempFilePath -Container $containerName -Blob $fileName -Context $storageContext
Write-Output "JSON output uploaded to Blob Storage as $fileName"
}
catch {
Write-Error "Failed to upload JSON file to Blob Storage: $_"
throw
}
}
else {
Write-Error "The file $tempFilePath does not exist. Check if the Export-M365DSCConfiguration command completed successfully."
}

Verbose logs showing the problem

Verbose
Exception calling "SourceExists" with "1" argument(s): "The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security, State."
06/11/2024, 7:09:01 pm
Verbose
Could not write to event log Source {M365DSCReverse::Test-M365DSCModuleValidity} EntryType {Information} Message {Exception calling "ShouldContinue" with "2" argument(s): "A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or 'C:\Users\ContainerUser\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install and import the NuGet provider now?"} { Exception calling "SourceExists" with "1" argument(s): "The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security, State." } \ at Add-M365DSCEvent, C:\usr\src\PSModules\Microsoft365DSC\Modules\M365DSCLogEngine.psm1: line 193 \ at Start-M365DSCConfigurationExtract, C:\usr\src\PSModules\Microsoft365DSC\Modules\M365DSCReverse.psm1: line 107 \ at Export-M365DSCConfiguration, C:\usr\src\PSModules\Microsoft365DSC\Modules\M365DSCUtil.psm1: line 1460 \ at , : line 47
06/11/2024, 7:09:01 pm
Verbose
Exception calling "SourceExists" with "1" argument(s): "The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security, State."
06/11/2024, 7:09:01 pm
Verbose
Could not write to event log Source {[M365DSCLogEngine]} EntryType {Error} Message {Could not write to event log Source {M365DSCReverse::Test-M365DSCModuleValidity} EntryType {Information} Message {Exception calling "ShouldContinue" with "2" argument(s): "A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or 'C:\Users\ContainerUser\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install and import the NuGet provider now?"} { Exception calling "SourceExists" with "1" argument(s): "The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security, State." } \ at Add-M365DSCEvent, C:\usr\src\PSModules\Microsoft365DSC\Modules\M365DSCLogEngine.psm1: line 193 \ at Start-M365DSCConfigurationExtract, C:\usr\src\PSModules\Microsoft365DSC\Modules\M365DSCReverse.psm1: line 107 \ at Export-M365DSCConfiguration, C:\usr\src\PSModules\Microsoft365DSC\Modules\M365DSCUtil.psm1: line 1460 \ at , : line 47}
06/11/2024, 7:09:07 pm
Verbose
Access denied
06/11/2024, 7:09:07 pm
Verbose
Error Log created at {file://C:/app/1348-M365DSC-ErrorLog.log}
06/11/2024, 7:09:07 pm
Verbose
Loading module from path 'C:\usr\src\PSModules\Microsoft365DSC\DSCResources\MSFT_SCDLPComplianceRule\MSFT_SCDLPComplianceRule.psm1'.
06/11/2024, 7:09:07 pm
Verbose
Exporting function 'Get-TargetResource'.
06/11/2024, 7:09:07 pm
Verbose
Exporting function 'Set-TargetResource'.
06/11/2024, 7:09:07 pm
Verbose
Exporting function 'Test-TargetResource'.
06/11/2024, 7:09:07 pm
Verbose
Exporting function 'Export-TargetResource'.
06/11/2024, 7:09:07 pm
Verbose
Importing function 'Export-TargetResource'.
06/11/2024, 7:09:07 pm
Verbose
Importing function 'Get-TargetResource'.
06/11/2024, 7:09:07 pm
Verbose
Importing function 'Set-TargetResource'.
06/11/2024, 7:09:07 pm
Verbose
Importing function 'Test-TargetResource'.
06/11/2024, 7:09:07 pm
Verbose
Attempting connection to {MicrosoftGraph} with:
06/11/2024, 7:09:07 pm
Verbose
Name Value ---- ----- CertificatePath CertificateThumbprint 9xxxxxxxxxxxx8 ApplicationSecret ApplicationId 18xxxxxxxxxxxxxt TenantId xxxxxx.onmicrosoft.com
06/11/2024, 7:09:07 pm
Verbose
Initializing the Connected To Workloads List.
06/11/2024, 7:09:07 pm
Verbose
ApplicationId, TenantId, CertificateThumbprint were specified. Connecting via Service Principal
06/11/2024, 7:09:07 pm
Verbose
Calling into Connect-M365Tenant

Write-Error: Failed to export M365DSC configuration: The term 'Connect-M365Tenant' 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.

Environment Information + PowerShell Version

No response

@ricmestre
Copy link
Contributor

Connect-M365Tenant is not from M365DSC but from MSCloudLoginAssistant, if you're getting that error message it means you don't have that module installed and most likely all the remaining M365DSC's dependencies as well.

@dergint
Copy link
Author

dergint commented Nov 7, 2024

Connect-M365Tenant is not from M365DSC but from MSCloudLoginAssistant, if you're getting that error message it means you don't have that module installed and most likely all the remaining M365DSC's dependencies as well.

Thanks. I will install this try. do you recommend to run Update-M365DSCDependencies within the runbook script to update the dependencies or pick them up and install them on runbook runtime in Azure Portal

@ricmestre
Copy link
Contributor

Entirely up to you, but to save time running the script I'd install them before in the runtime.

@dergint
Copy link
Author

dergint commented Nov 7, 2024

Entirely up to you, but to save time running the script I'd install them before in the runtime.

Right. I have imported all the modules it does/may need and run this and it is failing with some unknown error. I have simplified the script to eliminate any other issues but it is failing with this error "Failed to export M365DSC configuration: An error has occurred. + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException"

Below is the full export of the log

#Variables for Certificate $cert = Get-AutomationCertificate -Name 'Azurexxxxxxxx' $CertName = "Azurexxxxxxx" # Retrieve the certificate from Azure Automation try { Write-Output "Getting Certificate Thumbprint" $Cert = Get-AutomationCertificate -Name $CertName Write-Output "Certificate Thumbprint: $($Cert.Thumbprint)" Write-Output "Has Private Key: $($Cert.HasPrivateKey)" } catch { Write-Error "Failed to connect to Certificate Thumbprint: $" exit } # Variables for Files and Folders $path = "$env:TEMP" $Date = $(Get-Date -f yyyy-MMM-dd-HHMMtt) # Variables for App Registration $AppId = "18xxxxxxxxxxxxxxxe" $OrgName = "xxxxxxx.onmicrosoft.com" $TenantID = "xxxxxxxx.onmicrosoft.com" #Start Exporting M365DSC Configuration and creating file try { "Exporting M365DSC Configuration" Export-M365DSCConfiguration -Components @("SCDLPComplianceRule") -ApplicationId $AppId -CertificateThumbprint $Cert.Thumbprint -TenantId $TenantId -path $path -filename "purviewdlpconfig$Date.ps1" } catch { Write-Error "Failed to export M365DSC configuration: $" exit } $fileName = "$path\purviewdlpconfigreport$Date.html" #Start creating M365DSC report file from configuration file stored in Temp try { "Creating M365DSC report from the configuration file and store to temp file as json" New-M365DSCReportFromConfiguration -Type HTML -ConfigurationPath "$path\purviewdlpconfig_$Date.ps1" -OutputPath "$fileName" } catch { Write-Error "Failed to generate DSC report: $_" exit } Write-Output $fileName : Failed to export M365DSC configuration: An error has occurred. + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException


Below is the script

Variables for Certificate
$cert = Get-AutomationCertificate -Name 'Azurexxxxxxxxx'
$CertName = "Azurexxxxxx"

Retrieve the certificate from Azure Automation

try {
Write-Output "Getting Certificate Thumbprint"
$Cert = Get-AutomationCertificate -Name $CertName
Write-Output "Certificate Thumbprint: $($Cert.Thumbprint)"
Write-Output "Has Private Key: $($Cert.HasPrivateKey)"
}
catch {
Write-Error "Failed to connect to Certificate Thumbprint: $_"
exit
}

Variables for Files and Folders

$path = "$env:TEMP"
$Date = $(Get-Date -f yyyy-MMM-dd-HHMMtt)

Variables for App Registration

$AppId = "18xxxxxxxxxxxxxx"
$OrgName = "xxxxxxx.onmicrosoft.com"
$TenantID = "xxxxxxxx.onmicrosoft.com"

#Start Exporting M365DSC Configuration and creating file
try {
"Exporting M365DSC Configuration"
Export-M365DSCConfiguration -Components @("SCDLPComplianceRule") -ApplicationId $AppId -CertificateThumbprint $Cert.Thumbprint -TenantId $TenantId -path $path -filename "purviewdlpconfig_$Date.ps1"
}
catch {
Write-Error "Failed to export M365DSC configuration: $_"
exit
}

$fileName = "$path\purviewdlpconfigreport_$Date.html"

#Start creating M365DSC report file from configuration file stored in Temp
try {
"Creating M365DSC report from the configuration file and store to temp file as json"
New-M365DSCReportFromConfiguration -Type HTML -ConfigurationPath "$path\purviewdlpconfig_$Date.ps1" -OutputPath "$fileName"
}
catch {
Write-Error "Failed to generate DSC report: $_"
exit
}

Write-Output $fileName


Any advice? I am starting to wonder if trying to export DLPcompliance rules using Azure autmoation account is suitable way to do this. Not sure if the root issue is the Connect-IPPSsession

@FabienTschanz
Copy link
Contributor

To have a better understanding where it's failing, we need more information. Unfortunately, you are masking the error with your try / catch block, so what you can do is to write down the entire error object in your Write-Error statement: Write-Error "Failed to export M365DSC configuration: $($_ | ConvertTo-Json -Depth 20)". That way, we should be able to get every information from the error statement.

Additionally, you can run the Export-M365DSCConfiguration with the -Verbose switch and enable the Verbose logging on the runbook. Then you should be able to view the verbose statements. Maybe you need to set the $VerbosePreference to Continue instead of SilentlyContinue though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants