31 August 2014

Database Seeding cmdlets

Get Database Copy StatusGet-MailboxDatabaseCopyStatus -Identity ‘EX10mbx01′ | ft name,Status,ContentIndexState,ReplayQueueLength,CopyQueueLength -autosize

Status for all database copies on the Mailbox server EX10CHM10 by status
Get-MailboxDatabaseCopyStatus -Server EX10CHM01 | Sort-Object -Property Status| ft mailboxserver,DatabaseName, status,Copyqueuelength,Replayqueuelength, ContentIndexState, ActiveCopy,ErrorMessage -AutoSize

UPDATE Seed a copy of a database named EX10mbx08 on EX10CHM01 using EX10CHM04 as the source Mailbox server for the seed
Update-MailboxDatabaseCopy -Identity EX10mbx01\EX10CHM02 -SourceServer EX10CHM01

UPDATE Seed a copy of a database named EX10mbx08 on EX10CHM01 using EX10CHM04 as the source Mailbox server for the seed (remove existing files)
Update-MailboxDatabaseCopy -Identity EX10mbx48\EX10CHM07 -sourceserver EX10CHM09 -DeleteExistingFiles

Update the Database using a source server and delete existing files
Update-MailboxDatabaseCopy -Identity EX10mbx02\EX10CHM10 -DeleteExistingFiles

Update ONLY the Database using a source server and delete existing files
Update-MailboxDatabaseCopy -Identity EX10mbx06\EX10CHM12 -SourceServer EX10CHM11 -DatabaseOnly -DeleteExistingFiles

Update Catalog Only
Update-MailboxDatabaseCopy -identity EX10mbx01\EX10CHM11 –CatalogOnly

Update Database Only without seeding the content index catalog
Update-MailboxDatabaseCopy -identity EX10mbx07\EX10CHM12 –Databaseonly

UPDATE the Catalog on EX10mbx08 on EX10CHM01 using EX10CHM04 as the source Mailbox server for the seed
Update-MailboxDatabaseCopy -Identity EX10mbx46\EX10CHM04 -SourceServer EX10CHM05 -catalogonly
Update-MailboxDatabaseCopy -Identity EX10mbx22\EX10CHM05 -DeleteExistingFiles

Resume all Copies in FailedandSuspended
Get-MailboxDatabase | Get-MailboxDatabaseCopyStatus | where {$_.Status -eq “FailedandSuspended”}| Resume-MailboxDatabaseCopy

Resume all Copies in Failed state on Server
Get-MailboxDatabase -server EX10CHM03| Get-MailboxDatabaseCopyStatus | where {$_.Status -eq “Failed”}| Resume-MailboxDatabaseCopy

Resume Database Copy for all Databases located on Server
Get-MailboxDatabaseCopyStatus -Server EX10CHM07 | Resume-Mailboxdatabasecopy
Resume-MailboxDatabaseCopy -Identity EX10mbx01\EX10CHM09

Suspend Mailbox Database Copy
Suspend-MailboxDatabaseCopy -Identity EX10mbx01\EX10CHM11 -SuspendComment “Maintenance ” -Confirm:$False

Suspend all Copies in Failed state on Server
Get-MailboxDatabase -server EX10CHM10| Get-MailboxDatabaseCopyStatus | where {$_.Status -eq “Failed”}| Suspend-MailboxDatabaseCopy
Get-MailboxDatabaseCopyStatus -Server EX10CHM01 | Suspend-MailboxDatabaseCopy

Add Mailbox Database Copy
Add-MailboxDatabaseCopy -Identity ‘EX10mbx01′ -MailboxServer ‘EX10CHM09′

Add Mailbox Database Copy (SEEDING POSTPONED)
Add-MailboxDatabaseCopy -Identity EX10mbx01 -MailboxServer EX10CHM11 -SeedingPostponed
MOVE ACTIVE DATABASE


Set Active Mailbox Database Copy
Move-ActiveMailboxDatabase -Identity ‘EX10mbx12′ -ActivateOnServer ‘EX10CHM04′ -MountDialOverride ‘None’

