强制更改 Microsoft 365 中所有用户的密码

Jacki

您可以在 Microsoft 365 管理中心强制更改用户的密码。但是,如果您想为许多用户执行此操作,最好使用 PowerShell。这是因为它比手动检查用户要快得多。在本文中,你将了解如何使用 PowerShell 强制更改 Microsoft 365 中所有用户的密码。

安装 Microsoft Graph PowerShell

以管理员身份运行 Windows PowerShell 并安装 Microsoft Graph PowerShell。

Install-Module Microsoft.Graph -Force

重要的:在运行 cmdlet 或脚本之前,请务必更新到最新的 Microsoft Graph PowerShell 模块版本,以防止出现错误和不正确的结果。

连接到 Microsoft Graph PowerShell

然后,使用以下范围连接到 Microsoft Graph PowerShell。

Connect-MgGraph -Scopes "User.ReadWrite.All", "Directory.ReadWrite.All", "Directory.AccessAsUser.All"

强制单个用户更改密码

这将在用户使用密码登录后显示更改密码提示。

$userId = "[email protected]"

$params = @{
	passwordProfile = @{
		forceChangePasswordNextSignIn = $true
	}
}

Update-MgUser -UserId $userId -BodyParameter $params

更新您的密码用户使用密码登录后会出现提示。

更改密码并强制更改单个用户的密码

这将更改用户的密码。之后,他们需要使用该密码登录。登录后,他们将收到更新密码的提示。

$UserId = "[email protected]"

$params = @{
    passwordProfile = @{
        forceChangePasswordNextSignIn = $true
        password                      = "B%#X*4BUiHK3%3"
    }
}

Update-MgUser -UserId $userId -BodyParameter $params

强制所有用户更改密码

强制所有用户在下次登录时更改密码。

重要的:打开管理员 UPN线1 因此它被排除在脚本之外。

$upnToExclude = "[email protected]"

# Get all users
$allUsers = Get-MgUser -All

foreach ($user in $allUsers) {
    if ($user.UserPrincipalName -ne $upnToExclude) {
        try {
            $userId = $user.Id
            $params = @{
                passwordProfile = @{
                    forceChangePasswordNextSignIn = $true
                }
            }
            Update-MgUser -UserId $userId -BodyParameter $params
            
            # Log successful update
            Write-Host "Successfully updated password profile for user: $($user.UserPrincipalName)" -ForegroundColor Green
        }
        catch {
            # Log error or failure
            Write-Host "Failed to update password profile for user: $($user.UserPrincipalName). Error: $_" -ForegroundColor Red
        }
    }
    else {
        Write-Host "Skipping user with UPN: $upnToExclude" -ForegroundColor Cyan
    }
}

更改密码并强制所有用户更改密码

强制更改所有用户的密码。使用新密码登录后,他们将收到密码提示以更改密码。

PowerShell 脚本将为每个用户创建一个随机密码并将其导出到 CSV 文件密码重置.csvC:温度

有关的:如何使用 PowerShell 强制删除 Microsoft 365 中的联系人

重要的:打开管理员 UPN1号线所以它被排除在脚本之外。

$upnToExclude = "[email protected]"
$CSVExportPath = "C:tempPasswordReset.csv"
$PasswordLength = 12

# www.alitajran.com/generate-secure-random-passwords-powershell/
function Get-RandomPassword {
    param (
        # The length of each password which should be created.
        [Parameter(Mandatory = $true)]
        [ValidateRange(8, 255)]
        [Int32]$Length,

        # The number of passwords to generate.
        [Parameter(Mandatory = $false)]
        [Int32]$Count = 1,

        # The character sets the password may contain.
        # A password will contain at least one of each of the characters.
        [String[]]$CharacterSet = @(
            'abcdefghijklmnopqrstuvwxyz',
            'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            '0123456789',
            '!$%&^.#;'
        )
    )

    # Generate a cryptographically secure seed
    $bytes = [Byte[]]::new(4)
    $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
    $rng.GetBytes($bytes)
    $seed = [System.BitConverter]::ToInt32($bytes, 0)
    $rnd = [Random]::new($seed)

    # Combine all character sets for random selection
    $allCharacterSets = [String]::Concat($CharacterSet)

    try {
        for ($i = 0; $i -lt $Count; $i++) {
            $password = [Char[]]::new($Length)
            $index = 0

            # Ensure at least one character from each set
            foreach ($set in $CharacterSet) {
                $password[$index++] = $set[$rnd.Next($set.Length)]
            }

            # Fill remaining characters randomly from all sets
            for ($j = $index; $j -lt $Length; $j++) {
                $password[$index++] = $allCharacterSets[$rnd.Next($allCharacterSets.Length)]
            }

            # Fisher-Yates shuffle for randomness
            for ($j = $Length - 1; $j -gt 0; $j--) {
                $m = $rnd.Next($j + 1)
                $t = $password[$j]
                $password[$j] = $password[$m]
                $password[$m] = $t
            }

            # Output each password
            Write-Output ([String]::new($password))
        }
    }
    catch {
        Write-Host "Error: $_" -ForegroundColor Red
    }
}

# Get all users
$allUsers = Get-MgUser -All

$Report = [System.Collections.Generic.List[Object]]::new()

foreach ($user in $allUsers) {
    if ($user.UserPrincipalName -ne $upnToExclude) {
        try {
            $userId = $user.Id
            # Generate a random password
            $newPassword = Get-RandomPassword -Length $PasswordLength
            $params = @{
                passwordProfile = @{
                    forceChangePasswordNextSignIn = $true
                    password                      = $newPassword
                }
            }
            Update-MgUser -UserId $userId -BodyParameter $params
            # Log successful update and add to CSV data
            Write-Host "Successfully updated password for user: $($user.UserPrincipalName) with new password." -ForegroundColor Green
            $ReportLine = [PSCustomObject]@{
                UserPrincipalName = $user.UserPrincipalName
                NewPassword       = $newPassword
            }
            $Report.Add($ReportLine)
        }
        catch {
            Write-Host "Failed to update password for user: $($user.UserPrincipalName). Error: $_" -ForegroundColor Red
            $ReportLine = [PSCustomObject]@{
                UserPrincipalName = $user.UserPrincipalName
                NewPassword       = "Failed to update"
            }
            $Report.Add($ReportLine)
        }
    }
    else {
        Write-Host "Skipping user with UPN: $upnToExclude" -ForegroundColor Cyan
    }
}

# Export data to CSV
$Report | Export-Csv "$CSVExportPath" -NoTypeInformation -Encoding utf8
Write-Host "Passwords have been successfully exported to $CSVExportPath" -ForegroundColor Cyan

就是这样!

笔记:如果您想知道用户是否更改了密码或获取其他一些有价值的密码信息,您可以检查 PowerShell 脚本导出 Microsoft 365 用户密码报告

结论

您了解了如何使用 PowerShell 强制更改 Microsoft 365 中所有用户的密码。使用正确的命令和脚本,您可以立即采取行动。

您喜欢这篇文章吗?您可能还喜欢导出 Microsoft 365 非活动用户报告。不要忘记关注我们并分享这篇文章。