How to Digitally Sign the Powershell Scripts with Microsoft CA in Domain – A step-by-step Guide – Part 2

2) Request the certificate the sign the script by user1
Go to >> Part-1:Install ADCS service and configure Code Signing Certificate Template
Go to >> Part-3: Configure GPO to allow only signed scripts and add user1’s certificate to trusted publisher group on domain computers
Go to >> Part-4: Run the test scripts

In the Part-1, we have configured AD CS role and configure certificate template. Now, it’s time that user1 request his certificate and sign his script. On the Node-1 computer with user1 logged on as domain user: Continue reading “How to Digitally Sign the Powershell Scripts with Microsoft CA in Domain – A step-by-step Guide – Part 2”

How to Digitally Sign the Powershell Scripts with Microsoft CA in Domain – A step-by-step Guide – Part 1

Go to >> Part-2: Request the certificate the sign the script by user1
Go to >> Part-3: Configure GPO to allow only signed scripts and add user1’s certificate to trusted publisher group on domain computers
Go to >> Part-4: Run the test scripts

This is a lengthy post of how to digitally sign your powershell script, so I divide it up to 4 sections.  Digitally signing of powershell script, for the security purpose, is particularly useful to prevent the execution of malicious scripts on servers or workstations in your domain environment. Today, I will show you how to sign your powershell scripts from Microsoft CA and use GPO to control the execution of unsigned scripts in domain environment. Continue reading “How to Digitally Sign the Powershell Scripts with Microsoft CA in Domain – A step-by-step Guide – Part 1”

Recover Crashed Exchange 2013 Mailbox Server in DAG

Recovering a crashed mailbox server is a straight-forward process if they are in DAG. You can do it by setup.exe /m:RecoverServer. However, there are certain steps to do for smooth recovery process. The following steps will do to recover the crashed mailbox servers in DAG. I will explain the each steps in more details.
  1. Reset the crashed computer accounts in AD.
  2. Install new server OS to replace the old crashed servers.  Install windows features, pre-requisites and updates.
  3. Remove the database passive copies on crashed servers. If the servers are accessible you can manually delete DB file and logs file residues from crashed servers.
  4. Remove the crash servers from DAG. This can be done by EMC or EMS.
  5. Evict(remove) the crash servers from failover cluster manager.
  6. Start the recovery process by running setup file in command prompt with necessary switches. More details later in this section.
After recovery process is complete, you can see the servers come up in EMC console. Then, do DAG and DB reseeding as necessary. Done!
 Here are detail steps I did for recovery:
1. Reset the crashed computer accounts in AD.
    You can do it in ADUC console. Right-click the crashed computer account and “Reset Account”.
 
2. Install new server OS to replace the old crashed servers.
Install new servers with the same spec as old ones. You also need to install some windows features ,Microsoft filter packs and Unified Communication Runtime.
a) On new machine, open powershell with “Run as Administrator.
b) Install the necessary windows features in Powershell:
Install-WindowsFeature AS-HTTP-Activation, Desktop-Experience, NET-Framework-45-Features, RPC-over-HTTP-proxy, RSAT-Clustering, RSAT-Clustering-CmdInterface, Web-Mgmt-Console, WAS-Process-Model, Web-Asp-Net45, Web-Basic-Auth, Web-Client-Auth, Web-Digest-Auth, Web-Dir-Browsing, Web-Dyn-Compression, Web-Http-Errors, Web-Http-Logging, Web-Http-Redirect, Web-Http-Tracing, Web-ISAPI-Ext, Web-ISAPI-Filter, Web-Lgcy-Mgmt-Console, Web-Metabase, Web-Mgmt-Console, Web-Mgmt-Service, Web-Net-Ext45, Web-Request-Monitor, Web-Server, Web-Stat-Compression, Web-Static-Content, Web-Windows-Auth, Web-WMI, Windows-Identity-Foundation
   c) Download and install other prerequisities from here:
Note: Use the same computer name as old ones and join to domain.
 
