Tuesday, 7 July 2015

Powershell: Find difference between two Dates

We can easily find difference between two dates with powershell. We can get difference in Days, Hours, Minutes and Seconds.

Total Days between two dates:

The below powershell script show the total number of days between two dates.
$FromDate  =[DateTime] "04/20/2015"
$ToDate      =[DateTime] "07/07/2015"

($ToDate - $FromDate).TotalDays

Total Hours between two dates:

The below powershell script show the total number of hours between two times.
$FromDate =[DateTime] "07/05/2015"
$ToDate     =[DateTime] "07/07/2015"

($ToDate - $FromDate).TotalHours

Total Minutes between two times:

$FromDate = [DateTime] "07/07/2015 1:47:31 PM"
$ToDate     = [DateTime] "07/07/2015 3:47:31 PM"

($ToDate - $FromDate).TotalMinutes
Read More...

Monday, 6 July 2015

C# - Check current machine is Domain Controller or not

We can determine whether the current machine is domain controller or not by checking Domain Role of the computer in Active Directory environment. We can also ensure if the machine DC or not by checking the Active Directory Domain Services is installed or not in current system.

Check current machine is DC or not by Domain Role in C#:

The below C# code retrieve the Domain Role information of current machine using the WMI class Win32_ComputerSystem. If the value of Domain Role is greater than 3 then the machine is domain controller or else, it is just a computer or member server.
using System.Management;
//----------------
public static bool IsThisMachineIsDC()
{
    bool is_this_DC = false;
    try
    {
        ManagementScope wmiScope = new ManagementScope(@"\\.\root\cimv2");
        wmiScope.Connect();
        ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(wmiScope, new ObjectQuery("SELECT DomainRole FROM Win32_ComputerSystem"));
        foreach (ManagementObject shareData in moSearcher.Get())
        {
            int domainRole = int.Parse(shareData["DomainRole"].ToString());
            if (domainRole >= 4)
            {
                is_this_DC = true;
            }
            break;
        }
    }
    catch (Exception ex)
    {
    }
    return is_this_DC;
}

Check current computer is DC or not by Active Directory Domain Services:

The below C# code checks if the Active Directory Domain Services is installed or not by using the WMI class Win32_ServerFeature.
using System.Management;
//----------------
public static bool IsThisMachineIsDC()
{
    bool is_this_DC = false;
    try
    {
        uint uID = 110;
        string search = string.Format("SELECT * FROM Win32_ServerFeature WHERE ID = 110", uID);
        ManagementObjectSearcher moSearcher = new ManagementObjectSearcher("root\\CIMV2", search);
        foreach (var output in moSearcher.Get())
        {
            if ((uint)(output["ID"]) == uID)
            {
                is_this_DC = true;
                break;
            }
        }
    }
    catch (Exception)
    {
    }

    return is_this_DC;
}
Read More...

Thursday, 25 June 2015

Powershell: Find AD users with Change Password at Next Logon

We can get the list of AD users who should change their password at the next logon using Active Directory powershell cmdlet Get-ADUser. In this article, I am going to write Powershell script to list of AD users who have the setting "Change Password At the Next Logon" enabled and export AD users to CSV file.

use the following command to import Active Directory cmdlets.
Import-Module ActiveDirectory
List AD users with change password at the next logon:
Get-ADUser -LDAPFilter "(pwdLastSet=0)" | Select SamAccountName,distinguishedName

Export AD Users with with Change Password at Next Logon to CSV using Powershell

We can export powershell output into CSV file using Export-CSV cmdlet. The following command export selected properties of all the AD users with change password at next the logon to CSV file.
Import-Module ActiveDirectory
Get-ADUser -LDAPFilter "(pwdLastSet=0)" | Select SamAccountName,distinguishedName |
Export-CSV "C:\\ChangePasswordAtNextLogon.csv" -NoTypeInformation -Encoding UTF8
Read More...

Powershell: Get AD users with Password Never Expires

We can get the list of AD users whose password never expire using Active Directory Powershell cmdlet Search-ADAccount with the parameter PasswordNeverExpires. In this article, I am going to write Powershell script to get the list of AD users whose password never expire and export AD users with password never expires to CSV file.

