Move all operations master roles in script.

If you need to move all the ops master roles to one server you can do it with this script.

ntdsutil roles connections "connect to server servername" quit "transfer pdc"  "transfer rid master" "transfer infrastructure master"  "transfer naming master" "transfer schema master" quit quit  
Posted in System Administration | Comments Off on Move all operations master roles in script.

Creating 2048 bit and SHA-2 Certificate request in SBS 2008 and Server 2008

Now that google chrome is “warning” about SHA-1 hashed certificates and most certification authorities seem to be issuing only 2048 bit encryption ones it is a good idea to update any certificates with the lower level hashing and encryption. The older versions of windows server such as SBS 2008 and Server 2008 don’t make it easy to request the higher level certificates. These steps below let you create and install a new certificate from an external authority.

To create the request you need to:

Run MMC and then “add or remove snap-ins” to load the Certificate Templates and Certificates management consoles. Load the Certificates console for the Local Computer.

Use the certificate template snap-in to copy the web-server template and then edit it. Make it as 2048 bit and SHA256.
certificate_template_copy_of_web_server_sha256
Then use the certificates snapin to create a custom request.
certificate_custom_request_sha256
Base it on the template made in the first step.
certificate_custom_request_template
When it gets to the Certificate Information page, click the Details and properties “buttons” to get access to the important information.
Enter you Common Name, Country, Organisation, etc…
Make sure you make the private key exportable and check that the key size is 2048 and hash algorithm is sha256.

certificate_custom_request_details

Then save that certificate request as a file and use that to submit to your certification authority. Once you recieve the certificate from your authority you can use the certreq tool to satisfy the request and it will be added back to the Certificates store.

certificate_custom_request_resolve

Then you can move or Export that now valid certificate (which is in the local computer / personal certificate store) including its private key (with a password). Once you have done that you can import that key (using the password) into your web server and assign it to the web site you needed it for. Exporting the private key with the certificate means it can be imported to any machine not just the one it was created on.

Posted in System Administration | Tagged , , | Comments Off on Creating 2048 bit and SHA-2 Certificate request in SBS 2008 and Server 2008

Get list of Active directory groups and members

$allgroups=get-adgroups
$t = foreach  ($g in $allgroups) {
	$m = get-adgroupmember $g
	foreach ( $me in $m ) {
		$me | add-member -membertype noteproperty -name "groupname1" -value $g.name  -force
	}
	$m | select 
}  

$t | select  *groupname, name | export-csv -path ExportedGroupMembers.csv  
Posted in Powershell, VBS, VBA and other scripting., System Administration | Comments Off on Get list of Active directory groups and members

Archiving windows event logs.

If you select the option in windows event logs to archive old event logs it will create files of the format that event viewer can open.

An event ID 1105 will be created as the first item in the new log if it is the security log, other logs such as forwarded events will cause a 105 event id in the system log.

event_ID_1105

By selecting to trigger a task when this event is generated we can automatically run a script that moves the archive files to a backup location. The log files compress well and putting them into an NTFS compressed folder should save a lot of space.

A simple cmd script that will move the archive files out.

@set moveto=F:\ServerBackups\SERVERNAME\EventLogs
@date /t 
@time /t 
@%homedir%
@cd "%systemroot%\system32\winevt\logs"
@echo event log has been archived due to size limit - now move to archive storage. 
cd
move archive*.evtx %moveto%

Another option is to use this powershell script, this will move all the archived event log files from the default location to another. It will then “cleanup” the archive location and remove all files more than 30 days old. However it will only remove the files that have been backed up (archive bit cleared).

The location and number of days can be specified on the command line (options to the task), the first option is the name of the directory to move the files (the subfolders, computername and eventlogs need to be created manually first) and the second the number of days old a file must be before it is removed.

The default location is d:\serverbackups and the default number of days is 30. Remember that files will only be removed if they have been backed up or had their archive bit cleared.

param( [string]$archivefolder='D:\ServerBackups', [int32]$limit=30 )
#script to archive event logs from log collecting server. 
$computername=$env:COMPUTERNAME
$sysroot=$env:SystemRoot
$attribute = [io.fileattributes]::archive
$limitdate=(Get-Date).AddDays(-$limit)
$archivefolder="$archivefolder\$computername\EventLogs"
$logfile="$archivefolder\ArchiveEventLogs.Log"
$eventlogfolder="$sysroot\system32\winevt\logs"
$myname=$MyInvocation.InvocationName
# test for existence of target folders
if (( test-path $archivefolder ) -and (test-path $eventlogfolder ) ) 
    { 

    $now=get-date
    Add-Content -Path $logfile "Script $myname started $now"

    #$myeventlogs= Get-ChildItem -path "$eventlogfolder\Arch*.evtx"

    $resultofmove=move-item -passthru -path "$eventlogfolder\Arch*.evtx" -destination $archivefolder

    if ( $resultofmove ) 
        {
        $resultofmove_count=$resultofmove.count
        Add-Content -path $logfile "$resultofmove_count files have been moved to Archive" 
        $resultofmove |  Add-Content -path $logfile 
        }
    else
        {
        Add-Content -path $logfile "No files found to archive." 
        }

    # Delete files older than the $limit.
    $myfiles= Get-ChildItem -Path $archivefolder | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limitdate  -and !( (get-itemproperty -path  $_.fullname ).attributes -band $attribute ) } 

    $myfiles_count=$myfiles.count
    if ( $myfiles ) { 
        $resultofdel = $myfiles | Remove-Item -Force
        Add-Content -path $logfile "Delete $myfiles_count log files that have been backed up and are older than $limitdate" 
        $myfiles  |  Add-Content -path $logfile 
        }
    else
        {
        Add-Content -path $logfile "No event log archives found to delete. Needed to be backed up and older than $limitdate" 
        }

    $now=get-date
    Add-Content -Path $logfile "Script $myname finished $now"

    #type $logfile 

    }
