Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Monday, January 11, 2010

Script to pull database stats and e-mail results

With some help from a coworker (irundis.com), I got this script put together for pulling database stats, and then e-mailing the results to an e-mail recipient. The idea is to just attach this to a scheduled task and let it run. It is a good thing I got help or I'm positive it wouldn't be quite this pretty.

Scheduled Task:

Program/Task:

C:\windows\system32\windowspowershell\v1.0\powershell.exe

Arguments:

-PSConsoleFile "C:\Program Files\Microsoft\Exchange Server\bin\exshell.psc1" -noexit -command ". C:\DBStats.ps1

-------------------------------------------------------------
Script (be careful about returns if you copy/paste)
-------------------------------------------------------------

function Get-MXDBData() {
PROCESS {

$identity = $_.Name
$FullID = $_.identity
$FilePath = $_.EdbFilePath.PathName
$SizeMB = [long]([long]((Get-ChildItem $FilePath).length) / 1048576)
$SizeGB = [long]($SizeMB / 1024)
$MBXCount = (Get-Mailbox -database $FullID).count

#Create the new custom object and add new members to the object
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Database $identity
$obj | Add-Member NoteProperty "Size in GB" $SizeGB
$obj | Add-Member NoteProperty "Size in MB" $SizeMB
$obj | Add-Member NoteProperty "Mailbox Count" $MBXCount

#Output the object to gain access to all of its properties for later in the pipeline.
Write-Output $obj
}
}

Get-MailboxDatabase -Server SERVER | Get-MXDBData | export-csv -path c:\DBStats.csv -NoTypeInformation

################
# SMTP Mail Alert
################

$file = "c:\DBStats.csv"

#Create new .NET object and assign to variable
$mail = New-Object System.Net.Mail.MailMessage

#Sender Address
$mail.From = "sender@domain.com";

#Recipient Address
$mail.To.Add("recipient@domain.com");

#Message Subject
$mail.Subject = "Database Statistics Report";

#Message Body
$mail.Body = "Please see attached CSV for database size and mailbox count.";

#Connect to your Hub Transport (FQDN or NLB alias)
$smtp = New-Object System.Net.Mail.SmtpClient("fqdn.domain.com");

#Attach CSV
$attachment = new-object Net.Mail.Attachment($file)
$mail.Attachments.Add($attachment)

#Uncomment if no anonymous relay (best practice to have separate receive connector)
# $smtp.Credentials = New-Object System.Net.NetworkCredential("username", "passwd");

#Send Email
$smtp.Send($mail);

$attachment.Dispose()


Example of output before CSV:


Monday, May 18, 2009

Powershell Reboot

Ever need to reboot a server remotely, and no standard tools (shutdown, etc) are working?

Can't RDP the box or get to it any other way?

I discovered a little trick about a year and a half ago, and it has been saving my life, and those of my colleagues ever since.  I just actually had to use it, which reminded me that I ought to post it.

$server = gwmi win32_operatingsystem -computer USSERVER1
$server.reboot()

Performing this will provide you with some output.  As long as it comes back with an output of zero, you are good to go.  I believe the target server doesn't even need powershell installed; just the one you are using to reboot it.


Wednesday, March 4, 2009

Deleting a Message From Everyone's Mailbox

Need to delete a message from everyone's mailbox at the server level?  Here is the command for you:

Get-Mailbox | Export-mailbox -SubjectKeywords "FillintheSubject" -StartDate "03/04/09" -EndDate "03/04/09" -TargetMailbox "Admin" -TargetFolder "Inbox" –DeleteContent

You can also add -ContentKeywords for additional filtering.

Sunday, February 15, 2009

Parts on order!

Finally buckled and decided a new computer is for me.  After a ton of research, my build is as follows.  This isn't meant to be the biggest beast on the block, but price for power, it seems to be the best bargain.

I went mostly with NewEgg.com because I just like the service I've gotten from them in the past.

AMD Phenom II X4 940 Deneb 3.0GHz 4 x 512KB L2 Cache 6MB L3 Cache Socket AM2+ 125W Quad-Core Black Edition Processor on a Foxconn A79A-S AM2+/AM2 AMD 790FX ATX AMD Motherboard.  This was a combo from NewEgg and seemed to be the best deal.  I originally was only looking at Intel processors, but after reviewing numerous benchmarks, I couldn't beat the power for the price.

HIS Hightech H487F1GP Radeon HD 4870 1GB 256-bit GDDR5 PCI Express 2.0 x16 HDCP Ready CrossFire Supported Video.  Though the GPU is slightly under the next bump up, the price price jumped significantly.

Corsair ddr2-1066 pc2-8500 4gb.  I would have gone with the cheaper Patriot, but Fry's was out, and I missed the deals on NewEgg.  I'd probably save the $40 and go with Patriot if I had it to do over again.  Corsair's warranty is better though, so that is a plus.

1.5 TB SATA drive from Dell.  Can't beat ~$100 + shipping.  Coworker hooked me up with a coupon.  Now I just need to figure out how I'm going to fill 1.5TB..images perhaps..

750w Corsair PSU.  I am no expert on power, nor do I claim to be.  That being said, it was a good price and single 12V rail with good reviews.  I was looking at the ThermalTake with it's 4x 12V rails, but from what I've read it really doesn't matter how many rails it has as long as the single has decent components (which mine should).  The split rails can help with power management, but a single rail also helps make to ensure that core components have the power they need without being limited.  (4 rails could mean 13A, 16A, 18A, 8A which can just get confusing).  If I'm way off base here, feel free to leave me a comment and contradict me. :)

