DeleteContents from mailbox with no confirmation (exchange 2010 and powershell) - powershell

I use the following command to delete the contents of a mailbox, but it still prompts me to confirm. Is there a way to not prompt me.
Search-Mailbox -id "UserName" -DeleteContent -Confirm:$false

The way to stop prompting is to use the -Force parameter (if the cmdlet supports it).
Setting -Confirm to $false just means "prompt me if you need to." Setting -Confirm to $true means "prompt me every time."

There seems to be a syntax error -confirm like -DeleteContent is a SwitchParameter this means that you just have to omit it.
Search-Mailbox -id "UserName" -DeleteContent

Simple thing just go through /Library/Mail/v2/MailData and delete the files with names
Envelope then all the contents will be deleted from Mail App

Related

How can I capture the Powershell informational console output to a variable?

I can't seem to figure out how to capture the quoted text below for parsing. I've tried setting it to a variable as well as redirecting all streams with *>&1 . How can I grab the output text? The *>&1 works for errors, but not for the text below for some reason? Writing to a file is not an option.
Connect-Mailbox -Identity $guidT -user $targetDNT -Alias $aliasT -Database $databaseT -DomainController $domainSpecificDCsSourceAccountT[0]
I've also tried
$outValue = Connect-Mailbox -Identity $guidT -user $targetDNT -Alias $aliasT -Database $databaseT -DomainController $domainSpecificDCsSourceAccountT[0] *>&1
WARNING: The operation completed successfully but the change will not
become effective until Active Directory replication occurs.
[edit]
For repro, this command appears to fall into the same situation, and is easier to setup/configure
$var = Set-Mailbox $sourceUserT -LitigationHoldEnabled $false
[edit2]
Some commands like set-mailbox will work if you change the type from a string to an array such as but connect-mailbox is not able to use that?
So this was kind of dumb luck, it works for the set-mailbox command but not the connect-mailbox command?
PS> Set-Mailbox "first.last" -LitigationHoldEnabled $false -WarningVariable wv
WARNING: The command completed successfully but no settings of 'xxx/last, first' have been modified.
PS> $wv
PS>
However when it did it this way
[System.Collections.ArrayList]$wvar = #();
Set-Mailbox "onprem.detailee1" -LitigationHoldEnabled $false -WarningVariable +wvar
WARNING: The command completed successfully but no settings of 'xxxx/last, first' have been modified.
PS> write-host $wvar
The command completed successfully but no settings of 'xxxx/last, first' have been modified.
So Powershell cannot cast some outputs (warning, error, etc) to a string, however they can add the object to an array. Strangely enough the non-typing portion of the Powershell language is not applicable here.
You should be able to use the -WarningVariable Common Parameter to capture messages destined for the warning stream.
Connect-Mailbox -Identity $guidT -user $targetDNT -Alias $aliasT -Database $databaseT -DomainController $domainSpecificDCsSourceAccountT[0] -WarningVariable WarningVar
$WarningVar
The common parameters include variable options for messages sent to the error, information, and warning streams.
One way I found to do this was to set erroraction explicitly to stop (-ea stop) for the cmdlet in a try catch statement, then I could get the exception value with $_.Exception.Message in the catch statement as it forces the cmdlet to have a terminating error.
This is something I've found to be frustrating coming from c# where a try/catch statement works without having to explicitly define an error as terminating or not. If you do not do that for some cmdlets, the try/catch will not work and it will never catch the terminating error.
Hopefully this helps others, more info
https://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell
The problem most likely stems from buggy behavior with respect to streams from implicitly remoting commands, such as created via Import-PSSession; this GitHub issue is presumably related.
You have already found one workaround, as demonstrated in your question: if you explicitly create the target variable to pass to -WarningVariable as a System.Collections.ArrayList instance and pass the variable name prefixed with + (-WarningVariable +var) - normally intended for appending to a preexisting variable value - capturing the warning(s) is possible.
A slightly simpler workaround is to call the command via Invoke-Command and apply -WarningVariable to the latter:
Invoke-Command -WarningVariable warnings {
Connect-Mailbox -Identity $guidT -user $targetDNT -Alias $aliasT -Database $databaseT -DomainController $domainSpecificDCsSourceAccountT[0]
}
# $warnings now contains any warnings emitted by the command.
Did you try the following?
$var = myCommand | out-string

