$adminUser = [ADSI] "WinNT://$name/Administrator"
$adminUser.SetPassword($password)
是否有办法验证这两行代码是否成功更改本地管理员密码,例如它返回 1 或 0 表示成功或失败?我可以确认这两行代码在我的设备上确实有效,但计划是通过组策略推送我的脚本,并希望创建一个日志来表明脚本是否成功。这就是我想要的:
最佳答案
因此,正如我的评论中所述,只要将 $ErrorActionPreference
设置为 Stop
,您的脚本就应该正确捕获错误。另外,您可以使用 $_
来实际捕获错误:
PS C:\> $admin.SetPassword('supers3cur3p4ssw0rd')
Exception calling "setpassword" with "1" argument(s): "Access is denied.
...
...
因此,如果我们尝试使用 try {...} catch {...}
,您实际上可以获得一个格式正确的错误,其中包含您想要的详细信息:
注意:您还可以使用 $Error[0]
检查最后一个错误。
$ErrorActionPreference = 'Stop' # This should usually be at the top of your script.
$storedError = try
{
$admin.SetPassword('supers3cur3p4ssw0rd')
}
catch
{
[pscustomobject]@{
TimeGenerated = [datetime]::Now
Message = 'Failed to set password on {0}' -f $env:COMPUTERNAME
Exception = $_.Exception.InnerException.Message.Trim()
}
}
这将在我的笔记本电脑上产生以下结果:
PS C:\> $storedError
TimeGenerated Message Exception
------------- ------- ---------
7/14/2021 7:30:09 PM Failed to set password on XXXXX Access is denied.
这就是 ErrorRecord
对象的外观:
PS C:\> $Error[0] | Select-Object *
PSMessageDetails :
Exception : System.Management.Automation.MethodInvocationException: Exception calling "setpassword" with "1" argument(s): "Access is denied.
" ---> System.UnauthorizedAccessException: Access is denied.
--- End of inner exception stack trace ---
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject :
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
关于powershell - 在 Powershell 中验证本地管理员密码更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68385476/