Set Active Mailbox Database Copy with failed Catalog
Move-ActiveMailboxDatabase -Identity ‘EX10mbx01′ -ActivateOnServer ‘EX10CHM01′ -MountDialOverride ‘None’ -SkipClientExperienceChecks

Remove Mailbox Database Copy
Remove-MailboxDatabaseCopy -Identity EX10MBX03\EX10CHM11 -Confirm:$False
Context Index


Disable Indexing on Mailbox Database
Set-MailboxDatabase “EX10MBX07″ -IndexEnabled $false

Enable Indexing on Mailbox Database
Set-MailboxDatabase “Mailbox Database EX10MBX03″ -IndexEnabled $true

Finding the passive Databases with Failed Index (can’t update the index on the active DB)
Get-MailboxServer | Get-MailboxDatabaseCopyStatus | ? {$_.Status -ne “Mounted” –and $_.ContentIndexState -eq “Failed”} | ft -autosize

Fix the Passive databases with Failed Index
Get-MailboxServer | Get-MailboxDatabaseCopyStatus | ? {$_.Status -ne “Mounted” –and $_.ContentIndexState -eq “Failed”} | Update-MailboxDatabaseCopy –CatalogOnly

Fix all Passive databases with Failed Index per Database
Get-MailboxDatabaseCopyStatus -identity EX10mbx01\* | ? {$_.Status -ne “Mounted” -and $_.ContentIndexState -eq “Failed”} | Update-MailboxDatabaseCopy -CatalogOnly

30 August 2014

Windows server 2012 task manager missing disk and network performance counters

I keep reading on some fora that this setting should not be used in a production envoironment, so try at your own risk or test first. 

Enabling Task manager Disk Performance Counters
 

  1. Ensure Task Manager is closed.
     
  2. Launch the Command Prompt using the "Run as Administrator" option.
     
  3. Enter the following at the Command Prompt:
     
    diskperf -Y
     
  4.  Hit Enter.
     
  5. Close the Command Prompt.
     
  6. Re-open the Task Manager

25 August 2014

Resolving DirectAccess Connectivity Issues

The NRPT

Direct Access utilizes a feature called the Name Resolution Policy Table (NRPT). This basically controls the way DirectAccess handles name resolution for specific Domains. Entries in the NRPT control where client machines look for name resolution on specific domains and allow finer control of what happens when client machines are utilizing DirectAccess for connectivity. For instance, you can utilize the NRPT to force client machines to look to external DNS servers for resolution on some hostnames or domain zones, while looking to internal DNS for everything else and vice versa. There are really only two ways to modify the NRPT, through the Registry (I don’t recommend modifying the NRPT through the registry), and through group Policy using the Name Resolution Policy node. Technet has some information on how to handle NRPT here: NRPT

The Problem with DirectAccess Failures

Usually when DirectAccess stops communicating, it stops working because the NRPT isn’t configured properly. If this happens, you may run into a situation where some systems are unable to ping domain controllers or other systems by using NetBIOS names or through FQDNs. This can be a huge problem, because if DirectAccess fails, systems will typically no longer be able to communicate with the Domain to retrieve corrected NRPT information, since this information is deployed via GPO.

Fixing the Communication Issue

If something causes your DirectAccess configuration on a client machine to corrupt or if Direct Access isn’t properly configured, it may be necessary to reset the NRPT on the client machine to fix the problem. The only way to modify the NRPT on a client machine is through the registry. If you’re experienced enough with DirectAccess, you may be able to resolve the issue directly in the registry. However, it is usually easier to just remove the existing NRPT entries on the client machine entirely. This has to be done in the registry at the following location: HKLM\Software\Policies\Microsoft\Windows NT\DNSClient\DNSPolicyConfig (Pictured below)

NRPTreg

Note the two entries there. Both are composed of DA-{GUID}. DA stands for DirectAccess. Remove any entries that have that DA- prefix and reboot. Once this is done, the system will begin communicating without DirectAccess and will have the ability to connect to the domain to retrieve new NRPT information if it is available.