Deleting an email using powershell

I want to delete an email from Exchange serveur and then from the mailbox received items,so I used this following powershell command but after a while , powershell_ise crashes and it closes
Search-Mailbox -Identity "Khalil Med" -SearchQuery 'Subject:"Phishing"' -DeleteContent
I live in the ISE daily and sometimes VSCode as needed and I do this sort of thing regularly in the ISE and VSCode, neither have crashed on me for this kind of use case. Yet, environments can differ. I find it hard to understand how running this simple request would crash the ISE, as it's not doing anything $psISE / ISE GUI specific.
Are you doing this on the Exchange server directly, or via Explicit or Implicit remote session from your admin workstation?
Also, make sure you have the RBAC role to perform this...
Get-ManagementRoleAssignment -Role 'Mailbox Import Export'
New-ManagementRoleAssignment -Role 'Mailbox Import Export' -User 'Administrator'
... and make sure you are getting something to act on, meaning actual emails using...
Search-Mailbox -Identity 'HostMaster TestUser' -SearchQuery "Subject:test" -EstimateResultOnly
If the response from the above is '0', then well, you now know why the -DeleteContent did not actually work.
As a sanity check. Rather than looking at one account. Look at all accounts to see if you are getting any hits on anyone..
Get-Mailbox -ResultSize Unlimited |
Search-Mailbox -SearchQuery 'Subject:test' -EstimateResultOnly -Force |
Where-Object -Property ResultItemsCount -gt 0

Using Read-Host to output information from a script

I am trying to run a script against exchange to bring back all of the mailboxes a certain user has access to. I want to be able to input the usersname using read-host. I currently have this:
$username = Read-Host("Please enter users username")
#Enable Exchange cmdlets
add-pssnapin *exchange* -erroraction SilentlyContinue
Get-MailBox | Get-MailboxPermission -User $username | FL > C:\MailboxPermissions.txt
However, when I run this via powershell, it asks for the username, looks like it is starting to run the script, then powershell just exits and there is not data outputted
Any help would be greatly appreciated
Thanks for all the help
I finally figured it out and there were a couple of issues. It was to do with the result size. I added -resultsize unlimited:
$username = Read-Host("Please enter users username")
add-pssnapin *exchange* -erroraction SilentlyContinue
>Get-MailBox -resultsize unlimited | Get-MailboxPermission -User $username | FL > C:\MailboxPermissions.txt
It would also not work by running the .ps1 file as this was not run by admin, and it needs admin permissions to output to the location I want. Once I created a shortcut for it to run via the powershell.exe with admin credentials it is now working as expected.
The problem is that you are only out putting to the screen.
This means that when you run your script it will carry out the required action, print to screen and close the window immidiatly. In turn, this means you can't see the output.
As #DarkLite1 mentioned, you could output to a file.
Or, you could simply allow the console to wait before closing. This is done like this at the end of your code:
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
You may also need a Write-Host on the last action in your code snippet, I'm not entirely sure as I am not familiar with how Get-Mailbox works, but try it without first.
To summarize, You must keep the window open or print the results to file to actually see anything. The code you have currently will complete so fast you will never see any output.

Set-MailboxFolderPermission does not, what it should do

I'm currently working on a script to change some Mailboxfolderpermissions in Exchange 2010.
The basic functions work, I can read out the current permission-status and I can set permissions, but the cmdlet Set-Mailboxfolderpermission does not correctly set the permissions.
For example:
Set-MailboxFolderPermission -Identity Owner:\Calendar -User TargetUser -AccessRights Contributor
This results in a custom named setting, where nothing changed in relation to the previous setting.
Same thing when I substitute Contributor with the explicit permissions FolderVisible, CreateItems.
Update:
I just tried to use the cmdlet from the shell and there it works.
To test whether the internal output is right, I printed the permissions on the shell and everything was fine.
Right now I'm wondering even more.
What is the point here? Is it a bug, am I to frustrated to see the right way out of my problem?
I use the below - just be certain to use the UPN & Set permission - Set doesn't always work - You could just first remove the current & then add a different permission:
Remove-MailboxFolderPermission -identity "Owner#something.com:\calendar" -User targetUser#something.com
Add-MailboxFolderPermission -identity "Owner#something.com:\calendar" -User targetUser#something.com -AccessRights owner

