PowerShell - Listen TCP Port

PowerShell Script to open TCP port and listen for connections

Use cases

This script can be used to test firewall rules for Windows Servers located in different subnets, DMZ etc.


-IP [IPv4 Address]
-PORT [TCP Port number]
-ListenTimeOut [Seconds]
-KeepAlive [Seconds]

Usage examples

Example below opens 443 TCP port on loopback interface and starts listening it for 1 minute. Once client is connected the session will be kept for 5 second before drop. 
.\TCPListen.ps1 -IP -PORT 443 -ListenTimeOut 60 -KeepAlive 5
Another example with output. 
.\TCPListen.ps1 -IP -PORT 443 -ListenTimeOut 20 -KeepAlive 2
07/24/2017 20:21:25 - will listen 20 seconds on port 443 with 2 seconds keepalive, ctrl+c to cancel

Status                        Date                          Address                         Port 
------                        ----                          -------                         ---- 
Connected                     7/24/2017 8:21:33 PM                     51068 
Disconnected                  7/24/2017 8:21:35 PM                     51068 
Connected                     7/24/2017 8:21:38 PM                     51073 
Disconnected                  7/24/2017 8:21:40 PM                     51073 

07/24/2017 20:21:45 - Listen stopped
This example listens for connections on 443 port for 20 seconds. It uses local IP address and keeps client connection for 2 seconds. Output shows Status event (Connected or Disconnected), Date, Client IP address and client port. Also it shows when script was started and ended.

Script Syntax





if (Test-NetConnection -ComputerName $IP -Port $PORT -InformationLevel Quiet) {Write-Host "Socket $IP`:$PORT is busy, please try another IP/PORT"; Exit}
$ListenTimeOutt = New-TimeSpan -Seconds $ListenTimeOut; $LT = $ListenTimeOutt.Seconds
$TIME = [diagnostics.stopwatch]::StartNew()
$EP = new-object System.Net.IPEndPoint ([system.net.IPAddress]::Parse($IP), $PORT)    
$LSTN = new-object System.Net.Sockets.TcpListener $EP
$LSTN.server.ReceiveTimeout = 300

$start = get-date
$start - $IP will listen $LT seconds on port $PORT with $KeepAlive seconds keepalive, ctrl+c to cancel
    While ($TIME.elapsed -lt $ListenTimeOutt)
    if (!$LSTN.Pending()) {Start-Sleep -Seconds 1;continue;}
$CONNECT = $LSTN.AcceptTcpClient()
$CONNECT.client.RemoteEndPoint | Add-Member -NotePropertyName Date -NotePropertyValue (get-date) -PassThru | Add-Member -NotePropertyName Status -NotePropertyValue Connected -PassThru | select Status,Date,Address,Port
Start-Sleep -Seconds $KeepAlive;
$CONNECT.client.RemoteEndPoint | Add-Member -NotePropertyName Date -NotePropertyValue (get-date) -PassThru -Force | Add-Member -NotePropertyName Status -NotePropertyValue Disconnected -PassThru -Force | select Status,Date,Address,Port

catch {Write-Error $_}
finally {$LSTN.stop(); $end = get-date; Write-host "`n$end - Listen stopped"} 

Azure AD Connect - installation error

Error: Unable to install the Synchronization Service. Please see the event log for additional details.

Application Log:
EnableADSyncBootstrapLocalDBInstance: Error while attempting to enable local db instance. Details: Microsoft.Azure.ActiveDirectory.Client.Framework.ProcessExecutionFailedException: Exception: Execution failed with errorCode: 1.

Details: Sqlcmd: Error: Microsoft SQL Server Native Client 11.0 : Encryption not supported on the client..

Sqlcmd: Error: Microsoft SQL Server Native Client 11.0 : SSL Provider: The client and server cannot communicate, because they do not possess a common algorithm.

Current AD Connect version (1.1.553.0) is shipped with Microsoft SQL Server 2012 Native Client version 11.0.2100.60. By default AD connect works over TLS 1.0. In environments where TLS 1.0 is disabled Synchonization Service can't be installed because Native client doesn't support TLS 1.2.

Install never version of SQL Native Client, for example 11.3.6020.0. Obviously all required changes to allowed ciphers, manual RC2/4 hardening (in case of .Net 4.6), SchUseStrongCrypto etc. need to be reviewed and applied as well (many articles about it).

CloudStack - XenServer - single server deployment

This blog post shows how to deploy CloudStack on a single XenServer. Obviously non production example, simply a proof of concept case.

