Category Archives: Coding

Automatically Add Missing @onmicrosoft.com Aliases to Office 365 Users

When managing Office 365, especially during domain migrations or hybrid setups, it’s critical to ensure every user has a corresponding @onmicrosoft.com alias.
This alias helps avoid delivery issues and supports fallback routing if needed.

Today, we’ll walk through how to check if users are missing the @onmicrosoft.com alias — and automatically add it if needed.

Let’s dive in.


What This Script Will Do:

  • Pull all mailboxes from Microsoft 365.
  • Check if their primary email is from your main domain (e.g., yourdomain.com).
  • If so, make sure they also have a yourdomain.onmicrosoft.com alias.
  • If missing, add the alias automatically.
  • Log everything into a clean, auditable table.
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName youradmin@yourdomain.com

# Define your domains
$primaryDomain = "yourdomain.com"
$onMicrosoftDomain = "yourdomain.onmicrosoft.com"

# Initialize a results array
$results = @()

# Get all mailboxes
$users = Get-Mailbox -ResultSize Unlimited

foreach ($user in $users) {
    $userPrincipalName = $user.UserPrincipalName

    # Only process users whose primary address is @yourdomain.com
    if ($userPrimaryAddress = $user.EmailAddresses | Where-Object { $_ -cmatch "^SMTP:.*@$primaryDomain$" }) {

        # Extract the local part (before the @)
        $localPart = ($userPrimaryAddress -replace "SMTP:", "").Split("@")[0]
        $expectedAlias = "$localPart@$onMicrosoftDomain"

        # Check if alias already exists
        $hasAlias = $user.EmailAddresses | Where-Object { $_ -match [regex]::Escape($expectedAlias) }

        if (-not $hasAlias) {
            Write-Host "Adding alias $expectedAlias to $userPrincipalName" -ForegroundColor Yellow

            # Add the missing alias
            Set-Mailbox $user.Identity -EmailAddresses @{add="smtp:$expectedAlias"}

            $results += [PSCustomObject]@{
                UserPrincipalName = $userPrincipalName
                PrimaryEmail      = $userPrimaryAddress
                AddedAlias        = $expectedAlias
                Action            = "Alias Added"
            }
        }
        else {
            $results += [PSCustomObject]@{
                UserPrincipalName = $userPrincipalName
                PrimaryEmail      = $userPrimaryAddress
                AddedAlias        = $expectedAlias
                Action            = "Alias Already Exists"
            }
        }
    }
    else {
        $results += [PSCustomObject]@{
            UserPrincipalName = $userPrincipalName
            PrimaryEmail      = "N/A"
            AddedAlias        = "N/A"
            Action            = "Skipped (Not $primaryDomain)"
        }
    }
}

# Display the results
$results | Format-Table -AutoSize

# Optional: Export results to CSV for auditing
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$results | Export-Csv -Path "AliasUpdateReport_$timestamp.csv" -NoTypeInformation

Script Summary

StepAction
1Connects to Exchange Online.
2Filters users with a primary @yourdomain.com address.
3Checks if their @yourdomain.onmicrosoft.com alias already exists.
4Adds the alias if missing.
5Logs everything to the screen and to a CSV file.

Pro Tips

  • Always test first: Run the script with the Set-Mailbox line commented out if you want a dry run.
  • This script only adds aliases — it never modifies the user’s primary email or login.
  • The CSV file gives you a full audit trail you can save for compliance purposes.

Safety Features

✅ Only users in your @yourdomain.com are affected.
✅ Existing aliases are never duplicated.
✅ No disruption to user mail flow.


Conclusion

This approach ensures every user has a matching @onmicrosoft.com alias, keeping your environment clean, compliant, and ready for future migrations or backup routing needs.

If you’re managing a hybrid environment, tenant migration, or simply cleaning up your domain setup, this script will save you hours of manual work.

Keep free heroku dynos up forever

app.set('port', (process.env.PORT || 5000));

//For avoidong Heroku $PORT error
app.get('/', function(request, response) {
    var result = 'App is running'
    response.send(result);
}).listen(app.get('port'), function() {
    console.log('App is running, server is listening on port ', app.get('port'));
});

if(process.env.url){
    http.get(process.env.url);
}