After deleting the entries, you can either reboot or restart the DNS client service and do a gpupdate /force.

Source

09 July 2014

Set Active Directory user property's with Powershell

Need to edit a user property here's how:


To set the Dail-in property to deny access, you look for the corresponding value, in this case:
"msNPAllowDailin" which is set to TRUE.

In Powershell you type:set-ADUser username -Replace @{msnpallowdialin=$false}

Now when you look at the same value in the attribute editor it displays FALSE.


I haven't tried it but i guess everything that has a value can be changed or edited by the same command.
If you know some others, or disagree let me know.




Get system up time script and alternative ways

Save as a ps1 script, and run.

$computer = "computername"

$lastboottime = (Get-WmiObject -Class Win32_OperatingSystem -computername $computer).LastBootUpTime

$sysuptime = (Get-Date) – [System.Management.ManagementDateTimeconverter]::ToDateTime($lastboottime) 
  
Write-Host "$computer has been up for: " $sysuptime.days "days" $sysuptime.hours "hours" $sysuptime.minutes "minutes" $sysuptime.seconds "seconds" 

Outputs like:

PS D:\_DATA\Scripts> .\Uptime.ps1
computername has been up for:  71 days 4 hours 26 minutes 50 seconds

Alternatives:

1. Go to "Start" -> "Run".

2.  Write "CMD" and press on "Enter" key.

3. Write the command systeminfo | find "up time" and press on "Enter" key.

1. Go to "Start" -> "Run".

2.  Write "CMD" and press on "Enter" key.

3.  Write the command "net statistics server" and press on "Enter" key.


4.  The line that start with "Statistics since …" provides the time that the server was up from.

  •   The command "net stats srv" can be use instead.
Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher

Source

Alternate source

05 June 2014

Powershell 407 proxy authentication required

When trying to run Get-Software.ps1, you may receive an error message:

Do you want to Download PSExec ?
[Y] Yes  [N] No  [?] Help (default is "Y"): y
Exception calling "DownloadFile" with "2" argument(s): "The remote server retur
ned an error: (407) Proxy Authentication Required."
At D:\_DATA\Downloads\Hydrationkit\Build\Modules\Software.psm1:83 char:33
+                                 $WebClient.DownloadFile($Source, $Destination
)
+                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

Run these commands to send your current credentials

$proxy = New-Object System.Net.WebClient

$Proxy.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

After this the script runs fine:

Do you want to Download PSExec ?
[Y] Yes  [N] No  [?] Help (default is "Y"):

Do you want to Download SetupCA ?
[Y] Yes  [N] No  [?] Help (default is "Y"):

Do you want to Download Windows Assessment and Deployment Kit (ADK) for
Windows® 8 ?
[Y] Yes  [N] No  [?] Help (default is "Y"):


21 May 2014

New-exchangecertificate for Exchange EDGE 2010

Do this after office hours or in a service window, because the risk exists that mail flow may come to a halt because the edgesync subscription certificate don't match anymore. I found out the hard way.

Generate a new certificate request:

$data = New-ExchangeCertificate -GenerateRequest -SubjectName "cn=mx03.domain.com" -domainname mx03.domain.com, sr-XXXXX.domain.lan, sr-XXXXX -friendlyname mx03.domain.com -PrivateKeyExportable $true
Set-Content -Path "c:\Temp\mailcert.req" -Value $Data

Import the request into the PKI website http://servername/certsrv

Request a new Certificate

Submit a certificate request by using a base-64-encoded CMC or PKCS #10 file, or submit a renewal request by using a base-64-encoded PKCS #7 file

Enter the request code and press Submit

On the PKI environment Issue the requested certificate and export the new certificate.

On the EDGE server copy the certificate to a folder.

To import the certificate in Powershell:

Import-ExchangeCertificate -FileData ([Byte[]]$(Get-Content -Path c:\certificates\ExportedCert.cer -Encoding byte -ReadCount 0))

Check the thumbprint to use in the next commandlet:

Get-exchangecertificate | fl

Use the thumbprint in the following line:

