GetMailboxStatisticsAndEmail.PS1

Script to export a list of all the mailboxes in an organisation and send the results as attachments to an email.

Gives a list ordered by size and after that ordered by last logon time (to hilight old inactive mailboxes).

Also creates and attaches a CSV listing the mailboxes and the size of each one.

###Send mailbox statistics script
###
### to schedule this use PowerShell.exe -PSConsoleFile "C:\Program Files\Microsoft\Exchange Server\Bin\ExShell.psc1" -Command "./scriptname.ps1"
###
### Change the mail message values in this section


# this needs to be changed depending on version of exchange
Add-PSSnapin "Microsoft.Exchange.Management.PowerShell.Admin"


$FromAddress = "nanotera@nanotera.com.au"
$ToAddress = "nanotera@nanotera.com.au"
$MessageSubject = "Mailbox Size Report from $env:computername "
$MessageBody = "Attached is the current list of mailbox sizes."

### put your SMTP server here 

$SendingServer = "192.168.1.1"

$tempfilename= "$env:temp\listmailboxes1.txt"
$tempfilenamemk1= "$env:temp\listmailboxes1_"

Get-MailboxDatabase | sort-object "server","storagegroup" | Select Server, StorageGroupName, Name, @{Name="Size (GB)";Expression={$objitem = (Get-MailboxDatabase $_.Identity); $path = "`\`\" + $objitem.server + "`\" + $objItem.EdbFilePath.DriveName.Remove(1).ToString() + "$"+ $objItem.EdbFilePath.PathName.Remove(0,2); $size = ((Get-ChildItem $path).length)/1048576KB; [math]::round($size, 2)}}, @{Name="Size (MB)";Expression={$objitem = (Get-MailboxDatabase $_.Identity ) ; $path = "`\`\" + $objitem.server + "`\" + $objItem.EdbFilePath.DriveName.Remove(1).ToString() + "$"+ $objItem.EdbFilePath.PathName.Remove(0,2); $size = ((Get-ChildItem $path).length)/1024KB; [math]::round($size, 2)}}, @{Name="No. Of Mbx";expression={(Get-Mailbox -Database $_.Identity -resultsize unlimited | Measure-Object).Count}} | Format-table -AutoSize | out-file -width 255 $tempfilename


foreach ($mbdatabase in Get-MailboxDatabase  | sort-object "server","storagegroup"  ) { 
echo "Mailboxes in $mbdatabase.identity sorted by size" | out-file -append -width 255 $tempfilename
###Now get the stats and store in a text file
Get-MailboxStatistics -database $mbdatabase.identity  | Sort-Object    @{Expression="Database";Descending=$false}  ,@{Expression="TotalItemSize";Descending=$true} | ft database, DisplayName, lastlogontime ,@{label="TotalItemSize(MB)";expression={$_.TotalItemSize.Value.tomb()}}, ItemCount | out-file -append -width 255 $tempfilename

echo "Mailboxes in $mbdatabase.identity sorted by last logon (oldest first)" | out-file -append -width 255 $tempfilename
Get-MailboxStatistics -database $mbdatabase.identity  | Sort-Object @{Expression="Database";Descending=$false}  ,@{Expression="Lastlogontime";Descending=$false}  | ft database, DisplayName, lastlogontime ,@{label="TotalItemSize(MB)";expression={$_.TotalItemSize.Value.tomb()}}, ItemCount | out-file -append -width 255 $tempfilename

}


###Create the mail message and add the statistics text file as an attachment
$SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject, $MessageBody 

$Attachment = New-Object Net.Mail.Attachment($tempfilename)
$SMTPMessage.Attachments.Add($Attachment)


# get them all in one CSV file per server

foreach ( $mbserver in get-mailboxserver ) {

	$mbs = Get-MailboxStatistics -server $mbserver
	$mbs1 = $mbs   | Sort-Object    @{Expression="Database";Descending=$false}  ,@{Expression="TotalItemSize";Descending=$true} 
	$tmpfile1=$tempfilenamemk1 + $mbserver + ".csv"
	$mbs1 | select database, DisplayName, lastlogontime ,@{label="TotalItemSize(MB)";expression={$_.TotalItemSize.Value.tomb()}}, ItemCount | export-csv -notypeinformation  -Path $tmpfile1
	$Attachment = New-Object Net.Mail.Attachment($tmpfile1 )
	$SMTPMessage.Attachments.Add($Attachment)

}


###Send the message
$SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
$SMTPClient.Send($SMTPMessage)

remove-variable SMTPclient
remove-variable SMTPmessage
Remove-Variable attachment

#should remove temp files
#remove-item "$tempfilename"


Posted in Powershell, VBS, VBA and other scripting., System Administration | Comments Off on GetMailboxStatisticsAndEmail.PS1

get_programs_installed_local.ps1

export a list of all software installed on this windows computer. writes to a csv file in the “current” folder.



#
# 
#

$COTSInstalledSoftware = Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ | Get-ItemProperty

$COTSInstalledSoftware += Get-ChildItem HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\ | Get-ItemProperty

IF (Test-path HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\) {

   $COTSInstalledSoftware += Get-ChildItem HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\ | Get-ItemProperty

}

$CotsInstalledSoftware | where { $_.displayname -ne $null } |  select-object displayname | sort-object displayname | get-unique -asstring | export-csv .\allsoftware.csv


}

Posted in Powershell, VBS, VBA and other scripting. | Comments Off on get_programs_installed_local.ps1

Replace the icon lables “Computer” and “This PC” with something more useful.

This script will read the computers name and domain settings and rename the icon in the form computername.domain.local

This makes it much easier to be certain which desktop you are working on when using multiple remote RDP , mstsc connections.

I cant remember now where I found the “special” CLSID code for the registry entry, without that this wouldn’t be easy to do. It may have been on some of the technet discussions about this.

The registry functions were “borrowed” from http://ss64.com/vb/regwrite.html ,

It works on windows 7 and server 2008, server 2012 r2, windows 8.1

Windows 7 default name is “Computer”
Server 2008 default name is “Computer”
Windows 8.1 default name is “This PC”
Server 2012 default name is “This PC”

I found it annoying that a brand new server install was calling itself a PC 😉

I havent rolled it out in a domain anywhere (yet) but I like the idea of some standardised “useful” text there rather than the generic “computer” or “This PC”

'----------------------------------------------------------------------
' script to replace "Computer" name in windows explorer with the actual computer name.
'----------------------------------------------------------------------
 'dont use the computername from the environment as we want to query domain membership anyway.
 strOldName= readreg("HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\")
 ' get network name if one is available "
 Dim WshNetwork
 Set WshNetwork = CreateObject("WScript.Network")
 dim sysinfo
 Set sysInfo = CreateObject("ADSystemInfo")
 strNewName = lcase( WshNetwork.ComputerName  )
 ' on some computers get an error if the domain is not defined. just use the computername then. 
 On error resume next
 strNewName = strNewName + "." + sysInfo.DomainDNSName
 on error goto 0
 strMyName = Wscript.ScriptFullName
 result = writereg("HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\",strNewName,"REG_SZ")
 ' should do something with the result - ignore it for now. "

 strOldName= "This PC/My Computer label was """ + strOldName + """"
 strNewName = "Label now changed to """ + strNewName + """"
 nl=vbCRLF & vbCRLF 
 call wscript.echo(now & nl & strOldName & nl & strNewName & nl & strMyName )
 wscript.quit


' functions from  http://ss64.com http://ss64.com/vb/regwrite.html

Function WriteReg(RegPath, Value, RegType)
      'Regtype should be “REG_SZ” for string, “REG_DWORD” for a integer,…
      '”REG_BINARY” for a binary or boolean, and “REG_EXPAND_SZ” for an expandable string
      Dim objRegistry, Key
      Set objRegistry = CreateObject("Wscript.shell")

      Key = objRegistry.RegWrite(RegPath, Value, RegType)
      WriteReg = Key

end function

Function ReadReg(RegPath)
      Dim objRegistry, Key
      Set objRegistry = CreateObject("Wscript.shell")

      Key = objRegistry.RegRead(RegPath)
      ReadReg = Key
End Function
Posted in Uncategorized | Comments Off on Replace the icon lables “Computer” and “This PC” with something more useful.

Powershell to list the rights for each mailbox (who can read others mailboxes)

Just need to put your server name and if you want to not include some of the access rights (ie bes server and backup software etc… just add it to the where clause).


Get-Mailbox -server myserver | Get-MailboxPermission | where {$_.user.tostring() -ne "dontshowme" -and $_.user.tostring() -ne "NT AUTHORITY\SELF" -and $_.IsInherited -eq $false} | Select Identity,User,@{Name='Access Rights';Expression={[string]::join(', ', $_.AccessRights)}} | Export-Csv -NoTypeInformation mailboxpermissions.csv

Posted in Powershell, VBS, VBA and other scripting. | Tagged , | Comments Off on Powershell to list the rights for each mailbox (who can read others mailboxes)

Powershell to export list of email forwards on an Exchange Server

this will list all the forwards that are active for mailboxes.


$fwds = get-mailbox | Where-Object { $_.ForwardingAddress -ne $null } | sort Name | select Name, ForwardingAddress

# now get the primary smtp adress of each forward address
foreach ($fwd in $fwds) {
$fwd | add-member -membertype noteproperty -name "ContactAddress" -value (get-Recipient $fwd.ForwardingAddress).PrimarySmtpAddress
}

$fwds | export-csv -path all_forwards.csv

Posted in Hints and Tips, Powershell, VBS, VBA and other scripting. | Tagged , | Comments Off on Powershell to export list of email forwards on an Exchange Server

Powershell to export list of Exchange Server Mailbox email addresses

this powershell snippet will export all the SMTP email addresses used on a mail server, useful to document and check on them.

;
Get-Mailbox -ResultSize Unlimited |Select-Object DisplayName,ServerName,PrimarySmtpAddress, @{Name=“EmailAddresses”;Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq “smtp”} | ForEach-Object {$_.SmtpAddress}}}
 ;

Or to get them all with each address on a new line (for easier importing etc…)

$a=get-mailbox

$objs=@() ; 
foreach ( $u in $a ) {
    foreach ( $ua in $u.emailaddresses ) {
        if ( $ua.prefixstring -ceq "smtp") { 
            $obj=New-Object psobject 
            add-member -inputobject $obj -membertype NoteProperty -name "Alias" -value $u.alias 
            add-member -inputobject $obj -membertype NoteProperty -name "primarysmtpaddress" -value $u.primarysmtpaddress  ; 
            add-member -inputobject $obj -membertype NoteProperty -name "email" -value $ua.smtpaddress
            $objs += $obj  
            }
       }
             
  }

$objs
Posted in Hints and Tips | Tagged , , | Comments Off on Powershell to export list of Exchange Server Mailbox email addresses

Listing files and folders into a document.

Its always been annoying that it isnt trivial to get a list of documents. This powershell code let you create an excel compatible CSV file listing all the files and folders, one with the newest (by creation data) files first.


function export-file-list
{
param ( $foldername)
echo $foldername
$csvfilename1=($foldername + "\dir_listing_by_creation_time.csv")
$csvfilename2=($foldername + "\dir_listing_by_name.csv")
$t = get-childitem -recurse  $foldername |  select fullname, name, lastwritetime, creationtime
foreach ( $f in $t ) {
    $f | fl
	$f1="."+$f.fullname.substring($foldername.length)
	$f.fullname=$f1
    $f1=$f.fullname.substring(0,$f.fullname.length-$f.name.length)
    $f1
    $f | fl
    $f.fullname=$f1
}

$t | select @{Name="Folder";Expression={$_."Fullname"}} , name , lastwritetime , creationtime |  sort creationtime  -descending | export-csv -notypeinformation $csvfilename1
$t  | select @{Name="Folder";Expression={$_."Fullname"}} , name , lastwritetime , creationtime | export-csv -notypeinformation $csvfilename2


}                                                     

export-file-list (  "d:\Shares\Data" )

Posted in Uncategorized | Comments Off on Listing files and folders into a document.

WSS3 sharepoint upgrade to Sharepoint Foundation 2013

WSS3 sharepoint upgrade to Sharepoint Foundation 2013

SBS 2003 and 2007 use the WSS3 version of sharepoint. To upgrade from that to a current version can be a bit tricky. It involves upgrading to the 2010 version of sharepoint foundation and then to 2013. To do this safely install two new servers one for SPF 2010 and one for SPF 2013

Plenty of excellent blog postings explain the details but in summary the steps are:

  1. Make sure your source sharepoint wss3 is up to date (needs to have latest updates for conversion to succeed). You can backup an older one and restore to a current version one for the export.
  2. Make SQL backup using SQL tools or SQLCMD (“”)
  3. Install a foundation 2010 Sharepoint, if you backup is larger than 4 gigs then install it as a farm with SQL server or SQL express R2 (gives 8 gigs). Make sure it is up to date as some earlier versions have issues with upgrade.
  4. Restore the SQL backup of you content database to the new server (either over or into a new database, I did it into a new one called wss_content_wss3 to make it clear it was from the old server.
  5. Reset site collection administrators accounts (needed if not still in domain etc…), check on Alternative mappings. May need to give access via web application for testing.
  6. Once Sharepoint Foundation 2010 version is working do SQL level backup of contentdatabase.
  7. Restore the SQL database to Foundation 2013 server. Make sure this server is up to date
  8. Reset site collection administrators accounts (needed if not still in domain etc…), check on Alternative mappings.
  9. Do upgrade to Claims authentication for user accounts https://technet.microsoft.com/en-us/library/gg251985.aspx
  10. Do Schema database upgrade powershell Upgrade-SPContentDatabase https://technet.microsoft.com/en-us/library/ff607813.aspx

That was simple wasn’t it =)

The things that caused me issues were:

  • If site settings and other editing things give you errors and “list not found” or “object not found” errors check on your site alternative mappings settings.

Fixing new default spacing on menu

SharePoint 2013 has large gaps in the menus on the quicklaunch (and lots of other spots). I guess its for fat fingers on touch screens. We don’t use them so wanted to close it up.

The style to change is (this was padding:5px 20px; – I changed it to 1px (which gives a gap of two I think).

.ms-core-listMenu-verticalBox li.static > .ms-core-listMenu-item { display:block; padding:1px 20px; }

Make this change to your master page (seattle.master in my case).

Posted in System Administration | Leave a comment

ATO Tax calculations in Excel

Some possibly useful excel functions and macros.

save this function in a macro enables excel documnet (xlsm) and then you can use the formula =taxpayable(a1) and it will calculate the tax payable for that gross income.

ATO Tax scales

Australian Tax department “sliding” scales calculation

Function taxpayable(income)
'Stop
If income < 6000 Then
    taxp = 0
    ElseIf income < 35000 Then
        taxp  = 0.15 * (income - 6000)
    ElseIf income < 80000 Then
        taxp  = 4350 + 0.3 * (income - 35000)
    ElseIf income < 180000 Then
        taxp = 17850 + 0.38 * (income - 80000)
    Else
        taxp = 55850 + 0.45 * (income - 180000)

End If
taxpayable=taxp
End Function
Posted in Hints and Tips | Comments Off on ATO Tax calculations in Excel

Changes to twenty ten theme

Based on twenty ten template, add “pretty” pictures with standard width/height for banner headings.

added logo.jpg to images subfolder within template

Added code to header.php to show logo on top of page next to description (logo has white space on rhs).


< id="site-title">
					
						

						
						

					
				>

Altered heading styles to get rid of italics, removed black border around banner headings. Altered background and hover colours of menus.

changes to styles.css

/*
Theme Name: Twenty Ten Child Nano Tera
Theme URI: http://jetsoft.net.au/twentyten-child-nanotera/
Description: waffle
Author: Jeff Turner
Author URI: https://nanotera.com.au/
Template: twentyten
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: childtest
Text Domain: twentyten-child-nanotera
*/


/* =Reset default browser CSS. Based on work by Eric Meyer.
-------------------------------------------------------------- */

html, body, div
/*
LAYOUT: One column, no sidebar
DESCRIPTION: One centered column with no sidebar
*/

.one-column #content {
	margin: 0 auto;
	width: 900px;
}

#site-title {
	float: left;
	font-size: 30px;
	line-height: 36px;
	margin: 5px 0 10px 0;
	width: 700px;
}
#site-description {
	clear: right;
	float: right;
	jet-font-style: italic;
	margin: 5px 0 10px 0;
	width: 220px;
}

/* This is the custom header image */
#branding img {
	border-top: 0px solid #000;
	border-bottom: 0px solid #000;
	display: block;
	float: left;
}


/* =Menu
-------------------------------------------------------------- */

#access {
	background: #000040;
	display: block;
	float: left;
	margin: 0 auto;
	width: 940px;
}

#access li:hover > a,
#access ul ul :hover > a {
	background: #000099;
	color: #fff;
}


#colophon {
	border-top: 4px solid #000099;
	margin-top: -4px;
	overflow: hidden;
	padding: 18px 0;
}

Posted in System Administration | Leave a comment