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

02 April 2014

Lync 2010 - Revoke a User Certificate

Lync 2010 - Revoke a User Certificate


This one is more important than you may think. If you disable an AD account, and permit users to save their username/password, they will still be able to use Lync! A lot of people don't know this and it creates an interesting discussion with the security officer.

Revoke-CsClientCertificate "Username"

Source

Convert Legacy mailbox to User mailbox

If you happen to have a Legacy Mailbox on an Exchange 2010 server, you can upgrade or convert it to a User Mailbox by using the shell command:

Set-Mailbox -identity Alias -ApplyMandatoryProperties


After executing the command, the mailbox should be converted from Legacy to user in about 20 seconds.

How to find the version of your Lync Server 2010

Check this once in a while to see if you're missing Lync 2010 "CU" updates.

Get-WmiObject -query 'select * from win32_product' | where {$_.name -like "Microsoft Lync Server*"} | foreach {$_}

Or:



Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |  ?{$_.DisplayName -like “*Lync Server*”} | Sort-Object DisplayName | Select DisplayName, DisplayVersion, InstallDate | Format-Table -AutoSize

Output:

DisplayName                                         DisplayVersion InstallDate
-----------                                         -------------- -----------
Microsoft Lync Server 2010, Administrative Tools    4.0.7577.190   20130131
Microsoft Lync Server 2010, Application Host        4.0.7577.0     20130201
Microsoft Lync Server 2010, Audio Test Service      4.0.7577.0     20130201
Microsoft Lync Server 2010, Best Practices Analyzer 4.0.7577.118   20131022
Microsoft Lync Server 2010, Conferencing Server     4.0.7577.709   20141214
Microsoft Lync Server 2010, Core Components         4.0.7577.709   20141214
Microsoft Lync Server 2010, Core Management Server  4.0.7577.0     20130517
Microsoft Lync Server 2010, Front End Server        4.0.7577.707   20141214
Microsoft Lync Server 2010, Mobility Service        4.0.7577.217   20130919
Microsoft Lync Server 2010, Reach Fonts             4.0.7577.0     20130201
Microsoft Lync Server 2010, Resource Kit Tools      4.0.7577.197   20130808
Microsoft Lync Server 2010, Web Components Server   4.0.7577.231   20141214
Microsoft Lync Server 2010, Web Conferencing Server 4.0.7577.199   20130201

 
 PS C:\Lync> Get-WmiObject -query 'select * from win32_product' | where {$_.nam

 
 Name                                                Version
----                                                -------
Microsoft Lync Server 2010, Mobility Service        4.0.7577.217
Microsoft Lync Server 2010, Resource Kit Tools      4.0.7577.197
Microsoft Lync Server 2010, Web Components Server   4.0.7577.231
Microsoft Lync Server 2010, Web Conferencing Server 4.0.7577.199
Microsoft Lync Server 2010, Core Components         4.0.7577.709
Microsoft Lync Server 2010, Best Practices Analyzer 4.0.7577.118
Microsoft Lync Server 2010, Core Management Server  4.0.7577.0
Microsoft Lync Server 2010, Audio Test Service      4.0.7577.0
Microsoft Lync Server 2010, Application Host        4.0.7577.0
Microsoft Lync Server 2010, Administrative Tools    4.0.7577.190
Microsoft Lync Server 2010, Reach Fonts             4.0.7577.0
Microsoft Lync Server 2010, Front End Server        4.0.7577.707
Microsoft Lync Server 2010, Conferencing Server     4.0.7577.709

 
 PS C:\Lync> $PSVersionTable

 Name                           Value
----                           -----
CLRVersion                     2.0.50727.5485
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

CU update list:

Lync 2010
CU #Description
CU1http://support.microsoft.com/?kbid=2467763
Description of the cumulative update package for Lync 2010: January 2011
(Version: 4.0.7577.108)
CU2http://support.microsoft.com/?kbid=2496325
Description of the cumulative update package for Lync 2010: April 2011
(Version: 4.0.7577.253)
CU3http://support.microsoft.com/kb/2551268
Description of the cumulative update package for Lync 2010: May 2011
(Version: 4.0.7577.280)
CU4http://support.microsoft.com/?kbid=2571543
Description of the cumulative update package for Lync 2010: July 2011
(Version: 4.0.7577.314)
CU5http://support.microsoft.com/?kbid=2514982
Description of the cumulative update package for Lync 2010: November 2011
(Version: 4.0.7577.4051)
CU6http://support.microsoft.com/kb/2670326
Description of the cumulative update package for Lync 2010: February 2012
(Version: 4.0.7577.4072)
CU7http://support.microsoft.com/kb/2701664
Description of the cumulative update package for Lync 2010: June 2012
(Version: 4.0.7577.4103)
CU8http://support.microsoft.com/kb/2737155
Description of the cumulative update package for Lync 2010: October 2012
(Version: 4.0.7577.4356)
CU9http://support.microsoft.com/kb/2791382
Description of the cumulative update package for Lync 2010: March 2013
(Version: 4.0.7577.4378) 
CU10http://support.microsoft.com/kb/2815347
Description of the cumulative update package for Lync 2010: April 2013
(Version: 4.0.7577.4384)
CU11http://support.microsoft.com/kb/2842627
Description of the cumulative update package for Lync 2010: July 2013
(Version: 4.0.7577.4398)
CU12http://support.microsoft.com/kb/2884632
Description of the cumulative update package for Lync 2010: October 2013
(Version: 4.0.7577.4409)
CU13http://support.microsoft.com/kb/2912208
Description of the cumulative update package for Lync 2010: January 2014

(Version: 4.0.7577.4419)


Lync Server 2010
CU#Description
CU1http://support.microsoft.com/kb/2467775
Description of the cumulative update for Lync Server 2010, Core Components: January 2011
(Version: 4.0.7577.108)
CU2http://support.microsoft.com/kb/2500442
Description of the cumulative update for Lync Server 2010: April 2011
(Version: 4.0.7577.137)
CU3http://support.microsoft.com/kb/2571546
Description of the cumulative update for Lync Server 2010: July 2011
(Version: 4.0.7577.166)
CU4http://support.microsoft.com/kb/2514980
Description of the cumulative update for Lync Server 2010: November 2011
(Version: 4.0.7577.183)
CU5http://support.microsoft.com/kb/2670352
Description of the cumulative update for Lync Server 2010: February 2012
(Version: 4.0.7577.190)
CU6http://support.microsoft.com/kb/2701585
Description of the cumulative update for Lync Server 2010: June 2012
(Version: 4.0.7577.199)
CU7http://support.microsoft.com/kb/2737915
Description of the cumulative update for Lync Server 2010: October 2012
(Version: 4.0.7577.203)
CU8http://support.microsoft.com/kb/2791381
Description of the cumulative update for Lync Server 2010: March 2013 
(Version: 4.0.7577.216)
CU9http://support.microsoft.com/kb/2860700
Description of the cumulative update for Lync Server 2010: July 2013
(Version: 4.0.7577.217)
CU10http://support.microsoft.com/kb/2889610
Description of the cumulative update for Lync Server 2010: October 2013 
(Version: 4.0.7577.223)
CU11http://support.microsoft.com/kb/2909888
Description of the cumulative update for Lync Server 2010: January 2014

(Version: 4.0.7577.225)
  




Source 1
Source 2

14 March 2014

What are "Schannel" errors and how to stop logging them

With certain Microsoft products, such as Exchange and Lync you see your evelogs filling up with "Schannel" errors; event id: 36888 The following fatal alert was generated: 51. The internal error state is 1306.

The event it self doesnt give out a lwhole lot of information but here is an explanation for it from technet:

When you enable Schannel event logging on a computer that is running Microsoft Windows NT Server 4.0, Microsoft Windows 2000 Server, Microsoft Windows XP Professional, Microsoft Windows Server 2003, Microsoft Windows Server 2008, or Microsoft Windows Server 2008 R2, detailed information from Schannel events can be written to the Event Viewer logs, in particular the System event log. This article describes how to enable and configure Schannel event logging. 


The internal error state is 1203 - From a support forum: "This event is seen on windows 2008 R2 running IIS. If a user tries to access a web site using HTTP but specifies an SSL port in the URL then this event is logged. This event is expected as the client is trying to use the wrong port or the wrong protocol to access the site
The error 1203 indicates invalid ClientHello from the client. This is by design and you can ignore this warning."

If your System eventlog is filling up with "Schannel" errors, and you want to stop this behavior, you can do the following.

Enable /disable logging

Warning Serious problems might occur if you modify the registry incorrectly by using Registry Editor or by using another method. These problems might require that you reinstall your operating system. Microsoft cannot guarantee that these problems can be solved. Modify the registry at your own risk.

Note This registry key is present already in Windows 2000 and XP Professional.
  1. Start Registry Editor. To do this, click Start, click Run, type regedt32, and then click OK.
  2. Locate the following key in the registry:
    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL
  3. On the Edit menu, click Add Value, and then add the following registry value:
    Value Name: EventLogging
    Data Type: REG_DWORD
    Note After you add this property, you must give it a value. See the table in the "Logging options" section to obtain the appropriate value for the kind of events that you want to log.
  4. Exit Registry Editor.
  5. Click Start, click Shut Down, click to select Restart, and then click OK to restart the computer. (Logging does not take effect until after you restart the computer).

Logging options

The default value for Schannel event logging is 0x0000 in Windows NT Server 4.0, which means that no Schannel events are logged. In Windows 2000 Server and Windows XP Professional, this value is set to 0x0001, which means that error messages are logged. Additionally, you can log multiple events by specifying the hexadecimal value that equates to the logging options that you want. For example, to log error messages (0x0001) and warnings (0x0002), set the value to 0x0003.
Collapse this tableExpand this table:

ValueDescription
0x0000                  Do not log
0x0001                  Log error messages
0x0002                  Log warnings
0x0004                  Log informational and success events

Source


12 March 2014

How to renew Lync Edge server "webserver" certificate

Once a year it's time to do this, and probably just like me, you think how did i do this last year.
So to never forget, or to look it up each year, here goes:

1. Inside your Lync environment, click on Start -> All Programs -> Microsoft Lync Server 2010 -> Lync Server Deployment Wizard.

2. Click on Install or Update Lync Server System.

3. Under Step 3, click on Run Again.

4. Select the certificate you would like to renew and click on Request.
5. Click Next.
6. Select Prepare the request now, but send it later (offline certificate request), and click Next.

7. Select where you want the request to be saved and click Next.
8. Click Next in the Certificate Template window.
9. Specify a name you want to use for identifying this certificate, and select "Mark the certificate's private key as exportable".

10. Enter the organization and organization unit name, as well as geographical location on the next window.
11. Next window will list Subject Names what will be included in the certificate, click Next.
12. If you are requesting a certificate for an Edge server,you will be able to select your SIP domain, click Next.
13. In this window, you will have to enter all of the Subject Alternate Names used in your Lync environment. For example lync.domain.com, edge.domain.com, dialin.domain.com, meet. domain.com etc.

14. Verify your information and click next.
15. Click Next to generate the request then click Finish.
16. Now that you have your CSR request file, send it over to your SSL provider or your local PKI environment. When you get your new certificate files, right click on each one and select Install Certificate.
17. Go back to your Lync Certificate wizard and click on Assign. Look for the friendly name you created in step 9, and select it. Click next until your certificate is assigned.
18. Restart Lync services and they should start right up. Check for any error logs in the Event Viewer.

If you plan on using the same certificate on your other Lync servers, you will have to use the Microsoft Management Console Certificate Snap-in to export and import the certificate to other servers. Now repeat from step 16.

Source 1
Source 2