azure
99 TopicsStop hardcoding secrets! Now what?!
Yeah, we all know this right “STOP DOING THIS”, “STOP DOING THAT!” Yeah… that’s nice, but now what?! When you are already in the PowerShell field for some time and have created some scripts you might have been running into this topic; ‘How to deal with secrets’. There are of course solutions like KeyVault, SecureString and secret providers with API’s which help you to store the secrets you have in a secure environment. Things like this might look familiar; $password = "P@ssw0rd123!" $apiKey = "sk-1234567890abcdef" $connectionString = "Server=myserver;Database=mydb;User=admin;Password=SuperSecret123;" But what if I told you there’s a better way? A way that’s: Secure by default Cross-platform (Windows, Linux, macOS) Works with multiple backends (local, Azure Key Vault, HashiCorp Vault) Standardized across your entire team Built right into PowerShell 7+ (with some extra module support) That way forward is called ‘PowerShell SecretManagement”! What is SecretManagement? Think of PowerShell SecretManagement as the universal remote control for your secrets. With this remote control you can handle credentials for different systems while you just get one unified interface. It doesn’t matter if that secret is stored: In your local machine In an Azure KeyVault In HashiCorp Vault In KeePass, LastPass etc. The mindset remains the same ‘One remote control, to control them all’. The architecture behind it looks a bit like below; Explaination: SecretManagement “The interface where you code against” SecretStore “The default storage where your secrets live” Getting Started Let’s get started! Start PowerShell 7+ and run the code below Install-Module Microsoft.PowerShell.SecretManagement -Repository PSGallery -Force Install-Module Microsoft.PowerShell.SecretStore -Repository PSGallery -Force Now we have the required modules installed form the PowerShell Gallery it’s time to create our first vault. Register-SecretVault -name "LocalTestVault" It will ask you for the module. Enter the name “Microsoft.PowerShell.SecretStore”. (If you want you can also specify this value directly in the CMDLet by specifying the -ModuleName parameter. You should end up with something like below: First secrets Now we have the vault set-up it’s time to add some content to it. Follow the steps below to create the first secret in the vault Run the command below to create the first secret Set-Secret -Name "TestSecret" -Secret "SuperDuperSecureSecretString" If you haven’t specified the password it will now ask for one! You should end up with something like below; Cool right? On my personal blog I have the full post where I also show how to change, delete, and store complex objects. You can find it here: https://bartpasmans.tech/powershell-stop-hardcoding-secrets-now-what/ Happy scripting!31Views0likes0CommentsFetch Email of Login User In System Context
Dear Team, We are working on retrieving email address of the user joined to Entra ID from Entra-joined Windows devices, specifically while running in a system context.The whoami /upn command successfully returns the joined user’s email address in a user context, but it does not work in a system context, particularly when using an elevated terminal via the psexec utility.We also tested the dsregcmd /status command; however, in a system context, the User Identity tab in the SSO State section only appears when there is an error in AzureAdPrt. Under normal, healthy operating conditions, this command does not provide the user identity or the full domain username. We would greatly appreciate guidance on how to retrieve the Entra ID joined user’s email address in a system context, especially from those with prior experience in this area. Thank you for your support.Solved192Views0likes3CommentsRe-using computer account with Add-Computer
I am having an issue getting computers to rejoin the domain after they are reimaged. It has been working up until Windows 11 22H2. I found that KB5020276 changed re-using computer names, I have done all the required changes and the script still will not work but I am able to add the computer back to the domain if I use the GUI. Use the same network account in both. The account is a member of the Domain Admins. $domain= '<domain>' $password= "<password>" | ConvertTo-SecureString -asPlainText -Force #enter user account that will be used to join domain $user= '$domain\<user>' $cred= New-Object System.Management.Automation.PSCredential($user,$password) #edit for OU path $oupath = '<path>' #add computer to OU Add-Computer -domainname $domain -oupath $oupath -Credential $cred -ErrorAction silentlycontinue #add computer to domain Add-Computer -DomainName $domain -Credential $cred Script output Microsoft Windows [Version 10.0.22621.1635] (c) Microsoft Corporation. All rights reserved. C:\Users\Administrator>powershell -nologo -executionpolicy bypass -noprofile -file C:\test\CUR_Join.ps1 Add-Computer : Computer 'TEST' failed to join domain '<domain>' from its current workgroup 'WORKGROUP' with following error message: The group name could not be found. At C:\test\CUR_Join.ps1:17 char:1 + Add-Computer -domainname $domain -oupath $oupath -Credential $cred + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (TEST:String) [Add-Computer], InvalidOperationException + FullyQualifiedErrorId : FailToJoinDomainFromWorkgroup,Microsoft.PowerShell.Commands.AddComputerCommand Add-Computer : Computer 'TEST' failed to join domain '<domain>' from its current workgroup 'WORKGROUP' with following error message: An account with the same name exists in Active Directory. Re-using the account was blocked by security policy. At C:\test\CUR_Join.ps1:21 char:1 + Add-Computer -DomainName $domain -Credential $cred + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (TEST:String) [Add-Computer], InvalidOperationException + FullyQualifiedErrorId : FailToJoinDomainFromWorkgroup,Microsoft.PowerShell.Commands.AddComputerCommand NetSetup.log using script 05/09/2023 09:18:50:880 IsLegacyAccountReuseSetInRegistry returning: 'FALSE''. 05/09/2023 09:18:50:880 NetpManageMachineAccountWithSid: The computer account already exists in Active Directory.Re-using the account was blocked by security policy. NetSetup.log using GUI 05/09/2023 09:22:15:333 IsLegacyAccountReuseSetInRegistry returning: 'FALSE''. 05/09/2023 09:22:15:333 NetpCheckIfAccountShouldBeReused: Matching Owner and current user SIDs. Allowing re-use of account.12KViews0likes8CommentsAssigning a Manager with PowerShell Graph – Manager Not Found
Hi everyone, We are currently refactoring our PowerShell scripts to align with Microsoft's recommended standards. In our script that creates new users in Azure Active Directory (AAD) via Microsoft Graph, we’re having trouble assigning a manager to a new user. Whether we try using the manager’s object ID or email address, the manager is not found, and the assignment fails. Has anyone encountered this issue before? Is there something we might be doing wrong in how we’re referencing or assigning the manager? Thanks in advance for your help.161Views0likes3CommentsActivating a users multiple PIM groups using PowerShell
Hi All, Following on from the implementation of PIM by one of my clients. Due to the large numbers of groups for some staff, i.e. developers etc, we have looked into activating them programmatically. However, this always appears to fall over due to the syntax etc. Whether using Get-MgPrivilegedAccessGroupEligibilityScheduleInstance or Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/beta/identityGovernance/privilegedAccess/group/assignments" or New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest. In various scripts, it either falls over intermittently saying '..is not recognised as the name of a cmdlet..etc etc etc. To check whether anyone else has achieved this. I am trying to avoid reworking what they have put in place over the past 3 months or so. Many Thanks MoZZaSolved151Views0likes1CommentAd-Hoc Entra MFA using SMS
Error : Get MFA Client Access TokenDone. Send MFA challenge to the user Done. OTP sent to your phone. Please enter the OTP: Enter the OTP sent via SMS: 696632 Invoke-RestMethod: C:\Git_Repo\MFA_Test\MFATestWIthKyle\sms.ps1:54:28 Line | 54 | … ionResult = Invoke-RestMethod -Uri 'https://strongauthenticationservi … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Service BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; | } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; | text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: | #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px | solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: | 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: | Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; | } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; | border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; | border-bottom: 2px white solid; background-color: #e5e5cc;} Service Endpoint not found. WARNING: Invalid OTP or validation failed. Below line causing the error $mfaValidationResult = Invoke-RestMethod -Uri 'https://strongauthenticationservice.auth.microsoft.com/StrongAuthenticationService.svc/Connector//ValidatePin' -Method POST -Headers $Headers -Body $XML -ContentType 'application/xml'96Views0likes0CommentsGet a list of specific agegroup users stored on a security group
Dear Community, I wonder if it would be possible to get a list of users (stored in a security group) marked as "minor" and "not adult" using microsoft graph. Once I get the members of the group (using Get-MgGroupMember -GroupId XXXX), I am not sure how to retrieve only the ones with a specific agegroup property. Is that feasible? Any help would be greatly appreciated. Many thanks in advance!Solved173Views0likes2Commentsfind 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 .95Views0likes1CommentExport Enterprise apps and signin count
I need to export all the configured enterprise apps and login count for each. This script does the job, but it truncates the application name (see example screen shot) and I can't figure out how to export the results to csv. Can anyone help? #To enable verbose [CmdletBinding()] Param() #Retrieve list of applications $Apps = Get-AzureADApplication #Loop through each application ForEach($App in $Apps){ Write-Verbose "Processing $($App.DisplayName)" #Retrieve logs filtered on AppID $Log = Get-AzureADAuditSignInLogs -All $true -filter "appid eq '$($App.AppID)'" #Create a custom object for output [PSCustomObject]@{ ApplicationName = $App.DisplayName ApplicationID = $App.AppID SignIns = $Log.count } #To prevent throttling on Sign-in Log querying, insert a sleep Start-Sleep 1 }420Views0likes3CommentsPowershell Script to extract Azure VM Metrics data
Hi Community, hope you are doing well. I am currently playing around with powershell scripting and trying to extract Azure VM utilization data using https://learn.microsoft.com/en-us/powershell/module/az.monitor/get-azmetric?view=azps-12.3.0 powershell module. I am trying to extract VM metrics through my script for all VMs in my current subscription (free trial) and outputting the same to a csv file. I can see the data getting extracted when I run in console but when I run the script I am unable to see the data getting outputted to my csv file. Please find below my script: # Modules importation #$modules = 'Az.Accounts','Az.Compute', 'Az.Reservations' , 'Az.Storage' , 'Az.Billing' ,'Az.BillingBenefits' ,'Az.Monitor','Az.ResourceGraph', 'Join-Object' ,'PSExcel' ,'Az.Resources', 'Az.CostManagement','ImportExcel' # PS Module required #Install-Module -Name $modules -Scope CurrentUser -Force #Powershell-5.1 # Suppress breaking changes Set-Item Env:\SuppressAzurePowerShellBreakingChangeWarnings "true" # Connect to Azure Connect-AzAccount # Name of the analyze [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') $title = ' Azure VM Usage' $msg = 'Please enter the name of the analyze:' $checklistname = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title) # Subscription(s) selection - CTRL & click to select more than 1 subscription $subquery = (Get-AzSubscription | Out-GridView -Title "Select an Azure Subscription" -PassThru) $sub = $subquery.Id Write-Host "Subscription(s) selected: $sub" -ForegroundColor Green # Creation of the directroy New-Item -Path "c:\" -Name "Azurecost\$checklistname" -ItemType "directory" -force set-location c:\azurecost\$checklistname #$csvFileVM = New-Object System.IO.StreamWriter("c:\azurecost\$checklistname\VM-Usage.csv") #$csvFileVM.WriteLine("Name, Id, ResourceGroup, MaxCPU") foreach ($subscription in $sub) { # Set the subscription context Set-AzContext -Subscription $subscription $vms = Get-AzVM $vmUtilizationData = @() # Loop through each VM to get utilization metrics foreach ($vm in $vms) { $vmName = $vm.Name $resourceId = $vm.Id $Resourcegroup = $vm.ResourceGroupName # Get metrics for the VM (e.g., CPU Percentage) $metric = Get-AzMetric -ResourceId $resourceId -MetricName "Percentage CPU" -TimeGrain 12:00:00 -StartTime (Get-Date).AddDays(-3) -EndTime (Get-Date) $MaxCPU = $metric.data.maximum | Measure-Object -Maximum | Select-Object -property Maximum #$csvFileVM.WriteLine(" $MaxCPU") $vmUtilizationData += [PSCustomObject]@{ VMName = $vmName ResourceGroup = $Resourcegroup MaxCPU = $MaxCPU } } } $vmUtilizationData | Export-Csv -Path "c:\Azurecost\$checklistname\VMUsage.csv" -NoTypeInformation Write-Host "Your script has finished running." pause Please help me understand what am I missing here since other details like VM name, Resource group name are getting outputted to my csv file through this script except the metric values.482Views0likes0Comments