setInterval(function(){
    http.get(process.env.url);
}, 300000)

Enabling node debugging in vscode

Setting up VS Code To Debug in Node.js

Sorry, I couldn’t resist this meme — it’s just so appropriate. Ok, so let’s walk through setting up VS Code to debug Node. I’ll assume you’ve already downloaded VS Code from the link I posted above, so we’re ready to start setting it up.

Open up Preferences > Settings and in the search box type in “node debug”. Under the Extensions tab there should be one extension titled “Node debug”. From here, click the first box: Debug > Node: Auto Attach and set the drop down to “on”. You’re almost ready to go now. Yes, it really is that easy.

Here’s what you should see under the Settings tab. Set the first drop down ‘Debug > Node: Auto Attach’ to ‘on’.

Now, go to your Node.js project file, and set some breakpoints by clicking on the left hand side of the file wherever you’d like to see your code stop, and in the terminal type node --inspect <FILE NAME>. Now watch the magic happen…

See the red breakpoints? See the `node — inspect readFileStream.js` in the terminal? That’s it.

VS Code Debugging in Action

If you need a Node.js project to test this out with, you can download my repo here. It was made to test different forms of streaming large amounts of data with Node, but it works really well for this demo. If you’d like to see more about streaming data with Node and performance optimization, you can see my posts here and here.

Once you hit Enter, your VS Code terminal should turn orange at the bottom to indicate you’re in debug mode and your console will print some message along the lines of ‘Debugger Attached’.

The orange toolbar and `Debugger attached’ message will tell you VS Code is running correctly in debug mode.

Once you see this happening, congrats, you’re running in debug mode in Node.js!

Now, you can see your breakpoints in the bottom left corner of the screen (and can toggle them on and off with the checkboxes), and you can step through the code just like you would in a browser with the little play, step over, step in, restart, etc. buttons at the top center of the IDE. VS Code even highlights the breakpoint and line you’ve stopped on with yellow, making it easier to follow along.

Hit the play button at the top to step from one break point to the next one in your code.

As you step from breakpoint to breakpoint, you can see the program printing out the console.logs in the debug console at the bottom of the VS Code IDE and the yellow highlighting will travel with you, as well.

As you can see, when we stop on breakpoints, we can see all the local scope info we could explore in the console in the upper left corner of VS Code.

As you can see, as I progress through the program, more prints out to the debug console the further through the breakpoints I go, and along the way, I can explore the objects and functions in the local scope using the tools in the upper left hand corner of VS Code, just like I can explore scope and objects in the browser. Nice!

That was pretty easy, huh?

Conclusion

Node.js debugging doesn’t have to be the headache it was in the past, and it doesn’t need to involve 500 console.log()s in the codebase to figure out where the bug is.

Visual Studio Code’s Debug > Node: Auto Attach setting makes that a thing of the past, and I, for one, am so thankful.

Check back in a few weeks, I’ll be writing about end-to-end testing with Puppeteer and headless Chrome or using Nodemailer to reset passwords in a MERN application, so please follow me so you don’t miss out.

Thanks for reading, I hope this gives you an idea of how to more easily and effectively debug your Node.js programs with a little assistance from VS Code. Claps and shares are very much appreciated!

Simple script to backup all SQL Server databases

DECLARE @name VARCHAR(50) -- database name  
DECLARE @path VARCHAR(256) -- path for backup files  
DECLARE @fileName VARCHAR(256) -- filename for backup  
DECLARE @fileDate VARCHAR(20) -- used for file name
 
-- specify database backup directory
SET @path = 'C:\Backup\'  
 
-- specify filename format
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) 
 
DECLARE db_cursor CURSOR READ_ONLY FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases
 
OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   
 
WHILE @@FETCH_STATUS = 0   
BEGIN   
   SET @fileName = @path + @name + '_' + @fileDate + '.BAK'  
   BACKUP DATABASE @name TO DISK = @fileName  
 
   FETCH NEXT FROM db_cursor INTO @name   
END   

 
CLOSE db_cursor   
DEALLOCATE db_cursor

Powershell script not digitally signed

If you get 

is not digitally
signed. You cannot run this script on the current system. For more information about running scripts and setting
execution policy, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1

run from elevated powershell:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass