You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Intune中检测与修复脚本执行失败问题排查求助

Intune本地管理员密码检测/修复脚本故障排查与修复

问题背景

将检测与修复脚本上传至Intune后,运行修复脚本出现以下问题:

  • 检测状态显示“存在问题”
  • 修复状态显示“失败”
    调整Exit 1代码位置后问题仍未解决,脚本逻辑存在明显缺陷。

原脚本缺陷分析

1. 检测脚本(DetectAdminChange.ps1)缺陷

  • 类型不匹配导致误判:(Get-LocalUser -Name $adminUsername).Password返回的是SecureString类型,无法直接与明文字符串"messyW@ter10"做相等比较,这会导致检测逻辑永远判定密码已更改,始终返回Exit 1,检测状态一直显示“存在问题”。
  • 日志目录未预创建:C:\ps_script_logs目录如果不存在,Add-Content命令会执行失败,无法生成日志。

2. 修复脚本(RemediateAdminPassword.ps1)缺陷

  • 提前终止脚本:第一个Exit 0会直接终止脚本,导致后续设置密码永不过期、禁止修改密码以及日志记录的代码完全无法执行。
  • 日志目录未预创建:同样存在日志目录不存在的问题,Add-Content会执行失败。
  • 退出码逻辑混乱:脚本末尾的Exit 1永远无法触发,且修复成功应返回Exit 0,失败返回Exit 1,当前逻辑不符合Intune对脚本退出码的要求。

修正后的脚本

检测脚本(DetectAdminChange.ps1)

# 定义要监控的本地管理员用户名
$adminUsername = "OfflineAdmin"
# 定义日志文件路径
$logFilePath = "C:\ps_script_logs\OfflineAdmin Password Change Log.txt"

# 预创建日志目录
$logDir = Split-Path -Path $logFilePath -Parent
if (-not (Test-Path -Path $logDir)) {
    New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}

# 获取本地用户对象
$adminUser = Get-LocalUser -Name $adminUsername -ErrorAction Stop

# 将明文密码转换为SecureString用于对比
$expectedPassword = ConvertTo-SecureString -String "messyW@ter10" -AsPlainText -Force

# 对比密码哈希(通过ConvertFrom-SecureString转换为可比较的字符串)
$currentPasswordHash = $adminUser.Password | ConvertFrom-SecureString -AsPlainText
$expectedPasswordHash = $expectedPassword | ConvertFrom-SecureString -AsPlainText

if ($currentPasswordHash -ne $expectedPasswordHash) {
    Add-Content -Path $logFilePath -Value "$(Get-Date) - 管理员密码已更改."
    Exit 1 # 检测到问题,返回1触发修复
}
Exit 0 # 密码符合预期,返回0

修复脚本(RemediateAdminPassword.ps1)

# 定义要修复的本地管理员用户名
$adminUsername = "OfflineAdmin"
# 定义日志文件路径
$logFilePath = "C:\ps_script_logs\OfflineAdmin Password Change Log.txt"

# 预创建日志目录
$logDir = Split-Path -Path $logFilePath -Parent
if (-not (Test-Path -Path $logDir)) {
    New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}

try {
    # 设置默认密码
    $password = ConvertTo-SecureString -String "messyW@ter10" -AsPlainText -Force
    Set-LocalUser -Name $adminUsername -Password $password -ErrorAction Stop

    # 设置密码永不过期且禁止用户修改
    Set-LocalUser -Name $adminUsername -PasswordNeverExpires $true -CannotChangePassword $true -ErrorAction Stop

    # 记录修复日志
    Add-Content -Path $logFilePath -Value "$(Get-Date) - 管理员密码已修复."
    Exit 0 # 修复成功,返回0
}
catch {
    # 记录错误日志
    Add-Content -Path $logFilePath -Value "$(Get-Date) - 修复失败: $_"
    Exit 1 # 修复失败,返回1
}

内容的提问来源于stack exchange,提问作者Carol Ceguerra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:13:17