如何从注册表获取Office 365登录状态并检查指定子键的SignedOut属性
Office 365未登录状态的注册表检测方案
背景
由于MSOnline cmdlet将于2024年3月弃用,且GraphAPI权限申请流程不符合公司策略,因此通过注册表路径HKCU:\SOFTWARE\Microsoft\Office\16.0\Common\Identity\Identities检测Office 365登录状态:当路径下名称为字母数字且以_ADAL结尾的子键存在SignedOut属性时,判定用户未登录,需弹出提示框。
实现步骤
1. 精准筛选目标注册表子键
原命令使用-Exclude *_AD的过滤方式不够精准,建议通过正则表达式直接匹配符合要求的子键名称:
$identityPath = 'HKCU:\SOFTWARE\Microsoft\Office\16.0\Common\Identity\Identities' # 筛选名称为字母数字组合且以_ADAL结尾的子键 $targetKeys = Get-ChildItem -Path $identityPath -ErrorAction SilentlyContinue | Where-Object { $_.PSChildName -match '^[a-zA-Z0-9]+_ADAL$' }
正则表达式^[a-zA-Z0-9]+_ADAL$确保子键名称仅包含字母数字,且严格以_ADAL结尾,避免误匹配其他无关子键。
2. 检查子键是否存在SignedOut属性
每个注册表子键对象的Property属性会返回该子键下所有属性名称的字符串数组,通过-contains运算符可快速判断是否包含SignedOut属性:
if ($targetKeys) { foreach ($key in $targetKeys) { # 检查当前子键是否存在SignedOut属性 if ($key.Property -contains 'SignedOut') { # 加载Windows Forms程序集,弹出提示框 Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.MessageBox]::Show( '您的Office 365账户未登录,请登录后重试。', 'Office登录状态提醒', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning ) # 找到符合条件的子键后立即退出循环,避免重复提示 break } } }
完整脚本
将上述步骤整合为完整可执行脚本:
# 定义目标注册表路径 $identityPath = 'HKCU:\SOFTWARE\Microsoft\Office\16.0\Common\Identity\Identities' # 获取符合要求的ADAL子键 $targetKeys = Get-ChildItem -Path $identityPath -ErrorAction SilentlyContinue | Where-Object { $_.PSChildName -match '^[a-zA-Z0-9]+_ADAL$' } # 检测未登录状态并弹出提示 if ($targetKeys) { foreach ($key in $targetKeys) { if ($key.Property -contains 'SignedOut') { Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.MessageBox]::Show( '您的Office 365账户未登录,请登录后重试。', 'Office登录状态提醒', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning ) break } } }
内容的提问来源于stack exchange,提问作者mzurhorst
相关产品推荐
相关产品推荐