I went with the Sunbeam CR-CCTF 120mm "Core Contact Freezer" for cooling.  From what I can tell, the ThermalRight 120 Ultra Black Edition seemed like the best choice, but at half the price, the SunBeam was more appealing to me.  All reviews point toward it being quite comparable.  Tomshardware and Frostytech both show the "Core Contact Freezer" as being near the top of the charts.  Can't beat $30 from NewEgg for a quality product.

I'll be using Arctic Silver for the thermal compound as well.  We'll see how it goes.  Should be here in a few days..  Hopefully everything fits in the case and on the motherboard without covering RAM slots..

Friday, August 29, 2008

Quick Powershell Templates vol1

GET MAILBOXES WITH X ACTIVESYNC POLICY

Get-CASMailbox -resultsize unlimited | Where {$_.ActiveSyncMailboxPolicy -eq "Policy Name "} | export-csv C:\outputDefault.csv

You could also replace “| export-csv C:\outputDefault.csv” with “>> file.txt” or “| Out-File c:\file.txt”


Script for identifying and pulling event logs

Param (

[string] $ID

)

Get-Eventlog Application | where {$_.EventID -eq $ID}


ALLOW SHAREPOINT / DISALLOW UNC or File shares

Set-ActiveSyncMailboxPolicy -Identity ContosoMobo -UNCAccessEnabled $false -WSSAccessEnabled $true


Pull Mailbox size and sort

Get-Mailbox -Database <mbdb> | Get-MailboxStatistics | select DisplayName,TotalItemSize | sort TotalItemSize


Change OWA time out

set-ItemProperty ‘HKLM:\SYSTEM\CurrentControlSet\Services\MSExchangeOWA’ -name TrustedClientTimeout -value 1440 -type dword


RAISED RULES QUOTA

Get-Mailbox | Where {$_.RulesQuota -ne "64KB"} | Select Name, RulesQuota


FIND USERS ANTISPAM BYPASS SET

Get-Mailbox | Where {$_.AntispamBypassEnabled -eq $True} | Select Name, AntispamBypassEnabled


FIND USERS WITH SEND ON BEHALF OF VALUE

Get-Mailbox | Where {$_.GrantSendOnBehalfTo -ne $null} | Select Name, GrantSendOnBehalfTo


FIND PEOPLE WHO’S ITEM RETENTION NOT DEFAULT

Get-Mailbox | Where {$_.UseDatabaseRetentionDefaults -eq $False} | Select Name, UseDatabaseRetentionDefaults


FIND PEOPLE HIDDEN FROM GAL

Get-Mailbox | Where {$_.HiddenFromAddressListsEnabled -eq $True} | Select Name, HiddenFromAddressListsEnabled


FIND EXCEPTIONS TO SIZE RESTRICTIONS

Get-Mailbox | Where {$_.UseDatabaseQuotaDefaults -eq $false} | Select Name, IssueWarningQuota, ProhibitSendQuota, ProhibitSendReceiveQuota


PULL MAILBOX STATS FOR USERS

Get-Mailbox -Filter { (Name -eq "Name1") -or (Name -eq "Name2") -or (Name -eq "Name3") } | Get-MailboxStatistics | Format-Table


BLOCK EXTENSIONS AND DELETE WITH NO NDR

Add- AttachmentFilterEntry -Name *. ext -type FileName

Set- AttachmentFilterListConfig -Action SilentDelete

Restore RSGMAILBOX TO:

Restore-Mailbox -Identity "Name2" -RSGDatabase MyRSGDatabase -RSGMailbox "Name1" -TargetFolder Extraction -SubjectKeywords "Meeting"

Places a copy of all items where the subject contains the word "Meeting" from Name1 recovered mailbox into Name2’s mailbox under the folder named Extraction.


REMOTE MOBILE WIPE

Clear-ActiveSyncDevice -Identity WINMOBILE


RESTORE AFTER RSG LOADED

Restore-Mailbox -Identity "Name1" -RSGDatabase Alpha -RSGMailbox "Name2" -TargetFolder NameRecovery


ENABLE OUTLOOK ANYWHERE

Enable-OutlookAnywhere -Server:ExchCas1 -ExternalHostName:mail.domain.com -SSLOffLoading:$false -ExternalAuthenticationMethod:Basic

(After RPC/HTTP is installed as well as cert)


SEND AS/ RECEIVE AS

$server = Get-MailboxServer SERVERNAME

Add-ADPermission -Identity $server.Identity -User "domain\user" -ExtendedRights ("Send As", "Receive As")

OR

Get-mailboxserver <servername> | add-adpermission –user <service account> -accessrights GenericAll -extendedrights Send-As, Receive-As, ms-Exch-Store-Admin

PULL Mailbox size and sort

Get-Mailbox -Database <mbdb> | Get-MailboxStatistics | select DisplayName,TotalItemSize | sort TotalItemSize


RECOVERCMS

Stop-ClusteredMailboxServer

setup.com /RecoverCMS /CMSName:servername /CMSIPAddress:ipaddress

Setup.com /ClearLocalCMS /CMSName:servername

Enable-StorageGroupCopy servername\SG1 -StandbyMachine standbyservername