Run the following command to import Active Directory cmdlets.
Import-Module ActiveDirectory
Powershell command to list password never expire ad users:
Search-ADAccount –PasswordNeverExpires | Select Name, DistinguishedName

Find Password Never Expire AD Users from specific OU:

We can set target OU scope by using the parameter SearchBase in Search-ADAccount cmdlet. The following command select and list all the AD users whose password never expires from the Organization Unit 'TestOU'.
Import-Module ActiveDirectory
Search-ADAccount  -SearchBase "OU=TestOU,DC=TestDomain,DC=Com" –PasswordNeverExpires |
Select -Property Name,DistinguishedName

Export Password Never Expire AD Users to CSV using Powershell

We can export powershell output into CSV file using Export-CSV cmdlet. The following command export selected properties of all the password never expire AD users to CSV file.
Import-Module ActiveDirectory
Search-ADAccount –PasswordNeverExpires | Select -Property Name,DistinguishedName |
Export-CSV "C:\\PasswordNeverExpireADUsers.csv" -NoTypeInformation -Encoding UTF8

CSV output of Password Never Expire AD users report:

Powershell script to find AD users whose password never expires
Read More...

Wednesday, 24 June 2015

Powershell : Find machine name from IP address and vice versa

In this article, I am going to write powershell script to find machine name from IP address and get IP address from computer name. We can resolve hostname from IP address and vice versa by using .NET class System.Net.Dns.

Find machine name from IP address:

$ipAddress= "192.168.1.54"
[System.Net.Dns]::GetHostByAddress($ipAddress).Hostname

Get IP address from Hostname:

$machineName= "DC1"
$hostEntry= [System.Net.Dns]::GetHostByName($machineName)
$hostEntry.AddressList[0].IPAddressToString

Resolve Hostname for set of IP addresses from text file:

Use the below powershell script to find machine name for multiple IP addresses. First create the text file ip-addresses.txt which includes one IP address in each line. You will get the machine name list in the txt file machinenames.txt.
Get-Content C:\ip-addresses.txt | ForEach-Object{
$hostname = ([System.Net.Dns]::GetHostByAddress($_)).Hostname
if($? -eq $True) {
  $_ +": "+ $hostname >> "C:\machinenames.txt"
}
else {
   $_ +": Cannot resolve hostname" >> "C:\machinenames.txt"
}}

Find Computer name for set of IP addresses from CSV:

Use the below powershell script to get hostname for multiple IP addresses from csv file. First create the csv file ip-addresses.csv which includes the column IPAddress in the csv file. You will get the hostname and IP address list in the csv file machinenames.csv.
Import-Csv C:\ip-Addresses.csv | ForEach-Object{
$hostname = ([System.Net.Dns]::GetHostByAddress($_.IPAddress)).Hostname
if($? -eq $False){
$hostname="Cannot resolve hostname"
}
New-Object -TypeName PSObject -Property @{
      IPAddress = $_.IPAddress
      HostName = $hostname
}} | Export-Csv C:\machinenames.csv -NoTypeInformation -Encoding UTF8
Read More...

Friday, 19 June 2015

Powershell : Export AD Groups and Members to CSV file

We can get the list of AD groups and its members using the Active Directory Powershell cmdlets Get-ADGroup and Get-ADGroupMember.

Use the following command to enable Active Directory cmdlets.
Import-Module ActiveDirectory

Get specified AD Group members:

Use the below Powershell command to get the list of members of specified AD Group.
Get-ADGroupMember -Identity "Domain Admins" | Select Name, SamAccountName

Export AD Groups and Members to CSV:

The following PowerShell script gets a list of all AD groups and its members. The Get-ADGroup cmdlet gets all the AD Groups and the list of group values passed into ForEach-Object to get members of every AD Group. Finally it exports both groups and members as semi-colon(;) separated values to CSV file using Export-CSV cmdlet.
$Groups = Get-ADGroup -Filter "*"
$Groups | ForEach-Object {
$group = $_.Name
$members = ''
Get-ADGroupMember $group | ForEach-Object {
        If($members) {
              $members=$members + ";" + $_.Name
           } Else {
              $members=$_.Name
           }
  }
New-Object -TypeName PSObject -Property @{
      GroupName = $group
      Members = $members
     }
} | Export-CSV "C:\\AD-Group-Members.csv" -NoTypeInformation -Encoding UTF8