Subnet -
Gateway -
DNS Server -
XEN1 ( - XenServer 6.5 with all patches installed.
CLOUD1 ( - Ubuntu 14.04.2 - "apt update | apt upgrade". VM running on XEN1.


It will be CloudStack 4.9 deployment on CLOUD1 virtual machine, which is running on XEN1. CLOUD1 will act as CloudStack management server, MySQL server and NFS server.

# Make sure that FQDN is set correctly.
CLOUD1# hostname --fqdn

# Install NTP
CLOUD1# apt-get install openntpd

# Add repository
CLOUD1# nano /etc/apt/sources.list.d/cloudstack.list
deb http://cloudstack.apt-get.eu/ubuntu precise 4.9

# Add public key
CLOUD1# wget -O - http://cloudstack.apt-get.eu/release.asc|apt-key add -
CLOUD1# apt-get update

# Install CloudStack Management package
CLOUD1# apt-get install cloudstack-management

# Install vhd-util
CLOUD1# wget http://download.cloud.com.s3.amazonaws.com/tools/vhd-util
# Copy vhd-util to the scripts folder
CLOUD1# cp vhd-util /usr/share/cloudstack-common/scripts/vm/hypervisor/xenserver

# Install Database server
CLOUD1# apt-get install mysql-server
# Amend MySQL configuration file under [mysqld] section.
CLOUD1# nano /etc/mysql/my.cnf
binlog-format = 'ROW'
# Restart MySQL daemon
CLOUD1# service mysqld restart

# Setup CloudStack Database, where password1 is for cloud user and password2 is MySQL root password.
CLOUD1# cloudstack-setup-databases cloud:password1@localhost --deploy-as=root:password2 -i

# Setup Management Server
CLOUD1# cloudstack-setup-management

# Install and configure NFS
CLOUD1# apt-get install nfs-kernel-server
CLOUD1# mkdir -p /export/primary
CLOUD1# mkdir -p /export/secondary
CLOUD1# nano /etc/exports
/export *(rw,async,no_root_squash,no_subtree_check)
CLOUD1# exportfs -a

# Prepare system template
CLOUD1# /usr/share/cloudstack-common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://cloudstack.apt-get.eu/systemvm/4.6/systemvm64template-4.6.0-xen.vhd.bz2 -h xenserver -F

# Prepare XenServer
XEN1# xe-switch-network-backend bridge

XEN1 is ready to be added to the CloudStack.

Login to http://cloud1:8080/client and setup the first zone.

Preparation for CCNP Cloud Certification

Today (19/06/2017) I passed Cisco 300-465 exam so I want to share how to prepare to it without taking any external training. Only self-study, hope someone will find it useful. In this post I will provide the list of preparation materials and resources, which will help to pass Designing the Cisco Cloud exam (CLDDES).

First of all you need to check exam topics on Cisco Learning Network - CLDDES Exam Topics I recommend also to look at authorized training. Partners provide official training, just find any through the partner locator and copy study topics, it will be useful to have.

Practice part. Register on dCloud portal using your Cisco ID. Complete all UCS, IAC, PSC labs. Very important to complete them if you don't work with these products. Additionally it is recommended to download and install trial versions of UCS Director, UCS Manager, IAC and Intercloud Fabric software in Lab environment.

Below are the topics that must to be studied before taking an exam (most of them from Study Materials with my amendments). In conjunction with labs above they will provide the best experience and understanding the material. I do not provide the links because it seems that Cisco doesn't treat links properly (many broken links, removed, non available links, to be honest a sad story). So just search or google search the information on Cisco site by the following topics:
1. Get Started with Cisco UCS Director.
2. Introducing Cisco Intelligent Automation for Cloud.
3. Cisco Intelligent Automation for Cloud.
4. Cisco Intelligent Automation for Cloud Data Sheet.
5. Cisco Intelligent Automation for Cloud 4.3.2 Installation Guide.
6. Cisco UCS Director Fundamentals Guide, Release 6.0
7. Cisco UCS Director Administration Guide, Release 6.0.
8. Cisco Prime Service Catalog.
9. Cisco Prime Service Catalog datasheet.
10. Cisco Prime Service Catalog Plan and Build Service datasheet.
11. Cisco Prime Network Services Controller.
12. IT as a Service with Cisco Prime Service Catalog and UCS Director.
13. Cisco Cloud Accelerators.
14. Enterprise Platform as a Service.
15. Understanding Cisco Cloud Fundamentals.
16. FlexPod Overview.
17. FlexPod at a glance - Simplified Multivendor Support for Your FlexPod.
18. FlexPod Infrastructure Automation.
19. FlexPod Datacenter with VMware vSphere 6.5 Design Guide.
20. FlexPod Data Center with Cisco Nexus 7000 and NetApp MetroCluster for Multisite Deployment.
21. FlexPod Data Center with Microsoft Fast Track Private Cloud 3 Design Guide.
22. FlexPod Data Center with Microsoft Private Cloud v3 Design Guide.
23. Vblock Systems.
24. Cisco Solutions for VSPEX.
25. Cisco Solutions for EMC VSPEX.
26. Cisco UCS Director VSPEX Implementation Guide.
27. Cisco Intercloud Fabric Security Features Technical Overview.
28. Cisco Intercloud Fabric Architectural Overview.
29. Cisco Intercloud Fabric Provider Platform Architecture.
30. Cisco VMDC Cloud Security 1.0 Design Guide.
31. Cisco Cloud Security Solutions.
32. Cisco Secure Network Container Multi-Tenant Cloud Computing.
33. Cisco Cloud Security Architecture: Un-Cloaking Invisible Threats.

Additionally you should be able to understand the following (it includes some tips after passing the exam):
1. Difference and case usage of VXLAN and OTV.
2. VMware VM migration procedure and requirements (hot, cold, vMotion etc).
3. Deep Packed Inspection (DPI) principles and usage.
4. Context aware infrastructure.
5. Cisco Virtual WAAS (vWAAS) is a virtual appliance
6. Pay attention on on Stack Designer.
7. WMware datastores, VM disk formats (thin, thick etc).
8. File-level and block lever storage, usage and difference.
9. Application Centric Infrastructure 
10. Pay attention on multi-site HA/DRS solutions, license requirements etc.
11. Integration part of PSC with UCS director.

Overall impression after passing an exam is a bit frustrated as documentation and study material is not up to date and spread across so it was wasted much time just trying to find information.

Installing OpenVAS on Ubuntu 16.04

sudo apt update && sudo apt upgrade
sudo apt install software-properties-common
sudo add-apt-repository ppa:mrazavi/openvas
sudo apt update
sudo apt install openvas
sudo apt install sqlite3
sudo openvas-nvt-sync
sudo openvas-scapdata-sync
sudo openvas-certdata-sync
sudo service openvas-scanner restart
sudo service openvas-manager restart
sudo openvasmd --rebuild --progress
sudo openvasmd --user=admin --new-password=PASSWORD

PowerShell - Send email on behalf

$EmailFrom = "User One <user.one@example.com>"
$EmailTo = "Vyacheslav Fedenko <vyacheslav.fedenko@example.com>"
$Subject = "Email Subject"
$body = "Email Body"
$Smtp = new-object Net.Mail.SmtpClient($SmtpServer)
$MailMessage = new-object Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $body)
$MailMessage.Sender = "User.Two@example.com"

Get Calendar Permissions report - Exchange 2010/2013/2016 and Exchange Online

This PowerShell script gets Calendar Permissions report within your Exchange organization. It also can get a report from Office 365.
Usage examples:
.\Get-CalendarPermissionsReport.ps1 -Version 2010
Exchange 2010 Calendar Permissions report.

.\Get-CalendarPermissionsReport.ps1 -Version 2010 -File FileName.csv
The same as above but the results will be exported to FileName.csv file. 

.\Get-CalendarPermissionsReport.ps1 -Version 2013-2016 -File FileName.csv
Gets calendar permissions report for Exchange 2013 or 2016 and exports the results to FileName.csv file. 

.\Get-CalendarPermissionsReport.ps1 -Version O365 -File FileName.csv
Gets calendar permissions report for Exchange Online and exports the results to FileName.csv file. It will ask an Office 365 admin credentials.

.\Get-CalendarPermissionsReport.ps1 -Version O365
Connects to Exchange Online and prints calendar permissions to console. 

The script can be downloaded from TechNet Gallery.

Ubuntu 16.04 - Failed to start LXD

root@hostname:~# systemctl status lxd-containers.service
● lxd-containers.service - LXD - container startup/shutdown
   Loaded: loaded (/lib/systemd/system/lxd-containers.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Tue 2017-03-21 13:33:45 EDT; 3min 15s ago
     Docs: man:lxd(1)
 Main PID: 852 (code=exited, status=1/FAILURE)

Mar 21 13:33:45 hostname systemd[1]: Starting LXD - container startup/shutdown...
Mar 21 13:33:45 hostname lxd[852]: error: open /var/lib/lxd/containers: no such file or directory
Mar 21 13:33:45 hostname systemd[1]: lxd-containers.service: Main process exited, code=exited, status=1/FAILURE
Mar 21 13:33:45 hostname systemd[1]: Failed to start LXD - container startup/shutdown.
Mar 21 13:33:45 hostname systemd[1]: lxd-containers.service: Unit entered failed state.
Mar 21 13:33:45 hostname systemd[1]: lxd-containers.service: Failed with result 'exit-code'.

The fix:
root@hostname:~# sudo su
root@hostname:~# service lxd restart
root@hostname:~# reboot

root@hostname:~# systemctl status lxd-containers.service
● lxd-containers.service - LXD - container startup/shutdown
   Loaded: loaded (/lib/systemd/system/lxd-containers.service; enabled; vendor preset: enabled)
   Active: active (exited) since Tue 2017-03-21 13:37:14 EDT; 2min 4s ago
     Docs: man:lxd(1)
 Main PID: 857 (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/lxd-containers.service

Mar 21 13:37:13 hostname systemd[1]: Starting LXD - container startup/shutdown...
Mar 21 13:37:14 hostname systemd[1]: Started LXD - container startup/shutdown.

Exchange - Connect a disabled mailbox

Easy way to restore a mailbox if you accidentally removed it. Simply reconnect it back using steps described here.

But sometime a removed mailbox doesn't show up as a disconnected one. In this case you need to synchronize the mailbox state with its AD account using Update-StoreMailboxState cmdlet.

First of all find a MailboxGuid and Database name of removed mailbox:
Get-MailboxDatabase | Get-MailboxStatistics | Where { $_.DisplayName -eq "Display Name" } | ft DisplayName,Database,MailboxGuid 

Then update the mailbox state:
Update-StoreMailboxState -Database DBNAME -Identity MailboxGUID

Then the mailbox will show up in disconnected mailboxes as well as DisconnectReason attribute will be updated. The mailbox will be ready to reconnect.

Installing Hyper-V on ESXi

Validation Results: The validation process found problems on the server to which you want to install features. 
The selected features are not compatible with the current configuration of your selected 
server. Click OK to select different features.

Shutdown the VM.
Add vhv.allow = "TRUE" to vmx file of VM. 
Amend guest operating system string so it looks like - guestOS = "winhyperv"
Upgrade Virtual Hardware. 
Enable Intel VT-x/AMD-V for intrusion set virtualization in VM CPU Options.

Notes: Works with ESXi 5.1, ESXi can be installed as well, Hyper-V can be installed and run even with 1 vCPU. 

SMB v1 GPO adm



KEYNAME "SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters"

KEYNAME "SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters"


SMB_Version="SMB Version"
SMB1="SMB v1"
SMB1Help="Enable/Disable SMB version 1 by changing the value of 'SMB1' REG_DWORD in SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters."
SMB2="SMB v2"
SMB2Help="Enable/Disable SMB version 2 by changing the value of 'SMB2' REG_DWORD in SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters. Caution - SMB v3 works on the same stack as v2 (don't touch it)."

adm file can be easilly converted to admx via ADMX Migrator

Exchange setup error

"A reboot from a previous installation is pending. Please restart the system and then rerun Setup." 

If you are getting the error again after reboot (do it twice), clean up the values in REG_MULTI_SZ below: 

HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations 

Sure thing backup registry first.

RDS connection issue

"The task you are trying to do can't be completed because Remote Desktop Services is currently busy".

In this case you need to reset your session. 

Connect to remote server via psexec tool.
psexec \\Server1 cmd

Optionally you can connect with different credentials by specifying -u key. 

Find out your session ID by running:
query session

Reset your session
reset session ID

Now you should be able to logon with no issue.

Update 25/05/2017: No need to use psexec as query/reset commands have /server parameter. :/ 

Exchange 2013 - IMAP Health

Check components by running:
Get-ServerComponentState -Identity CASServer1

If ImapProxy component has inactive state run the command below:
Set-ServerComponentState -Identity CASServer1 -State Active -Requester HealthAPI -Component ImapProxy

For more deep troubleshooting you can refer to the following KB - Troubleshooting IMAP Health Set.

#Connection Closed Gracefully.

PRTG - VMware datastore latency monitoring

Here is an example how to monitor individual ESXi datastores read/write latency through vCenter and PRTG. Tested with PRTG V16.4.28.7421 and ESXi 5.1. "VMware vSphere PowerCLI" is required on Probe server.

# "DataStoreName - totalWriteLatency.ps1" file
Add-PSSnapin VMware.VimAutomation.Core
$a=Connect-VIServer vCenterServer -User "Domain\User" -Password "UserPassword" -WarningAction SilentlyContinue
$p=Get-Datastore DataStoreName | foreach {$dsName = $_.Name; $uuid = $_.ExtensionData.Info.Url.Split('/')[-2]; Get-VMHost -Datastore $_ | Get-Stat -Stat "datastore.totalWriteLatency.average" -Realtime | where {$_.Instance -eq $uuid} | sort Timestamp -descending | select -first 1 | select -expand Value}
echo $p':ok'

# "DataStoreName - totalReadLatency.ps1" file.
Add-PSSnapin VMware.VimAutomation.Core
$a=Connect-VIServer vCenterServer -User "Domain\User" -Password "UserPassword" -WarningAction SilentlyContinue
$p=Get-Datastore DataStoreName | foreach {$dsName = $_.Name; $uuid = $_.ExtensionData.Info.Url.Split('/')[-2]; Get-VMHost -Datastore $_ | Get-Stat -Stat "datastore.totalReadLatency.average" -Realtime | where {$_.Instance -eq $uuid} | sort Timestamp -descending | select -first 1 | select -expand Value}
echo $p':ok' 

Put both files into "PRTG Installation folder\Custom Sensors\EXE" and create EXE/Script sensors.

Get-UPDReport - User Profile Disks report

This PowerShell script generates a report about User Profile Disks including accounts information from Active Directory.

The report contains the following attributes:
FullName - full path to UPD file.
LastWriteTime - time when UPD was last modified.
Size - file size in MB.
SID - Active Directory account security identifier.
AD_Account_Name - Active Directory account name.
AD_Account_UPN - Active Directory account user principal name.
AD_User_Enabled - information if account is enabled or disabled.
AD_User_LastLogon - Active Directory account last logon time.

Access to UPD path and Active Directory PowerShell module.

Usage examples:
# Gets report where UPD files location is “\\Share\UPDs\”.
.\Get-UPDReport.ps1 -UPDPath "\\Share\UPDs\"

# The same as above but an output will be saved in Report.csv file.
.\Get-UPDReport.ps1 -UPDPath "\\Share\UPDs\" | Export-Csv Report.csv

Compare-GPOs.ps1 - comparing GPO version numbers across Domain Controllers

This PowerShell script compares Group Policy Objects versions between specified Domain Controllers. It is used to identify GPOs, which are not replicated properly or have versions mismatch.

As example I will use Active Directory domain called "AD.FEDENKO.INFO" and 2 domain controllers "DC01"and "DC02".

I will create a test Group Policy called "Test_GPO" shows below.

After some GPO settings amendments you can see that User and Computer versions are changed. 

To simulate replication issue I will go to second domain controller and remove GPT.ini file.

As result you will see User and Computer versions are not available in Group Policy Management console of DC02.

Compare-GPOs PowerShell script can help to identify such Group Policy objects.


DCName                : DC02.AD.FEDENKO.INFO
Id                    : c1acca94-7078-403b-b636-7f9916aa4665
DisplayName           : Test_GPO
Path                  : cn={C1ACCA94-7078-403B-B636-7F9916AA4665},cn=policies,cn=system,DC=AD,DC=FEDENKO,DC=INFO
Owner                 : AD\Domain Admins
CreationTime          : 7/24/2016 4:41:12 PM
ModificationTime      : 7/24/2016 5:04:34 PM
UserDSVersion         : 2
UserSysvolVersion     :
ComputerDSVersion     : 1
ComputerSysvolVersion :
GpoStatus             : AllSettingsEnabled

DCName                : DC01.AD.FEDENKO.INFO
Id                    : c1acca94-7078-403b-b636-7f9916aa4665
DisplayName           : Test_GPO
Path                  : cn={C1ACCA94-7078-403B-B636-7F9916AA4665},cn=policies,cn=system,DC=AD,DC=FEDENKO,DC=INFO
Owner                 : AD\Domain Admins
CreationTime          : 7/24/2016 4:41:12 PM
ModificationTime      : 7/24/2016 5:03:00 PM
UserDSVersion         : 2
UserSysvolVersion     : 2
ComputerDSVersion     : 1
ComputerSysvolVersion : 1
GpoStatus             : AllSettingsEnabled

Also there is optional "-DelayInMilliseconds" parameter, which can be used for CPU usage throttling. The script can be downloaded from TechNet Gallery.
(c) 2014-2017 www.fedenko.info - Vyacheslav Fedenko