Ответ в окне сообщения дает необработанное исключение - PullRequest
0 голосов
/ 16 мая 2019

Я пытаюсь создать инструмент для отключения пользователей.И я хочу создать окно сообщения «Пожалуйста, подтвердите, что хотите это сделать».

Итак, я сделал следующую функцию, чтобы отключить пользователя, но когда я вызываю функцию и нажимаю Нет в окне сообщения, я получаюнеобработанное исключение.

Если я запускаю первый оператор IF с некоторым кодом, после этого он работает нормально, просто не тогда, когда я вызываю функцию.

Есть идеи?

function DisableUser { 
    if ([System.Windows.Forms.MessageBox]::Show("Are you really really really sure you want to disable this user?`n`n" + $labelNameValue.Text, "Are you sure sure?", "YesNo", "Warning") -eq "No") {
        Break
    }

    $DisabledUsersOU = "OU=Disabled Users,DC=domain,DC=local"

    $userObject = Get-ADUser -Identity $textboxSearch.Text -Properties Manager
    $adGroups = Get-ADPrincipalGroupMembership -Identity $userObject.SamAccountName | Where-Object { $_.Name -ne "Domain Users" } | Sort-Object

    # REMOVE -WhatIf

    Remove-ADPrincipalGroupMembership -Identity $labelUsernameValue.Text -MemberOf $adGroups -Confirm:$false -WhatIf
    $userObject | Move-ADObject -TargetPath $DisabledUsersOU -WhatIf
    Set-ADUser $userObject -Manager $Null -Description "$date Disabled by $env:USERNAME" -WhatIf
    Disable-ADAccount -Identity $userObject -WhatIf

    [System.Windows.Forms.MessageBox]::Show("User would have been disabled if this button worked!`nBut is doesn't, so nothing happend.", "BANG!!!!!!", "Ok", "Information")
}

Это сообщение об ошибке, которое я получаю:

************** Exception Text **************
System.Management.Automation.BreakException: System error.
   at System.Management.Automation.Interpreter.ThrowInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)
   at System.Management.Automation.DlrScriptCommandProcessor.RunClause(Action`1 clause, Object dollarUnderbar, Object inputToProcess)
   at System.Management.Automation.DlrScriptCommandProcessor.Complete()
   at System.Management.Automation.CommandProcessorBase.DoComplete()
   at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop)
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
   at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
   at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)
   at System.Management.Automation.ScriptBlock.InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, Boolean createLocalScope, Dictionary`2 functionsToDefine, List`1 variablesToDefine, ErrorHandlingBehavior errorHandlingBehavior, Object dollarUnder, Object input, Object scriptThis, Pipe outputPipe, InvocationInfo invocationInfo, Object[] args)
   at System.Management.Automation.ScriptBlock.<>c__DisplayClass57_0.<InvokeWithPipe>b__0()
   at System.Management.Automation.Runspaces.RunspaceBase.RunActionIfNoRunningPipelinesWithThreadCheck(Action action)
   at System.Management.Automation.ScriptBlock.InvokeWithPipe(Boolean useLocalScope, ErrorHandlingBehavior errorHandlingBehavior, Object dollarUnder, Object input, Object scriptThis, Pipe outputPipe, InvocationInfo invocationInfo, Boolean propagateAllExceptionsToTop, List`1 variablesToDefine, Dictionary`2 functionsToDefine, Object[] args)
   at System.Management.Automation.ScriptBlock.InvokeAsDelegateHelper(Object dollarUnder, Object dollarThis, Object[] args)
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

1 Ответ

0 голосов
/ 16 мая 2019

Я не уверен, почему вы получаете эту ошибку. Может быть потому, что способ отображения вашего сообщения может сделать его позади других окон. Запуск его несколько раз без осознания того, что более ранние экземпляры ожидали ввода пользователя, может привести к сообщениям об ошибках.

Возможно, лучше попробовать это:

Add-Type -AssemblyName Microsoft.VisualBasic

$title   = "Are you sure sure?"
$message = "Are you really really really sure you want to disable this user?`r`n`r`n$($labelNameValue.Text)"
$buttons = "YesNo"     # choose from "OKOnly", "OKCancel", "AbortRetryIgnore", "YesNoCancel", "YesNo", "RetryCancel"
$icon    = "Question"  # choose from "Critical", "Question", "Exclamation", "Information"
if ([Microsoft.VisualBasic.Interaction]::MsgBox($message, "$buttons,SystemModal,$icon", $title) -eq 'No') {
    return   # exit the function
}

вместо

if ([System.Windows.Forms.MessageBox]::Show("Are you really really really sure you want to disable this user?`n`n" + $labelNameValue.Text, "Are you sure sure?", "YesNo", "Warning") -eq "No") {
    Break
}

Я немного запутался во всех различных способах обращения к удаляемому пользователю. Я вижу, как $textboxSearch.Text, $labelUsernameValue.Text, $labelNameValue.Text и $userObject смешаны в этой функции. Может быть, подумать немного дольше?

Из-за флага SystemModal окно сообщений появится сверху, поэтому больше нет шансов скрытых предупреждений.

П.С. break не выходит из функции. Обычно используется в циклах и операторах switch. Если используется в этом контексте, break будет «прерываться» из цикла или оператора switch. Используйте return вместо

Надеюсь, что помогает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...