Sample CSV output of Export AD Groups and Members:

Powershell script to export AD Groups and Members to CSV file
Read More...

Get AD Group Members using Powershell script

We can get the list of AD Group members using Active Directory Powershell cmdlet Get-ADGroupMember. In this article, I am going to write Powershell script to get list of AD Group members, export group members to CSV file and export AD groups and members to CSV file.

Run the following command to import Active Directory cmdlets.
Import-Module ActiveDirectory
Use the following Powershell command to get the list of specified AD Group members.
Get-ADGroupMember -Identity "Domain Admins" | Select Name, SamAccountName

Export AD Group Members to CSV:

The following Powershell script gets a list of members of specified AD group and exports member details to CSV file. Replace the group name "Domain Admins" with your own group name in the below script.
$GroupName = "Domain Admins"
Get-ADGroupMember -Identity $GroupName | Select Name, SamAccountName |
Export-CSV "C:\\ADGroupMembers.csv" -NoTypeInformation -Encoding UTF8

Export AD Groups and Members to CSV:

The following PowerShell script gets a list of all Active Directory groups and its members. The Get-ADGroup cmdlet gets all the AD Groups and passed into ForEach-Object to get members of every AD Group. Finally it exports both group and member details to CSV file.
$Groups = Get-ADGroup -Filter "*"
$Groups | ForEach-Object {
$group = $_.Name
$members = ''
Get-ADGroupMember $group | ForEach-Object {
        If($members) {
              $members=$members + ";" + $_.Name
           } Else {
              $members=$_.Name
           }
  }
New-Object -TypeName PSObject -Property @{
      GroupName = $group
      Members = $members
     }
} | Export-CSV "C:\\AD-Group-Members.csv" -NoTypeInformation -Encoding UTF8

CSV output AD Groups and Members:

Get AD Group Members using Powershell script

Read More...

Thursday, 18 June 2015

Change Service Account Information using VBScript

We can easily manage Windows Service account through vbscript by using the WMI class Win32_Service. Use the below vbscript code to change windows service account

1. Copy the below vbscript code and paste it in notepad or a VBScript editor.
2. Change the value strService into your own windows service name which you want to change service account.
3. Replace your new user account and password in the variables strUser and strPwd.
3. If you want to modify a service account in Remote machine, set the Remote computer name in the variable strComputer instead of "." (local machine).
4. Save the file with a .vbs extension, for example: ChangeServiceAccount.vbs
5. Double-click the vbscript file (or Run this file from command window) to change the given windows service logon user account .
Option Explicit
Dim objWMIService, objService,errOut
Dim strService,strComputer,strUser,strPwd
strService="RemoteRegistry"
strUser= ".\Morgan"
strPwd = "Password"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
For Each objService In objWMIService.ExecQuery("Select * from Win32_Service Where Name = '"&strService&"'")
    errOut = objService.Change( , , , , , , strUser, strPwd)
  If(errOut=0) Then
     WScript.Echo strService & ": Service account changed successfully"
  Else
     WScript.Echo strService & ": Account change failed. Error code: "& errOut
  End If
Next
WScript.Quit
Use the following vbscript code if you want to change only password of the service account.
Option Explicit
Dim objWMIService, objService,errOut
Dim strService,strComputer,strPwd
strService="RemoteRegistry"
strPwd = "NewPassword"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
For Each objService In objWMIService.ExecQuery("Select * from Win32_Service Where Name = '"&strService&"'")
    errOut = objService.Change( , , , , , , , strPwd)
  If(errOut=0) Then
     WScript.Echo strService & ": Service account password changed successfully"
  Else
     WScript.Echo strService & ": Password change failed. Error code: "& errOut
  End If
Next
WScript.Quit
Read More...

Change Service Account Password using VBScript

We can easily manage Windows Service through vbscript by using the WMI class Win32_Service. Use the below vbscript code to change service account password.