3. Remove the database passive copies on crashed servers.
You can do it on EMS on good servers(since bad servers are not accessible). Open EMS and type:
[Ps]C:> Get-MailboxDatabaseCopyStatus *<name of your crashed server>
Make sure all the listed selected databases on your console output are all in Service Down state. Now, you can remove the failed databases by the following command. This should give you some warnings and don’t worry, just proceed it.
[Ps]C:> Get-MailboxDatabaseCopyStatus *<name of your crashed server> | Remove-MailboxDatabaseCopy
4. Remove the crash servers from DAG.
You can remove crashed servers from DAG by EMC console.
Go to EMC >> servers >> database availability group. Select the DAG Group and click the “Manage DAG Membership” icon. Remove the crashed servers from there.
<or>
You can remove crashed servers in EMS shell.
Remove-DatabaseAvailabilityGroupServer -Identity <your DAG Name> -MailboxServer <Your failed server name>
 
5. Evict the crash servers from failover cluster manager
Removing the failed servers from DAG does not remove them from failover cluster itself. So, we have to manually remove it. Before this, you can check which nodes in cluster are currently down state by the elevated command prompt.
C:cluster.exe node
To evict the node from cluster:
Go to Failover Cluster Manager >> [your cluster name] >> Nodes >>  select your failed server >> Right-click and choose “More action” >> Evict
6. Start the recovery process
Go the directory where setup files are located and run:
setup.exe /m:RecoverServer /IAcceptExchangeServerLicenseTerms
 
In most cases, when you use the original exchange installation CD for recovery, you might encounter errors that prompts you to use the later cumulative updated exchange setup files than the ones you have setup. If so, you can find the latest released Exchange CUs here, get the latest CU, extract it to folder and run the setup files again with the switches shown above.
You can also check your current exchange server version with build numbers on good servers in EMS shell by:
 [PS] C:\>Get-ExchangeServer | Format-List Name, Edition, AdminDisplayVersion

As the recovery process is fetching info from AD objects and reinstalling the exchange server, you can see the progress in the console.
7) Add to DAG and Re-seeding DB copies
After the servers are recovered, you need to reboot the recovered servers for proper functioning. Then,
       a) add the servers back to DAG group.
       b) reseed the DB passive copies.
This is quite a simple process and I won’t go details with these.
Congratulation ! Your recovery process is now Successful.
Note: For me, I had some minor issues when reseeding DB with the following errors. So, I had to take additional steps to fix.
ERROR:
The seeding operation failed. Error: An error occurred while performing the seed operation. Error: Unable to delete logs at ‘D:\M datalogs’. The database has been seeded successfully. If any obsolete log files exist, manually delete them to prevent database divergence. Error: System.IO.IOException: The file or directory is corrupted and unreadable. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileInfo.Delete() at Microsoft.Exchange.Cluster.Replay.DatabaseSeederInstance.DeleteLogFiles(DirectoryInfo di, String logfilePrefix, String logfileSuffix, Int32& logNum) at Microsoft.Exchange.Cluster.Replay.DatabaseSeederInstance.
So, I assume there is some disk corruption in my harddisk. Fortunately, that server has no active database copies, So I manually chkdsk the volume without /r switch. Since some disk errors are found, I use the chkdsk /r /f instead.
C:chkdsk d: /r /f
Then, I reseed the DB again, and another errors come up.
Error:
The seeding operation failed. Error: An error occurred while performing the seed operation. Error: Failed to notify source server ‘[my source server name]’ about the local truncation point. Hresult: 0xc8000713. Error: Unable to find the file.
According to this article , it said that this is the issue with the old logs folder which was not in the sync. And, I did the following procedures:
    1) Dismount the Active Copy of the database from EMC console.
     2) Find the Database file path and Log file folder path in EMS shell. Let us assume here, edb file path is D:\Databasemydatabase.edb  and Log folder path is D:\DatabaseLogs.
[PS]C:>Get-MailboxDatabase mdb04 | fl *path*
 
     3) Login to the source server hosting that database, here ‘[my source server name]’ and you need to run eseutil.exe in elevated command prompt to verify that DB is in clean shutdown state. We have got the DB path & log folder path in step 2.
