Recent Discussions
External Access Policy - CsExternalAccessPolicy e CsTenantFederationConfiguration (PowerShell)
Hello, community. We are trying to enable functionality regarding the creation of external access policies using the New-CsExternalAccessPolicy (CommunicationWithExternalOrgs) and Set-CsTenantFederationConfiguration (CustomizeFederation) commands. However, we are receiving the following error: Set-CsTenantFederationConfiguration : Customize Federation is not allowed to enable in your tenant. In line:1 character:1 + Set-CsTenantFederationConfiguration -CustomizeFederation $true + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: ({ ConfigType = ...Configuration }:<>f__AnonymousType104`5) [Set-CsTenantFederationConfiguration], Exception + FullyQualifiedErrorId : ClientError,Microsoft.Teams.ConfigApi.Cmdlets.SetCsTenantFederationConfiguration Is it necessary to do something first? We are following the documentation below: https://learn.microsoft.com/en-us/microsoftteams/trusted-organizations-external-meetings-chat?tabs=organization-settings TKS!10Views0likes0CommentsHelp In Editing Data Source Credentials in PowerShell for Power BI Embedded Dashboards in D365 CRM
Hello, We are currently migrating Power BI embedded dashboards from one Dynamics 365 CRM tenant to another. The process involves creating a new Power BI report within a workspace. Since the Dynamics 365 Solution does not support the inclusion of Power BI reports within unmanaged solutions, we have resorted to using PowerShell scripting to manage the migration. During this migration, we encountered an issue where the report IDs from the original environment remained linked when moving the Power BI embedded dashboards to the new environment. To address this, we have utilized Environment Variables to map the new report and workspace IDs appropriately. However, we are facing an issue when attempting to edit the Data Source Credentials using PowerShell scripting. Specifically, we are receiving a "Bad Request" error, as shown in the screenshot below. Here is the PowerShell code we are currently using to edit the Data Source Credentials: Connect-PowerBIServiceAccount $accesstoken = Get-PowerBIAccessToken $patchBody = '"credentialDetails": { "credentials": {"accessToken":"'+$($accesstoken)+'"}, "encryptedConnection": "Encrypted", "encryptionAlgorithm": "None", "privacyLevel": "Organizational", "useEndUserOAuth2Credentials": true }' Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/gateways/9eaed562-e9c2-46e4-91cf-276ed0947b41/datasources/f1181856-de29-4a9a-a555-a0e181cd7898" -Method Patch -Body $patchBody We would greatly appreciate any guidance or suggestions on resolving this error in the PowerShell scripting process for updating the Data Source Credentials. Thanks! Inogic Professional Services: Power Platform/Dynamics 365 CRM An expert technical extension for your techno-functional business needs Drop an email at email address removed for privacy reasons Service: https://www.inogic.com/services/ Tips and Tricks: https://www.inogic.com/blog/13Views0likes0CommentsPowerShell 7.4 SharePoint Question
Hi everyone, I’m seeking assistance with constructing a PowerShell script to manage document versions and space on multiple SharePoint sites. My goal is to: Connect to various SharePoint sites. Delete older copies of documents to free up space. Update version history settings to ensure future document control. Pull the list of SharePoint sites from a CSV file to handle multiple sites at once. Produce a log at the end of the script execution. I’ve encountered challenges with consistent authentication methods, having tried PnP PowerShell and SharePoint REST API. I would appreciate guidance on the best approach for handling credentials and login within the script. Any advice or examples would be greatly appreciated! Thank you in advance for your help.11Views0likes0CommentsInternal Server Error when Setting Mailbox properties
I have a Power shell script to setting Mailbox properties below Notes, Mail Tip, Seniority Index, etc It always run good, but today shows the error below >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> You want to perform this operation? User ID: "MB001.onmicrosoft.com" Y(Yes) You want to perform this operation? User ID: "MB001.onmicrosoft.com" Y(Yes) MB001.onmicrosoft.com Resource setting completed. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> You want to perform this operation? User ID: "MB002.onmicrosoft.com" Y(Yes) You want to perform this operation? User ID: "MB002.onmicrosoft.com" Y(Yes) MB002.onmicrosoft.com Resource setting completed. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> loop.......... >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Then I check all the Mailbox properties, the all settings is correct looks no problem. What kind of error could be possible? Is there any solutions? Any information will be appreciated!22Views0likes1CommentBulk update Azure AD with user attributes from CSV
I am looking for a way to update user attributes (OfficePhone and Department) for about 500 users from a CSV to AzureAD using a powershell. Does anyone know of a script that I could use? I am new here and if I have not given enough information, please let me know. I tried using Set-AzureADUser piping records using a foreach statement from a csv that I imported, but it was throwing up errors. Thanks! JacobSolved195KViews4likes71CommentsAdding External Users in-bulk to: Microsoft Teams & Private Channel(s) within the Team
We have a customer who requires over 350 external users (their customers) to be added / invited into a Team which has been created. "Half" of the users need to be added into "private channel a", and the other "Half" need to be added into "private channel b". We have attempted to add the users via various PowerShell scripts, however none of these scripts that we have been provided with have worked for various reasons. I have been unable to locate any native methods for this within the MS 365 admin centre, therefore believe that the only way to achieve this is by PowerShell scripting. Example of the most recent script we have is as follows, omitting the creation of the private channel(s) as they have already been created - see below: We require assistance with the actual script itself to: Add users into the team from a CSV of their email addresses. Assign the users to the correct private channel. Note - users will be added in 2 batches - 1 per private channel, so we just require scripting that can be modified to achieve this. # Install the Microsoft Teams PowerShell Module Install-Module -Name PowerShellGet -Force -AllowClobber Install-Module -Name MicrosoftTeams -Force -AllowClobber # Connect to Microsoft Teams Connect-MicrosoftTeams # Define the team name and path to the CSV file $teamName = "Your Team Name" $csvPath = "C:\path\to\your\users.csv" # Get the GroupId of the team $team = Get-Team -DisplayName $teamName $groupId = $team.GroupId # Import users from the CSV file $users = Import-Csv $csvPath # Add external users to the team foreach ($user in $users) { Add-TeamUser -GroupId $groupId -User $user.Email } # Define the private channel name $privateChannelName = "Private Channel Name" # Create the private channel New-TeamChannel -GroupId $groupId -DisplayName $privateChannelName -MembershipType Private # Get the ChannelId of the private channel $channel = Get-TeamChannel -GroupId $groupId -DisplayName $privateChannelName $channelId = $channel.Id # Add users to the private channel foreach ($user in $users) { Add-TeamChannelUser -GroupId $groupId -User $user.Email -ChannelId $channelId }17Views0likes0CommentsHyper-V orphaned or unnecceasry file script
I am trying to create a script that I can run against a Hyper-V cluster or host that can scan and identify orphaned files or files that are unused. THe idea is to clean up a cluster that has a lot of messy files because of migrations, or failed backups, snapshots, etc.34Views0likes3CommentsHow to remove Google Meet links and add Teams links in all recently migrated calendar events?
Hello, we have just finished migrating our company from Google Workspace to O365. Things went more or less smoothly, but now we're noticing that all of our migrated calendar events still have the Google Meet link associated with them. Is there a way to bulk remove all Google Meet links from all of our calendar items and replace them with Teams links? Many thanks in advance!9Views0likes0CommentsMicrosoft Purview (DLP Policy via PowerShell)
Hello, I created a DLP policy within Microsoft Purview centered around Microsoft teams to block external users outside of my organization from sending/receiving sensitive data over teams, but the condition was set to block everyone per my PowerShell script. Any suggestions would be helpful. I want the condition/action to block those individuals outside of my organization not everyone. Which script would be appropriate to block only people outside of my organization. I tried several forums, but I still can't get the script to switch from everyone to block only people ouside of my organization.49Views0likes1Commentfind the azure vm status in multiple subscription
We have multiple subscription (more than 10) in our environment and MFA enabled , I was trying to find one vm status using the name but its not working , setting azcontext with tenant ID also not working , I need command to set all subscription as context and find the vm status or any other way to find the vm status , this is needed for daily work, appreciate someone help on this .8Views0likes0CommentsUnable to update help in MS PowerShell
Dear community, I have just started learning Microsoft PowerShell, so I apologize in advance in case my problem turns out to be too trivial. I have Windows 10 (Version 10.0.15063) installed on my virtual machine. PSVersion 5.1.15063.0 When trying to run Update-Help (in Administrator privilege) the process finished with multiple errors. PS C:\> Update-Help Update-Help : Failed to update Help for the module(s) "AppBackgroundTask, AppvClient, AssignedAccess, BitsTransfer, CimCmdlets, Defender, DnsClient, iSCSI, ISE, Microsoft.PowerShell.Archive, Microsoft.PowerShell.Core, Microsoft.PowerShell.Diagnostics, Microsoft.PowerShell.Host, Microsoft.PowerShell.LocalAccounts, Microsoft.PowerShell.Management, Microsoft.PowerShell.ODataUtils, Microsoft.PowerShell.Operation.Validation, Microsoft.PowerShell.Security, Microsoft.PowerShell.Utility, Microsoft.WSMan.Management, NetAdapter, NetEventPacketCapture, NetLbfo, NetNat, NetQos, NetSwitchTeam, NetTCPIP, PackageManagement, PowerShellGet, PSReadline, PSScheduledJob, PSWorkflow, PSWorkflowUtility, ScheduledTasks, Storage, TLS, UEV, WindowsDeveloper License, WindowsErrorReporting, WindowsSearch" with UI culture(s) {ru-RU}: Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again. At line:1 char:1 + Update-Help + ~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Update-Help], Exception + FullyQualifiedErrorId : UnableToConnect,Microsoft.PowerShell.Commands.UpdateHelpCommand Update-Help : Failed to update Help for the module(s) "PSDesiredStateConfiguration, VpnClient" with UI culture(s) {ru-RU}: Unable to retrieve the HelpInfo XML file for UI culture en-US. Make sure the HelpInfoUri property in the module manifest is valid or check your network connection and then try the command again. At line:1 char:1 + Update-Help + ~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [Update-Help], Exception + FullyQualifiedErrorId : UnableToRetrieveHelpInfoXml,Microsoft.PowerShell.Commands.UpdateHelpCommand I would be extremely grateful if anyone could help me deal with this issue!104Views0likes2CommentsAccess denied when I want create to File in Powershell
Hi, Please, your help me! I have problem to access denied, when i want create to file. I have the account in the group administrator. I valued the permission in the tab security and i have administrator permission. PS U:\> $cre | Export-Clixml -Path C:\ Export-Clixml : Acceso denegado a la ruta de acceso 'C:\'. En línea: 1 Carácter: 8 + $cre | Export-Clixml -Path C:\ + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (:) [Export-Clixml], UnauthorizedAccessException + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ExportClixmlCommand Regards. #PowerShellSolved63KViews1like7CommentsMicrosoft Graph Sign in Log Script
Hi all, I'm trying to create a script that will check sign ins based on the location. How ever the location always appears as 'Microsoft.Graph.PowerShell.Models.MicrosoftGraphSignInLocation'. I am able to see the location if I select the property 'location' by itself and expand the property, but then that only show's a list of the locations. If I add other properties, it either doesn't work or it displays like this: I tried exporting as a csv and the location column values showed up as 'Microsoft.Graph.PowerShell.Models.MicrosoftGraphSignInLocation'. This is what I have currently: Get-MgAuditLogSignIn -Filter "location/countryOrRegion eq 'AU'" -Top 10 | format-list And if I try selecting properties (I would add more properties later, this is just an example: $properties = 'location, userprincipalname' Get-MgAuditLogSignIn -All -Filter "location/countryOrRegion eq 'AU'" -Top 10 -Property $properties | Select -ExpandProperty $properties Has anyone tried something similar?Solved74Views1like3Commentsdownload data from web
Hi everyone I need to download a bunch of files from a website: https://www.finra.org/finra-data/browse-catalog/equity-short-interest/files The address doesn't show the filters that need to be applied. If you go to that website and select 'Any' for both Month and Year then you will see all the files. Can someone help me with creating the PowerShell script to download all the files to a local folder on my machine? Thank you cc: LainRobertsonSolved54Views0likes3CommentsAdd parent team in a shared channel with powershell
Hello, I'm trying to add the team, where my shared channel is, as a member oh this channel but I can't find the good command. The last one I used is : $TeamGrouId = "000-000-000-000" #ID de l'équipe concernée $Channel = "Mon canal partagé" $channelID = (Get-TeamChannel -GroupId $TeamGroupId | Where-Object { $_.DisplayName -Like $Channel}).Id $paramstest = @{ "@odata.type" = "microsoft.graph.aadUserConversationMember" roles = @("member") "*** Adresse électronique supprimée pour cause de confidentialité ***" = "https://graph.microsoft.com/v1.0/groups/$TeamGroupId" } Add-MgTeamChannelMember -TeamId $TeamGroupId -ChannelId $channelId -BodyParameter $paramstest The error message I'm encoutering is : Add-MgTeamChannelMember : Bind requests not expected for action payload. Status: 400 (BadRequest) ErrorCode: BadRequest If anyone have a solution :-) Best regards P.S. : I'm french so my english may be a little bad.11Views0likes0CommentsHow to use New-ComplianceSearchAction -Export to export content search results and download locally?
We need to do a compliance project. We want to export the content search results to a specific location through PowerShell, and then download them locally. How do I use the PowerShell command New-ComplianceSearchAction -Export to reach the goal, please? I saw one solution like this: 1. UseNew-ComplianceSearchAction -Export to export content search results to temporary storage address. 2.Use Get-ComplianceSearchAction to find theaddress. 3. Use Azcopy command to copy or download from the address. But I don't find out how to do this with PowerShell commands. Any one could help to give one sample, please?Any help or guidance would be greatly appreciated! Below link is also my related question: https://techcommunity.microsoft.com/t5/windows-powershell/how-to-use-new-compliancesearchaction-export-to-export-results/m-p/4203207Solved550Views0likes2CommentsThreat Hunting with PowerShell - Security even with a small budget - there is no excuse!
Dear Threat Hunter, Lack of IT security is often excused by little or no available money. In my view, this is a very poor excuse. In this article I will try to give you a jump start on how to investigate threats with PowerShell. Is this a comprehensive and conclusive list of how you can find or detect threats/threats? NO, absolutely not. But it is meant to provide you with the support that you need to move forward on your own. Let's talk about the "general conditions": 1. If you use the PowerShell scripts I show/explain in this article, this is entirely your responsibility. I use the scripts in different situations, they are not dangerous, but you should already know what you are doing. 2. Written permission! If you are not sure if you are allowed to do an investigation, organize a written permission from your supervisor. 3. In the different scripts I sometimes (for this article deliberately) use standard search words like "malware", "malicious", "hacker" etc. Such search patterns/search words need to be customized, of course. These simply serve as an example. 4. The last part of the article examines some Microsoft cloud services. I am absolutely aware that there are a huge number of tools for hunting in the Microsoft cloud services. It starts with Azure Sentinel and continues with Cloud App Security. Since the focus is on a small budget, I'll leave those tools on the side. Introduction: So first, why should you use PowerShell for threat hunting? PowerShell is a useful threat hunting tool because it is a powerful scripting language and a platform for automating tools and accessing data across any Windows environment. It allows you to quickly gather information from various sources such as event logs, registries, files, and processes. Additionally, it can also be easily integrated with other tools and technologies making it a flexible and efficient tool for threat hunting. Some common use cases for PowerShell in the threat hunting environment include automated collection of log data, identification of unusual behavior anomalies in the system, the discovery of malware or malicious activity by known signatures or patterns or behaviors. These are just a few examples of how PowerShell can be used in a threat hunting capacity. Its versatility and ability to access and manipulate data from across the Windows environment make it a very valuable tool for any security professional. Threat Hunting in PowerShell - Use Cases: All right. So now that we understand where PowerShell can benefit an organization from a threat hunting perspective. Let's take a deeper look at some of the actual use cases you might encounter on a day to day basis, first being identify malicious processor files. So specifically, you can conduct raw file analysis to sift through different data shares to look for particular files in question whether that be a signature or even an extension of a certain file being able to quickly search and triage through files is an extreme benefit of using PowerShell for threat hunting. But how exactly do we start, what can we use as a guide? For example, the MITRE ATT&CK Framework. Here are a few examples: Indicator Removal: Clear Windows Event Logs https://attack.mitre.org/techniques/T1070/001/ Event Triggered Execution: Installer Packages https://attack.mitre.org/techniques/T1546/016/ Hide Artifacts: NTFS File Attributes https://attack.mitre.org/techniques/T1564/004/ Command and Scripting Interpreter: PowerShell https://attack.mitre.org/techniques/T1059/001/ Command and Scripting Interpreter: Windows Command Shell https://attack.mitre.org/techniques/T1059/003/ Event Triggered Execution: Windows Management Instrumentation Event Subscription https://attack.mitre.org/techniques/T1546/003/ Credentials from Password Stores: Windows Credential Manager https://attack.mitre.org/techniques/T1555/004/ Abuse Elevation Control Mechanism: Bypass User Account Control https://attack.mitre.org/techniques/T1548/002/ The MITRE ATT@CK framework provides a comprehensive and regularly updated overview of tactics, techniques, and procedures (TTPs) used by various threat actors. We can locate these TTPs using PowerShell, here are a few examples: Indicator Removal: Clear Windows Event Logs https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/06_Account_Events.ps1 Event Triggered Execution: Installer Packages https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/08_Get-ItemProperty_Software.ps1 Hide Artifacts: NTFS File Attributes https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/08_Get-ItemProperty_Software.ps1 Windows Installer Service is running https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/01_WIS_is_running.ps1 Search Alternate Data Streams on NTFS File Systems https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/02_Search_ADS_on_NTFS%20_(specific%20file).ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/03_Search_ADS_on_NTFS_file_systems.ps1 Read the Contents of a File https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/06_Read_the_contents_file.ps1 Locating Data Patterns within a File https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/05_locating_data_patterns_within_file.ps1 Search for Encoding with Regex https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/07_Search_encoding_with_regex.ps1 Search for Command and Scripting Interpreter: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Tactics_Techniques_Procedures_(TTPs)/04_Searching_for_PIDs.ps1 Threat hunting in different environments with PowerShell: Coming examples are about collecting information in very different environments. Also here a few examples as a kind => as first starting points: Hunt for Threats in Active Directory: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/01_Resetting_Password_Unlocking_Accounts.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/02_Search_stale_accounts.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/03_Users_without_Manager.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/04_Password_Expiration.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/05_Group_Membership_Report.ps1 https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Active_Directory/06_Account_Events.ps1 https://github.com/tomwechsler/Active_Directory_Advanced_Threat_Hunting/blob/main/PowerShell/Tracking_the_Source_of_Account_Lock_Outs_and_Bad_Passwords.ps1 https://github.com/tomwechsler/Active_Directory_Advanced_Threat_Hunting/blob/main/PowerShell/Finding_Unused_Group_Policy_Objects.ps1 Some of the scripts are structured in such a way that they must be executed block by block/line by line. So do not execute the whole script at once. Pay attention to the different information that is collected. With some investigations in the Active Directory accounts can be indicated like "guest" or "krbtgt", there must be clear of course how this information is to be estimated. Depending on how and what information is searched. Hunt for Threats in Exchange Online: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Exchange_Online/Exchange_Mailbox_LastLogin.ps1 Find mailboxes with the last login. Hunt for Threats in Azure: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Azure/Collect_vms_subscription.ps1 We search Azure for all virtual machines in a subscription. https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_Azure/02_Graph_Create_Time_Last_Password.ps1 When was the last password change and when were the accounts created? Hunt for Threats in SharePoint: https://github.com/tomwechsler/Threat_Hunting_with_PowerShell/blob/main/Hunting_SharePoint_Online/SharePoint_Online_specific_files.ps1 With this script we search for files with the extension .ps1 in a SharePoint Online page. Summary: Is this the best tactic to hunt for threats? No! There are many different tactics/techniques to search for threats. First of all, there are a huge number of different tools that can be used, for example SIEM/SOAR (Security Information and Event Management/Security Orchestration, Automation and Response). These tools are really great, sometimes cost a lot and often it takes a lot of knowledge to use such tools. But what is the use of such tools if the information generated by these tools cannot be understood properly, not very much. For this reason, I have tried in this article with simple tools to generate information that hopefully can be interpreted. Is finished here at this point. NO, the journey continues. The examples in this article are neither exhaustive nor complete, but they should give you a starting point. I hope you can build on this foundation. I hope that this information is helpful to you and that you have received a good "little" foundation. But I still hope that this information is helpful for you. Thank you for taking the time to read the article. Happy Hunting, Tom Wechsler P.S. All scripts (#PowerShell, Azure CLI, #Terraform, #ARM) that I use can be found on github! https://github.com/tomwechslerGenerate vCard for each user in Exchange online and attach to user's mail.
We are looking best method to create vCard for each user in Exchange online and attach vCard in user's outlook for outgoing email. Is there any script or tool to programmatically create a vCard, that can generate .vcf files with the desired contact information for each user and integrate to Exchange online to apply to corresponding user.20Views0likes0Commentsis there a bug in bytes
There are multiple scripts involving creating Magic Packets for WOL. Basically, all consist of code creating a byte array and sending it via System.Net.Sockets.UdpClient with the 2nd parameter of the send command as the length of the packet. According to the WOL docs the length should be 102 bytes. The math works for some MAC addresses but gives 86 for others. Test below [PS 5.1 ISE]. The point being would a length of 86 still work with WOL uncomment as needed to test $MAC = "1A:2B:3C:4D:5E:6F" #should give 102 #$MAC = "74:86:31:7D:19" #should give 86 #$MAC = "1A:86:3C:7D:6F" #should give 102, but try your own to test #$ByteArray = $MAC -replace "[:\-]" -split "(..)" -ne '' | ForEach-Object { [Byte] "0x$_"} $ByteArray = $MAC -split ":" | ForEach-Object { [Byte] "0x$_"} [Byte[]] $MagicPacket = (,0xFF * 6) + ($ByteArray * 16) $MagicPacket.Length P.S. Tested determining the length in other languages and all came out 102.16Views0likes1CommentExchange online and MGGraph are interfering
I am creating a new script. The script is running unattended. The script doing a couple things, the important part here is: setting a new user a license and setting the new user mailbox Address book policy. The address book is an Exchange online task the license is Graph. I am getting an error. How to reproduce the error: 1. connect to MgGraph, I am using this command Connect-MgGraph -TenantId $tenantID -AppId $appID -CertificateThumbprint $CertificateThumbPrint -NoWelcome do some work, Disconnect-MgGraph 2. Connect to Exchange online, in the same script: Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint -AppID $appID -Organization $tenantID -CommandName Get-EXOMailbox,Get-mailbox,Set-mailbox -SkipLoadingCmdletHelp -ShowBanner:$false The command verbose debug output is this: DEBUG: using System; using System.Net; using System.Management.Automation; using Microsoft.Win32.SafeHandles; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security; namespace Microsoft.PowerShell.Commands.PowerShellGet { public static class Telemetry { public static void TraceMessageArtifactsNotFound(string[] artifactsNotFound, string operationName) { Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI.TraceMessage(operationName, new { ArtifactsNotFound = artifactsNotFound }); } public static void TraceMessageNonPSGalleryRegistration(string sourceLocationType, string sourceLocationHash, string installationPolicy, strin g packageManagementProvider, string publishLocationHash, string scriptSourceLocationHash, string scriptPublishLocationHash, string operationName) { Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI.TraceMessage(operationName, new { SourceLocationType = sourceLocationType, SourceLoca tionHash = sourceLocationHash, InstallationPolicy = installationPolicy, PackageManagementProvider = packageManagementProvider, PublishLocationHash = p ublishLocationHash, ScriptSourceLocationHash = scriptSourceLocationHash, ScriptPublishLocationHash = scriptPublishLocationHash }); } } /// <summary> /// Used by Ping-Endpoint function to supply webproxy to HttpClient /// We cannot use System.Net.WebProxy because this is not available on CoreClr /// </summary> public class InternalWebProxy : IWebProxy { Uri _proxyUri; ICredentials _credentials; public InternalWebProxy(Uri uri, ICredentials credentials) { Credentials = credentials; _proxyUri = uri; } /// <summary> /// Credentials used by WebProxy /// </summary> public ICredentials Credentials { get { return _credentials; } set { _credentials = value; } } public Uri GetProxy(Uri destination) { return _proxyUri; } public bool IsBypassed(Uri host) { return false; } } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct CERT_CHAIN_POLICY_PARA { public CERT_CHAIN_POLICY_PARA(int size) { cbSize = (uint) size; dwFlags = 0; pvExtraPolicyPara = IntPtr.Zero; } public uint cbSize; public uint dwFlags; public IntPtr pvExtraPolicyPara; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct CERT_CHAIN_POLICY_STATUS { public CERT_CHAIN_POLICY_STATUS(int size) { cbSize = (uint) size; dwError = 0; lChainIndex = IntPtr.Zero; lElementIndex = IntPtr.Zero; pvExtraPolicyStatus = IntPtr.Zero; } public uint cbSize; public uint dwError; public IntPtr lChainIndex; public IntPtr lElementIndex; public IntPtr pvExtraPolicyStatus; } // Internal SafeHandleZeroOrMinusOneIsInvalid class to remove the dependency on .Net Framework 4.6. public abstract class InternalSafeHandleZeroOrMinusOneIsInvalid : SafeHandle { protected InternalSafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { } public override bool IsInvalid { get { return handle == IntPtr.Zero || handle == new IntPtr(-1); } } } // Internal SafeX509ChainHandle class to remove the dependency on .Net Framework 4.6. [SecurityCritical] public sealed class InternalSafeX509ChainHandle : InternalSafeHandleZeroOrMinusOneIsInvalid { private InternalSafeX509ChainHandle () : base(true) {} internal InternalSafeX509ChainHandle (IntPtr handle) : base (true) { SetHandle(handle); } internal static InternalSafeX509ChainHandle InvalidHandle { get { return new InternalSafeX509ChainHandle(IntPtr.Zero); } } [SecurityCritical] override protected bool ReleaseHandle() { CertFreeCertificateChain(handle); return true; } [DllImport("Crypt32.dll", SetLastError=true)] [SuppressUnmanagedCodeSecurity, ResourceExposure(ResourceScope.None), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern void CertFreeCertificateChain(IntPtr handle); } public class Win32Helpers { [DllImport("Crypt32.dll", CharSet=CharSet.Auto, SetLastError=true)] public extern static bool CertVerifyCertificateChainPolicy( [In] IntPtr pszPolicyOID, [In] SafeX509ChainHandle pChainContext, [In] ref CERT_CHAIN_POLICY_PARA pPolicyPara, [In,Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus); [DllImport("Crypt32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern SafeX509ChainHandle CertDuplicateCertificateChain( [In] IntPtr pChainContext); [DllImport("Crypt32.dll", CharSet=CharSet.Auto, SetLastError=true)] [ResourceExposure(ResourceScope.None)] public static extern SafeX509ChainHandle CertDuplicateCertificateChain( [In] SafeX509ChainHandle pChainContext); public static bool IsMicrosoftCertificate([In] SafeX509ChainHandle pChainContext) { //------------------------------------------------------------------------- // CERT_CHAIN_POLICY_MICROSOFT_ROOT // // Checks if the last element of the first simple chain contains a // Microsoft root public key. If it doesn't contain a Microsoft root // public key, dwError is set to CERT_E_UNTRUSTEDROOT. // // pPolicyPara is optional. However, // MICROSOFT_ROOT_CERT_CHAIN_POLICY_ENABLE_TEST_ROOT_FLAG can be set in // the dwFlags in pPolicyPara to also check for the Microsoft Test Roots. // // MICROSOFT_ROOT_CERT_CHAIN_POLICY_CHECK_APPLICATION_ROOT_FLAG can be set // in the dwFlags in pPolicyPara to check for the Microsoft root for // application signing instead of the Microsoft product root. This flag // explicitly checks for the application root only and cannot be combined // with the test root flag. // // MICROSOFT_ROOT_CERT_CHAIN_POLICY_DISABLE_FLIGHT_ROOT_FLAG can be set // in the dwFlags in pPolicyPara to always disable the Flight root. // // pvExtraPolicyPara and pvExtraPolicyStatus aren't used and must be set // to NULL. //-------------------------------------------------------------------------- const uint MICROSOFT_ROOT_CERT_CHAIN_POLICY_ENABLE_TEST_ROOT_FLAG = 0x00010000; const uint MICROSOFT_ROOT_CERT_CHAIN_POLICY_CHECK_APPLICATION_ROOT_FLAG = 0x00020000; //const uint MICROSOFT_ROOT_CERT_CHAIN_POLICY_DISABLE_FLIGHT_ROOT_FLAG = 0x00040000; CERT_CHAIN_POLICY_PARA PolicyPara = new CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CERT_CHAIN_POLICY_PARA))); CERT_CHAIN_POLICY_STATUS PolicyStatus = new CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CERT_CHAIN_POLICY_STATUS))); int CERT_CHAIN_POLICY_MICROSOFT_ROOT = 7; PolicyPara.dwFlags = (uint) MICROSOFT_ROOT_CERT_CHAIN_POLICY_ENABLE_TEST_ROOT_FLAG; bool isMicrosoftRoot = false; if(CertVerifyCertificateChainPolicy(new IntPtr(CERT_CHAIN_POLICY_MICROSOFT_ROOT), pChainContext, ref PolicyPara, ref PolicyStatus)) { isMicrosoftRoot = (PolicyStatus.dwError == 0); } // Also check for the Microsoft root for application signing if the Microsoft product root verification is unsuccessful. if(!isMicrosoftRoot) { // Some Microsoft modules can be signed with Microsoft Application Root instead of Microsoft Product Root, // So we need to use the MICROSOFT_ROOT_CERT_CHAIN_POLICY_CHECK_APPLICATION_ROOT_FLAG for the certificate verification. // MICROSOFT_ROOT_CERT_CHAIN_POLICY_CHECK_APPLICATION_ROOT_FLAG can not be used // with MICROSOFT_ROOT_CERT_CHAIN_POLICY_ENABLE_TEST_ROOT_FLAG, // so additional CertVerifyCertificateChainPolicy call is required to verify the given certificate is in Microsoft Application Root. // CERT_CHAIN_POLICY_PARA PolicyPara2 = new CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CERT_CHAIN_POLICY_PARA))); CERT_CHAIN_POLICY_STATUS PolicyStatus2 = new CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CERT_CHAIN_POLICY_STATUS))); PolicyPara2.dwFlags = (uint) MICROSOFT_ROOT_CERT_CHAIN_POLICY_CHECK_APPLICATION_ROOT_FLAG; if(CertVerifyCertificateChainPolicy(new IntPtr(CERT_CHAIN_POLICY_MICROSOFT_ROOT), pChainContext, ref PolicyPara2, ref PolicyStatus2)) { isMicrosoftRoot = (PolicyStatus2.dwError == 0); } } return isMicrosoftRoot; } } } IDX12729: Unable to decode the header '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' as Base64Url encoded string. At C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.5.1\netFramework\ExchangeOnlineManagement.psm1:762 char:21 + throw $_.Exception.InnerException; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], ArgumentException + FullyQualifiedErrorId : IDX12729: Unable to decode the header '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/Id entityModel/PII.]' as Base64Url encoded string. Exception details: $exception.Exception.Message # empty $exception.Exception.ParamName $exception.Exception.TargetSite # empty $exception.Exception.Data $exception.Exception.InnerException #empty $exception.Exception.HelpLink $exception.Exception.Source $exception.Exception.HResult $exception.Exception.StackTrace IDX12729: Unable to decode the header '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' as Base64Url encoded string. Name : Decode DeclaringType : System.IdentityModel.Tokens.Jwt.JwtSecurityToken ReflectedType : System.IdentityModel.Tokens.Jwt.JwtSecurityToken MemberType : Method MetadataToken : 100663422 Module : System.IdentityModel.Tokens.Jwt.dll IsSecurityCritical : True IsSecuritySafeCritical : False IsSecurityTransparent : False MethodHandle : System.RuntimeMethodHandle Attributes : PrivateScope, Assembly, HideBySig CallingConvention : Standard, HasThis ReturnType : System.Void ReturnTypeCustomAttributes : Void ReturnParameter : Void IsGenericMethod : False IsGenericMethodDefinition : False ContainsGenericParameters : False MethodImplementationFlags : Managed IsPublic : False IsPrivate : False IsFamily : False IsAssembly : True IsFamilyAndAssembly : False IsFamilyOrAssembly : False IsStatic : False IsFinal : False IsVirtual : False IsHideBySig : True IsAbstract : False IsSpecialName : False IsConstructor : False CustomAttributes : {} A metódus nem található: „Void System.Text.Json.Utf8JsonReader..ctor(System.ReadOnlySpan`1<Byte>, System.Text.Json.JsonReaderOptions)”. System.IdentityModel.Tokens.Jwt -2147024809 a következő helyen: System.IdentityModel.Tokens.Jwt.JwtSecurityToken.Decode(String[] tokenParts, String rawData) a következő helyen: Microsoft.Exchange.Management.AdminApiProvider.Authentication.JwtSecurityTokenUtils.GetTenantId(String accessToken) a következő helyen: Microsoft.Exchange.Management.AdminApiProvider.Authentication.TokenProviderUtils.GetTokenInformation(AuthenticationResult token AcquisitionResult, TokenProviderContext context) a következő helyen: Microsoft.Exchange.Management.AdminApiProvider.Authentication.MSALTokenProvider.<GetAccessTokenAsync>d__34.MoveNext() I tired: updateing both modules to the latest version removeing the Microsoft.Graph andMicrosoft.Graph.Authentication module before connecting to Exchange online clearing the token cache file fromAppData\Local\.IdentityService\mg.msal.cache I would like to avoid running two separate script or script isolation like new processes or jobs. Because i need to pass many variables between the two script, input and output. The app I am using and the cert is okay. If i am running separately it is working, so I can connect Exchange online with it. This github issue:https://github.com/microsoftgraph/msgraph-sdk-powershell/issues/1816seems to have similar issue, but this was in 2023. There is a workaround, but I am unable to understand. Basically i should connect differently to Graph? or Exchange online? if so how? can anyone recommend a non interactive option? Any idea why is this happening? What should i check?Solved4KViews0likes13Comments
Events
Recent Blogs
- One new resource, logging improvements and bugfixes. This is what SharePointDsc v5.2 is bringing to the table!May 12, 20227.5KViews1like0Comments
- 2 MIN READThis article describes a solution of an issue I have been troubleshooting today, where switching to an AllSigned execution policy resulted in the "This publisher is explicitly not trusted on your sys...Mar 19, 20226.3KViews1like1Comment