1. Copy the below vbscript code and paste it in notepad or a VBScript editor.
2. Change the value strService into your own windows service name which you want to reset password.
3. If you want to modify password of a service account in Remote machine, set the Remote computer name in the variable strComputer instead of "." (local machine).
4. Save the file with a .vbs extension, for example: ChangeServicePwd.vbs
5. Double-click the vbscript file (or Run this file from command window) to change the given windows service account password.
Option Explicit
Dim objWMIService, objService,errOut
Dim strService,strComputer
strService="RemoteRegistry"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
For Each objService In objWMIService.ExecQuery("Select * from Win32_Service Where Name = '"&strService&"'")
    errOut = objService.Change( , , , , , , , "password")
  If(errOut=0) Then
     WScript.Echo strService & ": Service account password changed successfully"
  Else
     WScript.Echo strService & ": Password change failed. Error code: "& errOut
  End If
Next
WScript.Quit
Read More...

Wednesday, 17 June 2015

Powershell Error: Pipelines Cannot be Executed Concurrently

Problem:

Today I have received the Powershell error "Pipelines Cannot be Executed Concurrently" while running commands in Exchange Management Shell.
Pipeline not executed because a pipeline is already executing. Pipelines cannot be executed concurrently.
    + CategoryInfo          : OperationStopped: (Microsoft.Power...tHelperRunspace:ExecutionCmdletHelperRunspace) [],
   PSInvalidOperationException
    + FullyQualifiedErrorId : RemotePipelineExecutionFailed

Pipeline not executed because a pipeline is already executing. Pipelines cannot be executed concurrently.
    + CategoryInfo          : OperationStopped: (Microsoft.Power...tHelperRunspace:ExecutionCmdletHelperRunspace) [],
   PSInvalidOperationException
    + FullyQualifiedErrorId : RemotePipelineExecutionFailed
You can simply reproduce this error by running the following Exchange Powershell commands by two times.
Get-DistributionGroup | ForEach-Object {
$group = $_.Name
Get-DistributionGroupMember $_.Name | ForEach-Object {
      New-Object -TypeName PSObject -Property @{
       Group = $group
       Members = $_.Name
}}}

Fix/Solution: Pipelines Cannot be Executed Concurrently

In above Powershell, you can see that we are piping the output of Get-DistributionGroup to Foreach-Object and attempting to run the Get-DistributionGroupMember cmdlet.

The Get-DistributionGroupMember cmdlet is designed to accept pipeline input from Get-DistributionGroup, so there is no need to use Foreach-Object. You can just pipe Get-DistributionGroup to Get-DistributionGroupMember.
Get-DistributionGroup | Get-DistributionGroupMember
But the above command returns only members of all the Groups and doesn't return group name. Our need is to get both group names and members, so we supposed to use ForEach-Object. To fix this issue, we have to do it as two step process. First, we need to save the results of the Get-DistributionGroup cmdlet to a variable. Then we can pipe the variable to ForEach-Object.
$Groups = Get-DistributionGroup
$Groups | ForEach-Object {
$group = $_.Name
Get-DistributionGroupMember $_.Name | ForEach-Object {
      New-Object -TypeName PSObject -Property @{
       Group = $group
       Members = $_.Name
}}}
Read More...

Powershell: Export Distribution List Members to CSV

We can get Distribution list members by using the Exchange cmdlet Get-DistributionGroupMember in Powershell and export Distribution list members to CSV file using Powershell cmdlet Export-CSV.

Get Distribution Group members:

Use the following Powershell command to list Distribution list members.
Get-DistributionGroupMember -Identity <Group-Name>

Export Members of a single Distribution Group to CSV:

The following Powershell script gets members of a given distribution group and exports output to CSV file. Replace the distribution group name "TestDG" with your own group name in the below script.
$DGName = "TestDG"
Get-DistributionGroupMember -Identity $DGName | Select Name, PrimarySMTPAddress |
Export-CSV "C:\\Distribution-List-Members.csv" -NoTypeInformation -Encoding UTF8

Export All Distribution Groups and Members to CSV:

We can list all the distribution groups using Exchange cmdlet Get-DistributionGroup and get its members by passing group name into Get-DistributionGroupMember cmdlet. The following Powershell script gets all the distribution groups and its members and exports group names and members to CSV file.
$Groups = Get-DistributionGroup
$Groups | ForEach-Object {
$group = $_.Name
$members = ''
Get-DistributionGroupMember $group | ForEach-Object {
        If($members) {
              $members=$members + ";" + $_.Name
           } Else {
              $members=$_.Name
           }
  }
New-Object -TypeName PSObject -Property @{
      GroupName = $group
      Members = $members
     }
} | Export-CSV "C:\\Distribution-Group-Members.csv" -NoTypeInformation -Encoding UTF8
Read More...

