微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Powershell 中验证本地管理员密码更改 编辑

如何解决在 Powershell 中验证本地管理员密码更改 编辑

$adminUser = [ADSI] "WinNT://$name/Administrator"
$adminUser.SetPassword($password)

无论如何要验证这两行代码是否成功更改了本地管理员密码,例如它返回 1 或 0 表示成功或失败?我可以确认这两行确实在我的设备上工作,但计划是通过组策略推出我的脚本,并希望创建脚本是否成功的日志。这是我想要的:

Code Snippet

解决方法

因此,正如我在评论中所说,只要 $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 : {}
,

感谢大家的帮助!以下是我所做的更改:

$ErrorActionPreference = 'Stop'

try 
{
    $adminUser = [ADSI] "WinNT://$name/Administrator"
    $adminUser.SetPassword($password)

    $message = "" + $date + " - Local admin password change success"
    $message | Out-File -FilePath $filePath -Append
}
catch
{
    $errorMessage = [pscustomobject]@{
        TimeGenerated = [datetime]::now
        Message = 'Failed to set Password on {0}' -f $env:COMPUTERNAME
        Exception = $_.Exception.InnerException.Message.Trim()
    }

    $errorMessage | Out-File -FilePath $filePath -Append
}

这是经过几次测试后输出文件的样子:

enter image description here


编辑

$ErrorActionPreference = 'Stop'

# Since this block is running from a loop we can store all "Success" and
# "Failed" objects in a variable which then we can export.
$result = try 
{
    $adminUser = [ADSI] "WinNT://$name/Administrator"
    # Attempt to set password here
    $adminUser.SetPassword($password)

    # If setting password succeeded,create a "Success" object:
    [pscustomobject]@{
        TimeGenerated = [datetime]::now
        ComputerName = $env:COMPUTERNAME
        Status = 'Successfully Set Password'
        Exception = $null
    }  
}
catch
{
    # If setting password failed,create a "Failed" object
    # using the same properties as "Success" object:   
    [pscustomobject]@{
        TimeGenerated = [datetime]::now
        ComputerName = $env:COMPUTERNAME
        Status = 'Failed to Set Password'
        Exception = $_.Exception.InnerException.Message.Trim() # Catch the actual error here
    }
}

# Export the results here,first sort by Status
$result | Sort-Object Status,TimeGenerated |
Out-File -FilePath $filePath
# No need to append,this is far more efficient,# appending to a file causes high amount of Disk I/O which
# would slow down your script.

这将产生如下结果:


TimeGenerated        ComputerName Status                    Exception       
-------------        ------------ ------                    ---------       
7/15/2021 4:57:08 PM COMPUTER-01  Failed to Set Password    Access is denied
7/15/2021 4:57:08 PM COMPUTER-04  Failed to Set Password    Access is denied
7/15/2021 4:57:08 PM COMPUTER-08  Failed to Set Password    Access is denied
7/15/2021 4:57:08 PM COMPUTER-00  Successfully Set Password                 
7/15/2021 4:57:08 PM COMPUTER-02  Successfully Set Password                 
7/15/2021 4:57:08 PM COMPUTER-03  Successfully Set Password                 
7/15/2021 4:57:08 PM COMPUTER-05  Successfully Set Password                 
7/15/2021 4:57:08 PM COMPUTER-06  Successfully Set Password                 
7/15/2021 4:57:08 PM COMPUTER-07  Successfully Set Password                 
7/15/2021 4:57:08 PM COMPUTER-09  Successfully Set Password                 
7/15/2021 4:57:08 PM COMPUTER-10  Successfully Set Password                 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。