C:\eseutil /mh D:Databasemydatabase.edb
(If the DB state is clean shutdown, you can continue the next step. If the state is dirty shutdown, you need to go for the recovery process using log files. And this article will help you.)
     4) If the DB is clean shutdown state, you can delete all log files in folder path we obtained from step-2. If you are unsure, you can rename the Log folder and delete them later. You can also delete via the following command if there are thousands of log files.
D:\DatabaseLogsrmdir . /s /q
 
     5) Mount the database, this will create new log files.
     6) Reseed the database copies.

Search Multiple Words in Multiple Excel files using Powershell !

Inventory documentation with Excel is something that most infrastructure administrators have to deal with on a daily basis. Sometimes, I have to search for a bulk of IP addresses in multiple Excel files, but I have to do it by opening the Excel files one by one. After investigating how this can be achieved in PowerShell, I found that using comObject is the way to go, as it can be used to automate most Windows applications. Make sure Microsoft Excel is already installed before you run the script.

How to use the script:

You need to create search values.txt file and insert the contents line-by-line that you want to search. (Also the script will automatically create the search values.txt on the first run if not exists). The output files will have the same names as original files appended with _RESULT.xlsx

Then, open powershell console and run with following necessary parameters. You will need to specify -Folder or -File parameter at least.

Example:

.\Excel_search.ps1 C:\MyExcelFiles -Recurse -Color -OpenFile -Grid

Parameters:

-Folder : The folder name in which multiple Microsoft Excel files should already exist (Use it if the -File  is not specified)

-File : The file name of the Microsoft Excel file (Use it if the -Folder is not specified)

-Recurse : Use this with -Folder option to search excel files recursively

-Color : Use this to colorize the values found in the excel files (in darkblue color)

-Grid : Use this to display the summary of search results in grid output windows (See Fig-1) 

-OpenFile : Use this to automatically open the output files when the search operation is completed.

Find Multiple Words in Excel with Powershell
Fig-1: Search Results with Grid View


Find Multiple Words in Excel with Powershell
Fig-2: Results without Grid View
Find Multiple Words in Excel with Powershell
Fig-3: The new 2 files are created in which values are found
Find Multiple Words in Excel with Powershell
Fig-4: Usage and Examples

You can download my script from github.

View SSL/TLS Certificate Info with OpenSSL Command

You can simply check the SSL/TLS certificate information which is listening at non-http port (like STMP) by using the OpenSSL tool. All you need to know is to the port that uses encrypted connection. For example, I view the certificate info at CentOS website & TLS certificate used for smtp connection. With WSL, OpenSSL already installed and you’re ready to go.

For example here, I check the CentOS website & TLS certificate which is used for smtp connection.

For SSL connection:
openssl s_client -showcerts -connect www.centos.org:443

For TLS connection:
openssl s_client -connect mail.centos.org:25 -starttls smtp

OpenSSL to view SSL Cert Info
Fig-1: Viewing SSL Cert Info

OpenSSL to view TLS Cert Info
Fig-2: Viewing TLS Cert Info

Creating Active Directory Users in the Nested OUs

It is the powershell script that will automatically create AD users. What makes it unique is that all the necessary OUs (even nested OUs) are created in advance before users creation. So, you won’t need a separate script for both tasks. Here, I give the screenshot of my testing domain, with example users defined in my csv file.

You must include these properties as the csv file headers (See Fig-2). But leave the values blank if some users do not have these properties.

EmployeeID, DisplayName, OU, Description, Name, GivenName, SurName, SamAccountName, Title, Departement, Domain, Office, OfficePhone, Company, EmailAddress, Password

It takes only 3 min to create 1500 users for me, Cheers!

Create AD Users in nested OU with Powershell
Fig-1: Demo of AD user creation
Sample CSV file for AD user creation
Fig-2: Sample CSV file

You can download my script from github.

Powershell: Find When Active Directory Users’ Memership, OU and Creation Date

It’s a one-liner command that I use to find the most common AD attributes including the Creation date, Member Of and OU location. I attached the screenshot as example.