Powershell: Get Distribution List Members

We can get and list Distribution group members using the Exchange Powershell cmdlet Get-DistributionGroupMember. In this article, I am going to write Powershell script to get distribution list members, export distribution list members to CSV file and export distribution groups and members to CSV file.

Get Distribution List members:

Run the following command to enable Exchange cmdlets if you are working with normal PowerShell console instead of Exchange Management Shell.
Add-PSSnapin *Exchange*
Use the following Powershell command to list Distribution group members.
Get-DistributionGroupMember -Identity <Group-Name>
By default this command returns only two properties (Name and RecipientType) of the Group members. You can select required values by using select command.
Get-DistributionGroupMember -Identity <Group-Name> | Select Name, RecipientType, PrimarySMTPAddress

Export Distribution List Members to CSV:

The following Powershell script gets a list of distribution group members and exports output to CSV file. Replace the distribution group name "TestDG" with your own group name in the below script.
$DGName = "TestDG"
Get-DistributionGroupMember -Identity $DGName | Select Name, PrimarySMTPAddress |
Export-CSV "C:\\Distribution-List-Members.csv" -NoTypeInformation -Encoding UTF8

Export Distribution Groups and Members to CSV:

The following PowerShell script gets a list of Distribution groups and its members and exports output to CSV file.
$Groups = Get-DistributionGroup
$Groups | ForEach-Object {
$group = $_.Name
$members = ''
Get-DistributionGroupMember $group | ForEach-Object {
        If($members) {
              $members=$members + ";" + $_.Name
           } Else {
              $members=$_.Name
           }
  }
New-Object -TypeName PSObject -Property @{
      GroupName = $group
      Members = $members
     }
} | Export-CSV "C:\\Distribution-Group-Members.csv" -NoTypeInformation -Encoding UTF8
Read More...

Tuesday, 16 June 2015

Configure Desktop Wallpaper Background via Group Policy

Setting the Desktop Wallpaper Background using Group Policy is a most common task for Administrator to maintain common environment in all the Active Directory user's computer. We can set Desktop Wallpaper Background via Group Policy using following two methods.

Setting Desktop Wallpaper using GPO's Administrative Template Setting

This method is the easiest and most commonly used way for configuring the Desktop Wallpaper using GPO.

Note: Users can't change their backgrounds once the background wallpaper is applied using this method.

Follow the steps to set Desktop Wallpaper using Administrative Template:

1. Open the Group Policy Management console by running the command gpmc.msc.

2. Expand the tree and right-click on the OU you want this policy to be applied to. Now, I am going to apply for users who are under the OU TestOU. so right-click on the OU TestOU, and click Create a GPO in this domain, and Link it here...
Configure Desktop Wallpaper Background via Group Policy

3. Give the new policy name and click OK. I have given new policy name "Desktop Wallpaper Policy".

4. Now right-click on the newly created GPO Desktop Wallpaper Policy and click Edit...

Configure Desktop Wallpaper Background via Group Policy

5. In the Group Policy Management Editor window, expand User Configuration and go to the node Desktop (User Configuration > Administrative Templates > Desktop > Desktop). In right hand side, select the setting Desktop Wallpaper and double-click it. 

Configure Desktop Wallpaper Background through Group Policy

6. Enable the Desktop Wallpaper setting by selecting the option Enabled and set the explicit local path or a UNC to the image you want display as the desktop wallpaper. Finally click the Apply button to complete.

Configure Desktop Wallpaper Background through Group Policy

7.Now update the GPO by running the command gpupdate /force in Command Window.

8. That's all. Now we have successfully created GPO to apply desktop background wallpaper for the users who are under OU TestOU. Behind the scene, this policy update the registry value HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System\Wallpaper.

Configure Desktop Wallpaper Background using Group Policy

9. Now, you can see that desktop wallpaper by logging into any of the user's desktop who are under TestOU.

Note: This setting is not applied to domain users who log on to client computers that are running Windows 7 or Windows Server 2008 R2. You need to install the hotfix http://support.microsoft.com/kb/977944 to fix this issue.


