12 April 2021

The term is not recognized as the name of a cmdlet, function, script file, or operable program. How to connect from a specific module

Get-AzureADDirectorySetting : The term 'Get-AzureADDirectorySetting' is not recognized as the name of a cmdlet,            
function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the            
path is correct and try again.
And
Get-AzureADDirectorySetting : The term 'Get-AzureADObjectSetting' is not recognized as the name of a cmdlet,            
function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the            
path is correct and try again.

That's strange, the command does get completed when tabbing after typing get-azureaddir.
The problem is it's an AzureADPreview module commandlet, so you have to connect to AzureAd from that module like so:

Connect to AzureAD with a specific module:
AzureADPreview\Connect-AzureAD

08 April 2021

Add guest users to AzureAD in bulk and update the manager with PowerShell

 Bulk invite guest users:

<#  
.NOTES
    Name      : Add-BulkGuests.ps1
    Author    : Edwin van Brenk
    Version   : 1.0
    Date      : 08-04-2021
    Requires  : PowerShell v2 or higher
                AzureAD module
.SYNOPSIS
    -
.DESCRIPTION
    Bulk invite guest users in your AzureAD tenant
.PARAMETER
    -
.EXAMPLE
    -
.CSV FILE
    The csv need to look like this:
    DisplayName,EmailAddress
    firstname lastname,firstname.lastname@domain.com

#>            
            
# Connect to your tenant            
Connect-AzureAD            
            
# Import the csv file            
$guests = Import-Csv C:\temp\BulkGuests2.csv            
            
# Invite all users in the imported csv file            
foreach ($guest in $guests)            
{            
# Function Variables            
$emailaddress = $guest.EmailAddress            
$displayname = $guest.DisplayName            
            
   New-AzureADMSInvitation -InvitedUserEmailAddress $guest.emailaddress -InvitedUserDisplayName $guest.displayName -InviteRedirectUrl https://myapplications.microsoft.com -SendInvitationMessage $True            
   Write-Host "Invite sent to $emailaddress" -ForegroundColor Green            
}            
            
Write-Host Finished

Update the managers for the newly invited guests:

<#  
.NOTES
    Name      : Update-GuestManager.ps1
    Author    : Edwin van Brenk
    Version   : 1.0
    Date      : 08-04-2021
    Requires  : PowerShell v2 or higher
                AzureAD module
                Az.Accounts
.SYNOPSIS
    -
.DESCRIPTION
    Update guest users in your AzureAD tenant with the correct manager
.PARAMETER
    -
.EXAMPLE
    -
.CSV FILE
    The csv needs to look like this:
    User,Manager
    firstname lastname,manageremailaddress@domain.com
    
#>            
            
            
# Connecting to AzureAD            
Connect-AzureAD            
Connect-AzAccount            
            
# Importing the CSV source which has the changes             
$data = Import-Csv C:\Temp\Bulk\Manager.csv            
            
# Iterating through each row in the CSV            
foreach ($row in $data)            
{            
# Find the user and the manager            
$user = Get-AzureADUser -SearchString $row.User | select objectid            
$manager = Get-AzADUser -UserPrincipalName $row.Manager | Select Id            
            
# Updating the manager             
Set-AzureADUserManager -ObjectId $user.objectid -RefObjectId $manager.id            
            
# Completion info in the console for the specified row            
Write-Host "Updated "$row.user"" -ForegroundColor Green            
            
# Clear the variable for the next row            
$user = $null            
$manager = $null            
            
}            
Write-Host "Finished" -ForegroundColor Green

11 March 2021

Set Windows Server to use external NTP server

Stop the time service:
net stop w32time

Add the NTP servers to the manual peer list external servers:
w32tm /config /syncfromflags:manual /manualpeerlist:0.us.pool.ntp.org,1.us.pool.ntp.org,2.us.pool.ntp.org,3.us.pool.ntp.org

Set the source as reliable:
w32tm /config /reliable:yes

Start the time service:
net start w32time

Test the configuration:
w32tm /query /configuration



and
w32tm /query /status





27 February 2021

Usefull command's and little PowerShell scripts

Quickly get the Computer Name, Model, Make, and other useful information


Get-WMIObject -Class Win32_ComputerSystem             
information about the System            
            
Get-WMIObject -Class Win32_BIOS             
Information about the BIOS            
            
Get-WMIObject -Class Win32_Baseboard             
Information about the Motherboard            
            
Get-WMIObject -Class Win32_Processor             
Information about the CPU            
            
Get-WMIObject -Class Win32_LogicalDisk             
Information about Logical Drives (Includes mapped drives and I believe PSDrives)            
            
Get-WMIObject -Class Win32_DiskDrive             
Information about Physical Drives            
            