Command:

Get-ADUser -filter * -property name,displayname,MemberOf,description,Title,TelephoneNumber,CanonicalName,whencreated,emailaddress| select Name,
Displayname, @{Name=”MemberOf”;Exp={ ((-join (($_.memberof.split(‘,’)) -like “*cn=*”) ) -replace ‘CN=’,”,”).TrimStart(“,”)  }}, Description, Title, TelephoneNumber, @{Name=”OU”;Exp={ $_.CanonicalName.Remove($_.CanonicalName.LastIndexOf($_.Name)-1)  }}, Whencreated, Emailaddress

You can export to CSV file with the following commands.

Get-ADUser -filter * -property name,displayname,MemberOf,description,Title,TelephoneNumber,CanonicalName,whencreated,emailaddress| select Name,
Displayname, @{Name=”MemberOf”;Exp={ ((-join (($_.memberof.split(‘,’)) -like “*cn=*”) ) -replace ‘CN=’,”,”).TrimStart(“,”)  }}, Description, Title, TelephoneNumber, @{Name=”OU”;Exp={ $_.CanonicalName.Remove($_.CanonicalName.LastIndexOf($_.Name)-1)  }}, Whencreated, Emailaddress| export-csv -NoTypeInformation ADuser_Properties.csv

Get AD User Properties
Fig-1: Get AD User Properties

Powershell: Find Which Running Processes are Connecting to the Internet

These days, I have been looking for a way to find which running processes on my machines are accessing the internet without my consent. And fortunately, I found a script from TechNet Gallery written by Cookie.Monster. The script extract the connection info from netstat command and create Custom Object for further processing. So, I just changed the by adding some regx to find the public IP addresses. For testing purpose, I use the TeamViewer on my machine. Continue reading “Powershell: Find Which Running Processes are Connecting to the Internet”

PowerCLI: Automatically Power on VMs from the Saved CSV file

It’s the Powershell script using PowerCLI to power on a bunch of VMs when multiple servers go offline or during disaster recovery. Not using any third-party tools, I got the idea to do it in PowerCLI to backup the current Powerstate of the VMs to csv file and compare it when powering on VMs, so that you do not mistakenly turn on VMs that are initially powered off. I added the progress bar to get the progress state of powering on VMs.

What this script will do:
1) It will backup the current Power State of VMs to csv file. It will create the new csv file if not already created.
2) If the file is already created, it will check the current power state of VMs by comparing with the csv file.
3) If the Powered On server in the list is found as powered off in vCenter or esxi, it will power on all VMs.

Please note that you will need to connect the vCenter/Esxi before running the script. Also, you will need to disconnect the vCenter/Esxi connection once the job is finished.

Use the the following command to connect to the host.
Connect-VIServer -Server yourserver -Credential (get-credential)

Use the following command to disconnect from host.
Disconnect-VIServer -Server yourserver -confirm:$false

PowerCLI Saving VM Power State and Power On VMs
Fig-1: Demo of Saving VM Power State and Power On VMs

PowerCLI Powering on VM in action
Fig-2: Powering On VM in Action

You can download my script from the github.

PowerCLI: Get the Vmnic CDP Information of Esxi Hosts

In these days, I do have to backup the CDP info of our current esxi hosts and fortunately I found script this blog and official VMware site to discover information. Only I made little changes to the script to suite my environment. You need Powercli (PowerCLI 5.5 is here) already installed, and must be connected to vCenter of specific Esxi host before running the script.

If you’re not connected to vCenter, you can use the command:
Connect-VIServer -Server yourServerNameOrIP -Credential (Get-Credential)

After you have finished running the script, you can disconnect the vCenter Server by using the following command.
Disconnect-VIServer -Server yourServerNameOrIP

Note: You can also add the esxi hostnames in the hostlist.txt to get the CDP info for specific hosts only. If the hostlist.txt file doesn’t exit, then it will gather information for all Esxi hosts.

PowerCLI Get CDP Info
Fig-1: Demo of Getting the CDP Info

You can download my script from the github.