Apply Desktop Wallpaper using GPO Preference Registry Setting

As I said in Method #1, the Desktop Background Wallpaper is controlled by the Registry setting KEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System\Wallpaper , we can also use Group Policy Preferences Registry setting to configure desktop wallpaper background through Group Policy.

Note: We can allow user to change their background using this method and also we can restrict users to change if needed.

Follow the steps to set Desktop Wallpaper using Group Policy Preference Registry Extension:

- Repeat the steps 1-4 in Method #1 (Revert the old changes if you configured using Method #1).
5. In the Group Policy Management Editor window, expand User Configuration and go to the node Registry (User Configuration > Preferences > Windows Settings > Registry ).
6. Right-click on the node Registry and select New > Registry Item.

Configure Desktop Wallpaper Background using GPO

7. Now depends on the need you can set registry key that you configure for this setting. You can either have this as a Restricted setting or Unrestricted setting that allows users to change their own background wallpaper. Click Apply button to complete the process.
Restricted: HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System\Wallpaper
Unrestricted: HKCU\Control Panel\Desktop\Wallpaper

Configure Desktop Wallpaper Background through GPO

8. Now update the GPO by running the command gpupdate /force.

9. That's all. Now we have successfully created GPO to apply desktop background wallpaper for the users who are under OU TestOU. You can see that desktop wallpaper by logging into any of the user's desktop who are under TestOU.

Read More...

Enable Exchange Cmdlets in Powershell

We can run Exchange Management Powershell cmdlets using Exchange Management Shell to get exchange related details. However, If you are working with normal PowerShell console instead of Exchange Management Shell, you need to import Exchange snapins to enable and use Exchange Management cmdlets.

If you run the Exchange commands in Powershell (Ex: Get-Mailbox) without loading the Exchange Management cmdlets, you will get the following error:
The term 'Get-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
 spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:12
+ Get-Mailbox <<<<
    + CategoryInfo          : ObjectNotFound: (Get-Mailbox:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
Run the following command to load Exchange Powershell cmdlets that supports Admin tasks.
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
-or- Run the following command if you want to enable all the Exchange related cmdlets.
Add-PSSnapin "Exchange*
Note: The Exchange Management Powershell cmdlets will be available only if the Exchange System Management Tools installed in your machine. Otherwise, you need to use Exchange Cmdlets through Remote Exchange Powershell. Read this article to Connect Remote Exchange PowerShell.
Read More...

Powershell - List Domain Controllers and IP Address

We can list all the Active Directory Domain Controllers in current domain or forest using .NET classes System.Directoryservices.Activedirectory.Domain and System.Directoryservices.Activedirectory.Forest. We can resolve IP Address for every Domain Controller by using .NET class System.Net.Dns.

Note: This PowerShell script doesn't require to import Active Directory Module since it is using the methods from .NET Framework.

List all Domain Controllers and IP Address in Current Domain:

This following script returns all the Domain Controllers from current Domain and resolves IP address by DNS lookup. The results are output to the PowerShell console screen.
$domain = [System.Directoryservices.Activedirectory.Domain]::GetCurrentDomain()
$domain | ForEach-Object {$_.DomainControllers} | 
ForEach-Object {
  $hostEntry= [System.Net.Dns]::GetHostByName($_.Name)
New-Object -TypeName PSObject -Property @{
      Name = $_.Name
      IPAddress = $hostEntry.AddressList[0].IPAddressToString
    }
} | Select Name, IPAddress

Export List of Domain Controllers and IP Address to CSV:

We can export PowerShell output into CSV file using Export-CSV cmdlet. The following PowerShell script find all the Domain Controllers from current Domain and resolve IP address by DNS lookup and exports output to CSV file.
$domain = [System.Directoryservices.Activedirectory.Domain]::GetCurrentDomain()
$domain | ForEach-Object {$_.DomainControllers} | 
ForEach-Object {
  $hostEntry= [System.Net.Dns]::GetHostByName($_.Name)
  New-Object -TypeName PSObject -Property @{
      Name = $_.Name
      IPAddress = $hostEntry.AddressList[0].IPAddressToString
     }
} | Export-CSV "C:\\DomainControllers.csv" -NoTypeInformation -Encoding UTF8
Read More...