Powershell 2: Unable to suppress warning message

I am making a cmdlet call to 'set-distributiongroup' in powershell 2. I am simply setting the value of the parameter 'hiddenFromAddressListsEnabled' to a pre-defined boolean value.
However, no matter what I try, it displays a warning message if the boolean assignment is not actually changing the current value of 'hiddenFromAddressListsEnabled'.
Here is the main command I'm invoking:
set-DistributionGroup -identity TestGroup `
-hiddenFromAddressListsEnabled=$true
Let's semantically define what I have above as 'command'.
Now, I've tried adding several different variants, all with proper line-continuation and syntax. Here are those variants:
command > $null
command 2> $null
command -ErrorAction:silentlycontinue
command -ErrorVariable $throwAway
command -WarningAction:silentlycontinue
command -WarningVariable $throwAway
$var = command
Regardless of various combinations of one or more of the above, I still get a yellow WARNING: message spit to output. Specifically, this:
WARNING: The command completed successfully but no settings of
'<xxxxxx>/Users/TestGroup' have been modified.
Any suggestions on a key concept I'm not understanding? I want the command to not produce this output, and I want it to silently continue if this occurs.
Thanks!!
I've been trying to suppress the warning messages when stopping a service:
WARNING: Waiting for service 'Service Description' to finish stopping...
The following worked for me:
Stop-Service $svc.Name -WarningAction SilentlyContinue
If it's just a warning that cause problem why don't you set in your script $WarningPreference variable ?
PS C:\> $WarningPreference='silentlycontinue'
PS C:\> Write-Warning "coucou"
PS C:\> $WarningPreference='continue'
PS C:\> Write-Warning "coucou"
AVERTISSEMENT : coucou
just bumped this topic when searching on the issue,
my case PowerShell v2 , only after setting
$WarningPreference = "SilentlyContinue"
Write-Warning "blah" - returned me nothing... the parameter on the command didn't changed much too on my end.
You may be hitting this bug: http://connect.microsoft.com/PowerShell/feedback/details/541500/warning-verbose-and-debug-streams-do-not-respect-action-preferences-the-way-they-should
Anyway, your command should look like:
Set-DistributionGroup -Identity TestGroup -HiddenFromAddressListsEnabled $true
Your command is wrong. Which is the the reason why you get a yellow error message. The command should look like:
Set-DistributionGroup -Identity TestGroup -HiddenFromAddressListsEnabled $true
Or
Set-Distributionaliste -Identity TestGroup -HiddenFromAddressListsEnabled:$true
But not
Set-DistributionGroup -Identity TestGroup -HiddenFromAddressListsEnabled=$true
I was getting the same problem with the Exchange Management Console in 2010. Problem is the EMC runs on PowerShell 2.0, which as stated before has some bugs around warning preferences.
I found a cheeky workaround was to run my script in a vanilla PowerShell 4.0 shell, and then import the EMC cmdlets and start a new remote PS session like so...
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
...then, -WarningAction:SilentlyContinue suddenly starts behaving itself.
You should try
Set-DistributionGroup -Identity TestGroup -HiddenFromAddressListsEnabled $true -WarningAction silentlyContinue
I bumped into same issue, the following command seems to do the job (PS 3.0) :
Stop-Service<or whatever command> $svc.Name -WarningPreference SilentlyContinue
Don't know exactly what difference it makes with -WarningAction, though.
Hope this helps !
If you invoke powershell versión 2.0, you should use "-WarningAction silentlyContinue". I was having the same issue, but in the script, if I invoke, for example "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -versión 2.0" , then you can use this parameter. I was trying on a scheduled task and using a ps1 script.
Try something like that:
PS C:\> {command} | Out-Null
For more Information: Technet: Out-Null