Get-WMIObject -Class Win32_PhysicalMemory             
Information about the Memory            
            
Get-WMIObject -Class Win32_NetworkAdapter             
Information about the NIC            
            
Get-WMIObject -Class Win32_NetworkAdapterConfiguration             
Information about the NICs Configuration


Check your PowerShell Version

$PSVersionTable



Restart all Network Adapters *Must be run as admin or at least local admin*

Requires PowerShell 3.0+

Get-NetAdapter | Restart-NetAdapter


Browse UNC path with PowerShell

To access UNC via PowerShell;

cd \\servername\C$\Path\To\File



Copy a file to all users Desktop’s

$Users = Get-ChildItem C:\Users\ -Exclude “Administrator”,”Public”,”Default*” # Exclude any other defaults that you don’t want.            
            
foreach($User in $Users.name){             
$Path = “C:\Users\$User\Desktop”;             
Copy-Item -Path “\\Path\To\Source\File.txt” -Destination $Path\File.txt             
}


Get free disk space on drives

This can either be run locally or part of a larger script to hit multiple machines.

$Drive=Get-WmiObject Win32_LogicalDisk -Filter “DriveType = 3”             
$DriveSize=$Drive.Size;$DriveSize=[math]::Round($DriveSize/1GB)             
$FreeSpace=$Drive.FreeSpace;$FreeSpace=[math]::Round($FreeSpace/1GB)             
$DriveName=$Drive.Name             
$ComputerName=Get-WmiObject Win32_ComputerSystem;$ComputerName=$ComputerName.Name             
$UsedSpace=$DriveSize  $FreeSpace;$UsedSpace=[string]$UsedSpace+” GB free on drive $DriveName on computer $ComputerName”            
            

26 February 2021

Enable Wake On Lan with PowerShell and send Wake On Lan packet with PowerShell

Credit for the script goes to Jan-Henrik Damaschke at https://www.itinsights.org

function Set-WakeEnabled

{            
<#
.SYNOPSIS

Set WoL on nic

Author: Jan-Henrik Damaschke (@jandamaschke)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None

.DESCRIPTION

Set Wake on Lan (WOL) settings for specific network interface card

.PARAMETER InterfaceName

Specifies the name of the interface where WoL setting should be changed

.PARAMETER WakeEnabled

Specifies if WoL should be enabled or disabled

.EXAMPLE

PS C:\> Set-WakeEnabled -InterfaceName Ethernet -WakeEnabled $true

.LINK

http://itinsights.org/
#>            
            
[CmdletBinding()] Param(            
        [Parameter(Mandatory = $True, ParameterSetName="InterfaceName")]            
        [String]            
        $InterfaceName,            
            
        [Parameter(Mandatory = $True)]            
        [String]            
        $WakeEnabled,            
            
        [Parameter(Mandatory = $True, ParameterSetName="ConnectionID")]            
        [String]            
        $NetConnectionID            
)            
            
    If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {            
        Write-Warning "You do not have Administrator rights to run this script!`nPlease re-run this script as an Administrator!"            
        Break            
    }            
            
    $nicsWakeEnabled = Get-CimInstance -ClassName MSPower_DeviceWakeEnable -Namespace root/wmi            
    $nics = Get-CimInstance -ClassName Win32_NetworkAdapter | Where-Object NetEnabled -eq $true            
            
    if ($InterfaceName){            
        $nic = $nics | Where-Object Name -eq $InterfaceName            
    }            
    else {            
        $nic = $nics | Where-Object NetConnectionID -eq $NetConnectionID            
    }            
            
    $nicWakeEnabled = $nicsWakeEnabled | Where-Object InstanceName -like "*$($nic.PNPDeviceID)*"            
                
    $enabled = $nicWakeEnabled.Enable            
            
    if (!($enabled -and $WakeEnabled)){            
        Set-CimInstance $nicWakeEnabled -Property @{Enable=$enabled}            
    }            
}

Find the mac address of the nic you want to wake up.
Get-WmiObject win32_networkadapterconfiguration | select description, macaddress
Or
Get-CimInstance win32_networkadapterconfiguration | select description, macaddress

To send a wake on lan package:
Install-Module -Name wakeonlan -Force
Import-module -Name wakeonlan
Invoke-WakeOnLan -MacAddress 84:D2:4A:0F:78:44

16 February 2021

Open Windows Explorer collapsed

 Anoying.

When opening Windows Explorer it opens with all folders collapsed. The behaviour can come from different settings, such as:

Showing all folders
Allowing network discovery
Last opened folder saved when closing the explorer

And probably a few I don't k now about.

