Capturing powershell warning

喜欢而已 提交于 2019-12-07 13:40:25

问题


I am trying to capture the warning that gets thrown if I try to remove mailbox permissions from a mailbox for someone who doesn't have permissions in the first place.

#$WarningPreference = "continue"
try
{
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
Remove-MailboxPermission -Identity "test2" -User "test1" -AccessRights FullAccess -InheritanceType All -confirm:$False | Out-File c:\temp\output2.txt -Encoding ASCII
}
catch
{
#Write-Warning -Message $($_.Exception.Message) 3 > c:\temp\warning.txt
}

There is no output in either output2.txt or warning.txt - what am I doing wrong?

The warnings I am trying to capture appear in yellow and say:

WARNING: The cmdlet extension agent with the index 0 has thrown an exception in OnComplete(). The exception is:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at Microsoft.Exchange.Data.Storage.ExchangePrincipal.get_ServerFullyQualifiedDomainName()
   at Microsoft.Exchange.Data.Storage.MailboxSession.Initialize(MapiStore linkedStore, LogonType logonType,
ExchangePrincipal owner, DelegateLogonUser delegateUser, Object identity, OpenMailboxSessionFlags flags,
GenericIdentity auxiliaryIdentity)
   at Microsoft.Exchange.Data.Storage.MailboxSession.<>c__DisplayClass12.<CreateMailboxSession>b__10(MailboxSession
mailboxSession)
   at Microsoft.Exchange.Data.Storage.MailboxSession.InternalCreateMailboxSession(LogonType logonType,
ExchangePrincipal owner, CultureInfo cultureInfo, String clientInfoString, IAccountingObject budget, Action`1
initializeMailboxSession, InitializeMailboxSessionFailure initializeMailboxSessionFailure)
   at Microsoft.Exchange.Data.Storage.MailboxSession.ConfigurableOpen(ExchangePrincipal mailbox, MailboxAccessInfo
accessInfo, CultureInfo cultureInfo, String clientInfoString, LogonType logonType, PropertyDefinition[]
mailboxProperties, InitializationFlags initFlags, IList`1 foldersToInit, IAccountingObject budget)
   at Microsoft.Exchange.Data.Storage.MailboxSession.OpenAsSystemService(ExchangePrincipal mailboxOwner, CultureInfo
cultureInfo, String clientInfoString)
   at Microsoft.Exchange.ProvisioningAgent.MailboxLoggerFactory.XsoMailer.Log(AdminLogMessageData data,
LogMessageDelegate logMessage)
   at Microsoft.Exchange.ProvisioningAgent.AdminLogProvisioningHandler.OnComplete(Boolean succeeded, Exception e)
   at Microsoft.Exchange.Provisioning.ProvisioningLayer.OnComplete(Task task, Boolean succeeded, Exception exception)
WARNING: Can't remove the access control entry on the object "CN=xxxxx" for account "xxxxx" because the ACE doesn't exist on the
object.

Thanks for all the help so far! My code now looks like this:

$WarningPreference = "continue"
try
{
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
Remove-MailboxPermission -Identity "test1" -User "test2" -AccessRights FullAccess -InheritanceType All -confirm:$False 2> c:\temp\errors.txt 3> c:\temp\warnings.txt -ErrorAction Stop
}
catch
{
2> c:\temp\errors.txt
}

*FINAL SOLUTION - THANKS ALL *

$WarningPreference = "continue"
try
{
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
Remove-MailboxPermission -Identity "test1" -User test2" -AccessRights FullAccess -InheritanceType All -confirm:$False 2> c:\temp\errors.txt 3> c:\temp\warnings.txt -ErrorAction Stop
}
catch
{
$_ > c:\temp\errors.txt
}

回答1:


Given the question's generic title, let me first recap how capturing warnings works in general:

  • To a file such as warnings.txt: with 3> warnings.txt

    • To suppress warnings ad hoc: 3> $null
  • In a variable such as $warnings: with -WarningVariable warnings (-wv warnings)

    • However, that still passes the warnings through and therefore prints them, so in order to prevent that you must also use 3> $null.

Note that these constructs must be applied to the very command producing the warnings, as (by default) only the success output stream (the stream with index 1) is sent through the pipeline:

# OK - saves warnings to file 'warnings.txt' without printing them.
Do-Stuff 3> warnings.txt | Out-File out.txt

# INCORRECT - still prints warnings, because they are NOT sent through the 
#             pipeline, and then creates empty file 'warnings.txt', because
#             Out-File itself produces no warnings.
Do-Stuff | Out-File out.txt 3> warnings.txt

As for what you tried:

There is no output in either output2.txt or warning.txt

  • Presumably, there is no output in output2.txt, because the Remove-MailboxPermission has not produced any success output yet at the time it throws an exception. When the exception occurs, control is instantly transferred to catch handler, so the pipeline is stopped right there, and Out-File never receives input from Remove-MailboxPermission's success stream.

    • Note that try / catch only takes effect if Remove-MailboxPermission produces a statement-terminating error by default; to also make it take effect for non-terminating errors, add -ErrorAction Stop.
      If the Remove-MailboxPermission produces just warnings - and no error at all - then try / catch won't have any effect.
  • There is no output in warning.txt (even with the line re-activated by removing the initial #), because try / catch only catches error output, not warnings; that is, the warnings have already printed by the time the catch handler is processed.




回答2:


Add -WarningAction Stop or -ErrorAction Stop to your Remove-MailboxPermission command:

try
{
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
Remove-MailboxPermission -Identity "test2" -User "test1" -AccessRights FullAccess -InheritanceType All -confirm:$False -WarningAction Stop -ErrorAction Stop | Out-File c:\temp\output2.txt -Encoding ASCII
}
catch
{
#Write-Warning -Message $($_.Exception.Message) 3 > c:\temp\warning.txt
}



回答3:


Use the -WarningAction and -WarningVariable common parameters to capture the warning to a variable and cause it to not show to the console.

Remove-MailboxPermission -Identity "test2" -User "test1" -AccessRights FullAccess -InheritanceType All -confirm:$False | Out-File c:\temp\output2.txt -Encoding ASCII -WarningAction SilentlyContinue -WarningVariable CapturedWarning

Then, $CapturedWarning should have the warning in it.



来源:https://stackoverflow.com/questions/47376768/capturing-powershell-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!