Enable-ExchangeCertificate -Thumbprint 5113ae0233a72XXXXXXXXXXXXXXXX8675333d010e -Services SMTP

Then recreate the EdgeSync Subcription

new-edgesyncsubcription -filepath "C:\temp\filename.xml"

Export the XML file to your CAS server and create a new Edgesync subscription.

The problem right now is we do not refresh the certificate used by ADAM when issue a new subscription, so if you have created a new certificate, we keep presenting the old one. Ok, so here's what you need to do to get ADAM to present the new one:
 
1. On the Hub, Remove the Subscription
2. On the Edge, Remove the cert used by ADAM to establish secure
connections. You can do this by following the following steps:
  • a. Open up an empty mmc console (Run -> mmc)
  • b. Select File -> Add / Remove Snap-in
  • c. Hit Add
  • d. Select "Certificates" from the List of Snap-Ins available, and
  • hit Add.
  • e. Select "Service Account" on the "Certificates Snap-In" page,
  • click next.
  • f. Select "Local Computer" on the "Select Computer" page, click
  • next.
  • g. Select "Microsoft Exchange ADAM" from the list of services,
  • click Finish.
  • h. Close the "Add Snap-in" dialog.
  • i. Navigate to "Certifcates – Service" ->
  • "ADAM_MSExchange\Personal" -> Certificates
  • j. You should see a single certificate here. Remove it.
3. On the Edge, Unsubscribe, then create a new subscription file
(you should see a new certificate show up at this point on the ADAM cert container from the step above) by calling new-edgesubscription
 
New-EdgeSubscription -FileName "Path to file".xml
 
4. Re-start the "Microsoft Exchange ADAM" service.
5.Export the file to the Hub server.
6.On the Hub server import the new subscription.
7.Create a new Edge subscription in the EMC

Then you have to wait a few minutes.

To check if synchronization works run;

start-edgesynchronization
test-edgesynchronization




14 May 2014

Sync Folders and files with Powershell and send notification email

I needed a way to sync some files and folders to another disc, as Allwaysync only permits less than 40.000 items per sync.
I came across a nice script from here.

But it did not exactly do what i needed it to do so adjustments were made.
I didnt need it to check the destination against the source, so got rid of that,
and made a way for it to email me the results as it had
finished comparing and syncing.

The script looks like this now:

Param($Source,$Destination)
function Get-FileMD5 {
    Param([string]$file)
    $mode = [System.IO.FileMode]("open")
    $access = [System.IO.FileAccess]("Read")
    $md5 = New-Object System.Security.Cryptography.MD5CryptoServiceProvider
    $fs = New-Object System.IO.FileStream($file,$mode,$access)
    $Hash = $md5.ComputeHash($fs)
    $fs.Close()
    [string]$Hash = $Hash
    Return $Hash
}
# Source from http://bsonposh.com/archives/231

$logfile = "C:\temp\foldersync.log"

function Copy-LatestFile{
     Param($File1,$File2,[switch]$whatif)
     $File1Date = get-Item $File1 | foreach-Object{$_.LastWriteTimeUTC}
     $File2Date = get-Item $File2 | foreach-Object{$_.LastWriteTimeUTC}
     if($File1Date -gt $File2Date)
     {
         write-output "$File1 is Newer… Copying…" | out-file $logfile -Append
         if($whatif){Copy-Item -path $File1 -dest $File2 -force -whatif}
         else{Copy-Item -path $File1 -dest $File2 -force}
     }
     else
     {
         write-output "$File2 is Newer… Copying…" | out-file $logfile -Append
         if($whatif){Copy-Item -path $File2 -dest $File1 -force -whatif}
         else{Copy-Item -path $File2 -dest $File1 -force}
     }
     write-output | out-file $logfile
}

if(!(test-Path $Destination))
{
     New-Item $Destination -type Directory -force | out-Null
}

# Getting Files/Folders from Source and Destination
$SrcEntries = Get-ChildItem $Source -Recurse -Force
$DesEntries = Get-ChildItem $Destination -Recurse -Force