Some dude (EpilepticUnderscore) over at social.technet.com created a batch file to overcome this annoyance.
See the original thread here: Collapse all folder-trees when closing Explorer (microsoft.com)

The batch job way:

29 January 2021

Single Sign On broken - Azure Active Directory Seamless Single Sign-On

 I don't know if this is something that only happens in my environment, but it happens.

When ever I start AADConnect and make a change in the configuration, add an OU for example, and save the change SSO breaks.

Quick way to see what's up is here:


If there are zero Seamless single sign-on domain's than you know what's up.
The SSO trust is broken.

There is a blogpost on docs.microsoft.com about it:
Azure Active Directory Connect: Troubleshoot Seamless Single Sign-On | Microsoft Docs

The steps listed there are in this script below.

Run this from the AADConnect machine:

# https://docs.microsoft.com/en-us/azure/active-directory/hybrid/tshoot-connect-sso            
            
# Import the Seamless SSO PowerShell module            
cd \            
cd 'C:\Program Files\Microsoft Azure Active Directory Connect'            
Import-Module .\AzureADSSO.psd1            
# Get the list of Active Directory forests on which Seamless SSO has been enabled            
New-AzureADSSOAuthenticationContext            
Get-AzureADSSOStatus            
#Disable Seamless SSO for each Active Directory forest where you've set up the feature            
$creds = Get-Credential domain\username            
Disable-AzureADSSOForest -OnPremCredentials $creds            
# Enable Seamless SSO for each Active Directory forest            
Enable-AzureADSSOForest            
# Enable the feature on your tenant            
Enable-AzureADSSO -Enable $true

11 January 2021

problem 4003 (INSUFF_ACCESS_RIGHTS)

When I tried to change a mailbox from type "User mailbox" to type "Shared mailbox" I got this error:

[PS] C:\>Set-Mailbox mailboxalias -Type shared -force

Error on proxy command 'Set-Mailbox -Type:'Shared' -Identity:'mailboxalias' -Confirm:$False -Force:$True' to server servername.domain.lan: Server version 15.00.1497.0000, Proxy method RPS:

Active Directory operation failed on servername.domain.lan. This error is not retriable. Additional information: Insufficient access rights to perform the operation.

Active directory response: 00002098: SecErr: DSID-03150F93, problem 4003 (INSUFF_ACCESS_RIGHTS), data 0

+ CategoryInfo          : NotSpecified: (:) [Set-Mailbox], CmdletProxyException
+ FullyQualifiedErrorId : Microsoft.Exchange.Configuration.CmdletProxyException,Microsoft.Exchange.Management.RecipientTasks.SetMailbox
+ PSComputerName        : servername.domain.lan

Turns out this has to do with user rights inheritance, find the user, select the "Security" tab and click the "Advanced" button.

There you should see the "Enable inheritance" button. Click it and wait for Active Directory synchronization.


Now when you run the same commandlet again, you should see no output, and thus the command worked. To double check you could run:

Get-Mailbox mailboxalias | Select RecipientTypeDetails

07 January 2021

550 5.7.520 Access denied & 550 5.4.142 RESOLVER.FWD.LoopingTarget

Since a couple of months Office365 and Exchange Online are blocking the auto forwarding of email to external domains.

And this is the error that can be found in the message trace results:

Error: 550 5.7.520 Access denied, Your organization does not allow external forwarding. Please contact your administrator for further assistance. AS(7555)

While this is a good idea in general, sometimes you want to enable it.

Here's how:

Go to https://protection.office.com/antispam

And create a new outbound policy.

Give it a name, description, decide whether you to be notified or not and if you want to apply recipient limits with an action if the limits are exceeded.

The the following is important.
At the automatic forwarding choose "On - Forwarding is enabled".
Choosing "Automatic - System-controlled" will not let the email be sent. This is the setting for the default policy "Outbound spam filter policy ‎(always ON)‎".

Then add a condition at "Applied to".

The easiest condition is to create a mail enabled security group that holds all the user accounts that you want to grant this right.


If you add 2 conditions, such as a security group and a separate user then you will receive this error in the message trace results:

Reason: [{LED=550 5.4.142 RESOLVER.FWD.LoopingTarget; forwarding to a looping external address};{MSG=};{FQDN=};{IP=};{LRT=}]


05 January 2021

When was the last time you reset the password of the AzureADSSOACC account?

 When was the last time you reset the password of the AzureADSSOACC account?


$user = [adsi]"LDAP://CN=AzureADSSOACC,CN=Computers,DC=yourdomain,DC=lan"            
[PSCustomObject] @{            
name = $user.name.Value            
pwdLastSet = [datetime]::FromFileTime($user.ConvertLargeIntegerToInt64($user.pwdLastSet.            
value))            
}