else
    {
    write-host -ForegroundColor red "ERROR  $archivefolder or $eventlogfolder do not exist, debugging written to  $env:TEMP\archivecrashlog.txt"
    $myline= $MyInvocation.line
    add-content -path "$env:TEMP\archivecrashlog.txt" "$myline"
    }
   
Posted in Hints and Tips, System Administration | Comments Off on Archiving windows event logs.

Backing up SQL Express Databases

A scheduled script such as this which has hard coded the name of the sql command file, set it to run in the folder containing the backups

echo %0 starting 
date /t 
time /t 
dir 
sqlcmd -S localhost\caserver -i "%programfiles%\custom\sql_express_database_name_backup.sql"

Which calls a SQL commands file containing this which contains the hard coded name of the database and location of backup files.

BACKUP DATABASE [My_Database] TO  DISK = N'E:\Backup\My_Database' WITH NOFORMAT, INIT,  NAME = N'My_Database-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

Microsoft have a much more powerful script referenced here

Technet How to schedule and automate backups of SQL Server databases in SQL Server Express

Posted in Hints and Tips, System Administration | Comments Off on Backing up SQL Express Databases

Giving permissions in Exchange for users from a trusted domain.

After a recent consolidation we needed to give users in a seperate (but trusted) domain access to mailboxes on an exchange 2010 server.

The below code (copied from https://social.technet.microsoft.com/Forums/exchange/en-US/d2f051f0-9649-4ac0-8e82-9783a34d0eed/how-do-you-grant-full-mailbox-permissions-to-someone-in-a-different-domain-in-exchange-2010?forum=exchange2010 – by J. Duke Rogers Communicore Technologies & Triangle Forensics) does the job. I added the bit to get the Distinguished name from the mailbox (saves a lot of typing).

$mb= get-mailbox “mailbox_to_be_given_rights_on”

$dn = $mb.DistinguishedName

Add-ADPermission -Identity $dn -User ‘mydomain\mygroup’ -ExtendedRights ‘Send-as’

Add-MailboxPermission “mailbox_to_be_given_rights_on” -User “mydomain\mygroup” -AccessRights FullAccess

Posted in Powershell, VBS, VBA and other scripting., System Administration | Comments Off on Giving permissions in Exchange for users from a trusted domain.

get the total number of items in all folders of outlook mailbox store

If you are ever moving large amounts of email around it can be useful to be able to check that there is the correct number of emails in the old and new locations. This code generates a text file that can be used to compare the count of items in each folder. Just walks its way through the mailstore. includes public folders or PST files. Text file is in CSV format so it can be easily read and summarised in excel.


Sub CountAllFolders()

    Dim myfolder, mymyfolder, mydestfolder, mydestfolder1 As Folder
    Dim myisempty As Boolean
    mymsg = ""
    errorlist = ""
    
    
    
    
    Set myOlApp = CreateObject("Outlook.Application")
    Set myNameSpace = myOlApp.GetNamespace("MAPI")
    
    For x = 1 To myNameSpace.Folders.Count
        Set myfolder = myNameSpace.Folders(x)
        mymsg = mymsg + countthisfolder(myfolder)
    Next x
    
    'MsgBox mymsg
    
    
    'should be putting this somewhere cleverer
    FilePath = "c:\windows\temp\outlookfolderitemscount.csv"
    
    
     Set objFSO = CreateObject("Scripting.FileSystemObject")
     Set objFile = objFSO.OpenTextFile(FilePath, 2, True)
     objFile.Write (mymsg)
     Set objFile = Nothing
     Set objFSO = Nothing
     
     
    'Stop
    'myfolder.Display
    

End Sub

Function countthisfolder(ByVal myfolders As Folder)
    mymsg = ""
   

    mymsg = """" + myfolders.FolderPath + """," + CStr(myfolders.Items.Count)  + vbCrLf
    For i = 1 To myfolders.Folders.Count
        mymsg = mymsg + countthisfolder(myfolders.Folders(i)) + vbCrLf
        Debug.Print myfolders.Folders(i).FolderPath
        
    Next i
    countthisfolder = mymsg
    
        
End Function

Posted in Hints and Tips, Powershell, VBS, VBA and other scripting. | Tagged | Comments Off on get the total number of items in all folders of outlook mailbox store

Self Signed Certificates.

Allows you to create longer lasting self signed certificates for testing

new-selfsignedcertificate in powershell is pretty good but doesnt allow more than 12 months expiration.

selfssl7 allows up to 50 years and 2048 bit size. Its default behavior is to create and install the certificate – be careful.

http://blogs.iis.net/thomad/setting-up-ssl-made-easy

Posted in Powershell, VBS, VBA and other scripting., System Administration | Comments Off on Self Signed Certificates.

export all mailboxes exchange 2010

To do a bulk mailboxexport on exchange 2010 for all mailboxes, it mus tbe to a share and the share needs appropriate permissions.

Filter the get-mailbox to get a subset of the mailboxes.

$a=get-mailbox
foreach ($u in $a) {
  $u.alias
  $ua=$u.alias
  new-mailboxexportrequest $ua -filepath \\mailserver\exportedemail\$ua.pst
  }
Posted in Powershell, VBS, VBA and other scripting., System Administration | Comments Off on export all mailboxes exchange 2010

excel get domain from email address

=RIGHT(C2,LEN(C2)-SEARCH("@",C2))
Posted in System Administration | Comments Off on excel get domain from email address