# Parsing the folders and Files from Collections
$Srcfolders = $SrcEntries | Where-Object{$_.PSIsContainer}
$SrcFiles = $SrcEntries | Where-Object{!$_.PSIsContainer}
$Desfolders = $DesEntries | Where-Object{$_.PSIsContainer}
$DesFiles = $DesEntries | Where-Object{!$_.PSIsContainer}

# Checking for Folders that are in Source, but not in Destination
foreach($folder in $Srcfolders)
{
     $SrcFolderPath = $source -replace "\\","\\" -replace "\:","\:"
     $DesFolder = $folder.Fullname -replace $SrcFolderPath,$Destination
     if($DesFolder -ne ""){
         if(!(test-path $DesFolder))
         {
             write-output "Folder $DesFolder Missing. Creating it!" | out-file $logfile -Append
             new-Item $DesFolder -type Directory | out-Null
         }
     }
}

# Checking for Files that are in the Source, but not in Destination
foreach($entry in $SrcFiles)
{
     $SrcFullname = $entry.fullname
     $SrcName = $entry.Name
     $SrcFilePath = $Source -replace "\\","\\" -replace "\:","\:"
     $DesFile = $SrcFullname -replace $SrcFilePath,$Destination
     if(test-Path $Desfile)
     {
         $SrcMD5 = Get-FileMD5 $SrcFullname
         $DesMD5 = Get-FileMD5 $DesFile
         If($srcMD5 -ne $desMD5)
         {
             write-output "The Files MD5′s are Different… Checking Write Dates" | out-file $logfile -Append
             write-output $SrcMD5 | out-file $logfile
             write-output $DesMD5 | out-file $logfile
             Copy-LatestFile $SrcFullname $DesFile
         }
     }
     else
     {
         write-output "$Desfile Missing… Copying from $SrcFullname" | out-file $logfile -Append
         copy-Item -path $SrcFullName -dest $DesFile -force
     }
}

$smtpto = "user@domain.com"
$smtpfrom = "FolderSync@domain.com"
$messagesubject = "FolderSync results $finishtime"
$smtpServer = "smtp.domain.com"


out-file $Logfile -Append

$finishTime = get-date -format "dd-MM-yy HH-mm"
"Backup script finished at $finishTime" | out-file $logFile -Append -Force

$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.IsBodyHTML = $false
$finished = get-content $LogFile
$message.Body = ( $Finished | out-string )
$message.Body = $Finished
write-host 'Sending email'
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)
Write-Host "Email sent"

remove-item $Logfile


After this you can schedule it in task manager:

powershell -command "& 'E:\path to script\scriptname.ps1 X:\source Y:\destination' "

Sending email with powershell fails, 5.7.1 Client not authenticated

The error powershell throws at you:

Exception calling “Send” with “1″ argument(s): “The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated”

When using the following:
#Send email message
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)

Needs another line and becomes this:

#Send email message
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.UseDefaultCredentials = $true

Email delivers correctly.

17 April 2014

Install Exchange 2010 Prerequisites on Windows 7 with Powershell (CMD)

Scripting your IIS and .NET 3.5 prerequisites for Exchange 2010 on Windows 7:

IIS:

dism /online /enable-feature /featurename:IIS-WebServerRole  /featurename:IIS-WebServerManagementTools /featurename:IIS-IIS6ManagementCompatibility /featurename:IIS-Metabase /featurename:IIS-LegacySnapIn

.NET 3.5:
Write-Host "Installing .Net Framework 3.5, do not close this prompt..." 
                    DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:$LocalSource | Out-Null  
                    $Result = Dism /online /Get-featureinfo /featurename:NetFx3 
                    If($Result -contains "State : Enabled") 
                    { 
                        Write-Host "Install .Net Framework 3.5 successfully." 
                    } 
                    Else 
                    { 
                        Write-Host "Failed to install Install .Net Framework 3.5,please make sure the local source is correct." 
                    }
In case the above doesn't work, you can try:
DISM /Online /Enable-Feature /FeatureName:NetFx3

Source