Wednesday, 27 May 2015

Powershell - Export AD Computers to CSV

We can generate and export Active Directory computers report to CSV file using powershell cmdlets Get-ADComputer and Export-CSV. The Get-ADComputer cmdlet supports SQL like filter and LDAP filter to filter AD Computers.

Find and List AD Computers

The following powershell script list the selected properties of all Active Directory computers.
Import-Module ActiveDirectory
Get-ADComputer -Filter * -Properties * |
 Select -Property Name,operatingSystem,@{Name="LastLogon";
Expression={[DateTime]::FromFileTime($_.lastLogon).ToString()}}

Apply SQL Like filter to get specific computers:

The Get-ADComputer cmdlet supports SQL like filter, users who are not familiar with LDAP filter can easily use this filter to get only specific set of AD computers. This following powershell script export the selected properties to CSV file of AD computers whose OperatingSystem contains the text 'Server 2008 R2'.
Import-Module ActiveDirectory
Get-ADComputer -Filter 'OperatingSystem -like "*Server 2008 R2*"' -Properties * |
 Select -Property Name,operatingSystem,@{Name="LastLogon";
Expression={[DateTime]::FromFileTime($_.lastLogon).ToString()}}

Apply LDAP Filter to get specific set of AD computers:

If your are familiar with LDAP filter, instead of normal filter, you can also use LDAP filter with Get-ADComputer powershell cmdlet with more flexibility to filter Active Directory compters. The below script exports all the computers whose OperatingSystem contains the text 'Server 2008 R2'.
Import-Module ActiveDirectory
Get-ADComputer -LDAPFilter '(OperatingSystem=*Server 2008 R2*)' -Properties * |
 Select -Property Name,operatingSystem,@{Name="LastLogon";
Expression={[DateTime]::FromFileTime($_.lastLogon).ToString()}}

Export AD Computers to CSV file

We can generate and export Active Directory computer report to CSV file using Powershell cmdlets Get-ADComputer and Export-CSV. You can add more attributes in Select -Property field to export more AD attributes.
Import-Module ActiveDirectory
Get-ADComputer -Filter 'OperatingSystem -like "*Server 2008 R2*"' -Properties * |
 Select -Property Name,operatingSystem,@{Name="LastLogon";
Expression={[DateTime]::FromFileTime($_.lastLogon).ToString()}} |
# Export AD Computer Report to CSV file 
Export-CSV "C:\\ADComputers.csv" -NoTypeInformation -Encoding UTF8

Export AD Computers from Specific OU

We can set target OU scope by using the parameter SearchBase. The following powershell script select all the Windows Server 2008 R2 AD compuers from the Organization Unit 'TestOU' and export it to CSV file.
Import-Module ActiveDirectory
Get-ADComputer -SearchBase "OU=TestOU,DC=TestDomain,DC=Local"`
-Filter 'OperatingSystem -like "*Windows Server 2008 R2*"' -Properties * |
 Select -Property Name,operatingSystem,@{Name="LastLogon";
Expression={[DateTime]::FromFileTime($_.lastLogon).ToString()}} |
# Export AD Computers to CSV file 
Export-CSV "C:\\ADComputers.csv" -NoTypeInformation -Encoding UTF8

CSV output of AD Computers Report:

Powershell - Export Active Directory Computers to CSV
Read More...

Powershell - Export Inactive AD Users to CSV

One of the most common task in Active Directory is finding inactive AD users on regular basis to disable or delete staled accounts from Active Directory. In powershell, we can use the cmdlet Get-ADUser to get set of user details. We can use either SQL like filter or LDAP filter with lastLogonTimeStamp attribute to get inactive users.

Find and List Inactive AD Users

We can find all inactive AD users for the specified time period by comparing user's lastlogontimestamp value. The below powershell script find and list AD users who are not logged in last 90 days, it also filters disabled users and get only enabled inactive users.
Import-Module ActiveDirectory
# No of days - Get AD users who are no logged in last 90 days
$DaysInactive = 90
$time = (Get-Date).Adddays(-($DaysInactive))
Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties *| 

Select-Object Name, @{Name="LastLogonTimeStamp";
Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString()}}

Export Inactive AD Users to CSV file

We can generate and export Active Directory inactive users report to CSV file using Powershell cmdlets Get-ADUser and Export-CSV. You can add more attributes in Select-Object field to export more AD attributes of inactive users.
Import-Module ActiveDirectory
# No of days - Get AD users who are no logged in last 90 days
$DaysInactive = 90  
$time = (Get-Date).Adddays(-($DaysInactive)) 
Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties * | 

Select-Object Name,Mail,DistinguishedName, @{Name="LastLogonTimeStamp"; 
Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString()}} |
# Export Inactive Users Report to CSV file 
Export-CSV "C:\\InactiveADUsers.csv" -NoTypeInformation -Encoding UTF8

Export Inactive AD Users from Specific OU

We can set target OU scope by using the parameter SearchBase. The following powershell script select all the Inactive AD users from the Organization Unit 'TestOU' and export it to CSV file.
Import-Module ActiveDirectory
# No of days - Get AD users who are no logged in last 90 days
$DaysInactive = 90  
$time = (Get-Date).Adddays(-($DaysInactive)) 
Get-ADUser -SearchBase "OU=TestOU,DC=TestDomain,DC=Local"`
-Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties * | 

Select-Object Name,Mail,DistinguishedName, @{Name="LastLogonTimeStamp"; 
Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString()}} | 
Export-CSV "C:\\InactiveADUsers.csv" -NoTypeInformation -Encoding UTF8

CSV output of Inactive AD Users Report

Powershell - Export Inactive Active Directory Users to CSV
Read More...

Tuesday, 19 May 2015

How to disable IE Enhanced Security in Windows Server 2012

When IE ESC is enabled, you will get popups all the time and you are asked to add every new url to the Internet Explorer trusted sites zone. So, in development server or test server, it is desirable to disable it or turned off. This is just a quick guide to disable or turn off IE Enhanced Security in Windows Server 2012.

Steps to disable/turn off IE Enhanced Security in Windows Server 2012

1. Start the Server Manager from Windows 2012 desktop.

How to disable IE Enhanced Security in Windows Server 2012

2. Select Local Server which shows the settings of the server you are currently on and the one that needs IE ESC turned off.

3. In right side of the Server Manager, you can find the IE Enhanced Security Configuration Setting. (The default value is On).

How to disable IE Enhanced Security in Windows Server 2012

4. Click on the link On and turn off/disable IE Enhanced Security for Users and Administrators and click Ok.
How to turn off IE Enhanced Security in Windows Server 2012

Read More...

Stop Server Manager on Startup for All Users

The Server Manager wizard provides information of installed roles and features. This Server Manager wizard will be automatically launched at logon. You might not need Server Manager to automatically be displayed after each logon, you can disable this behavior by setting the option "Do not show me this console at logon" in Server Manager itself. If you are working with Active Directory domain service, you might need to turn off automatic start Server Manger for multiple users, you can achieve this need by setting the option "Do not show me this console at logon" through Group Policy.

Method 1: Stop by the option "Do not show me this console at logon"

You can easily stop the automatic launch of Server Manger at logon by checking the option "Do not show me this console at logon" and close the wizard.

disable server manager startup

Method 2: Stop Server Manager on Startup for All Users via GPO

- Open Group Policy Management Console by running the command gpmc.msc.

- Create new GPO and link it the the appropriate Organizational Unit (OU).

- Edit the policy to configure the settings "Do not display Server Manager automatically at logon".

- Expand the root Computer Configuration and go to the following node:
  Computer Configuration\Administrative Templates\System\Server Manager

- In right-hand side, select and right-click on the policy "Do not display Server Manager automatically at logon" ,click Edit.

disable server manager startup for all users

- Check the option Enable and click Apply button.

disable server manager startup for all users

- Now, close the Group Policy Editor snap-in.

- Update GPO by running the command gpupdate/force.

disable automatic launch of server manager on startup

Read More...

Thursday, 14 May 2015

Import-Module : There were errors in loading the format data file: Microsoft.PowerShell

I have tried to connect Office 365 through powershell to get mailbox size report.
$cred = Get-Credential 
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $cred -Authentication Basic -AllowRedirection 
$ImportCmd = Import-PSSession $Session 
After I have typed my credentials loading the modules and got the error message "Import-Module : There were errors in loading the format data file:Microsoft.PowerShell".
WARNING: Your connection has been redirected to the following URI:
"https://pod51053psh.outlook.com/powershell-liveid?PSVersion=2.0 "
PS C:\Users\kevin> $ImportCmd = Import-PSSession $Session
WARNING: Proxy creation has been skipped for the following command: 'TabExpansion', because it would shadow an existing
 local command.  Use the AllowClobber parameter if you want to shadow existing local commands.
Import-Module : There were errors in loading the format data file:
Microsoft.PowerShell, , C:\Users\kevin\AppData\Local\Temp\tmp_a97a2eff-f881-4737-82d4-4c6b63d658f6_nygoxstp.fjf\tmp_a97
a2eff-f881-4737-82d4-4c6b63d658f6_nygoxstp.fjf.format.ps1xml : File skipped because of the following validation excepti
on: File C:\Users\kevin\AppData\Local\Temp\tmp_a97a2eff-f881-4737-82d4-4c6b63d658f6_nygoxstp.fjf\tmp_a97a2eff-f881-4737
-82d4-4c6b63d658f6_nygoxstp.fjf.format.ps1xml cannot be loaded because the execution of scripts is disabled on this sys
tem. Please see "get-help about_signing" for more details..
At line:3 char:30
+                 Import-Module <<<<  -Name $name -Alias * -Function * -Prefix $prefix -DisableNameChecking:$disableNam
eChecking -PassThru -ArgumentList @($session)
    + CategoryInfo          : InvalidOperation: (:) [Import-Module], RuntimeException
    + FullyQualifiedErrorId : FormatXmlUpateException,Microsoft.PowerShell.Commands.ImportModuleCommand

Solution

In error message, you can see the message "File skipped because of the following validation exception: cannot be loaded because the execution of scripts is disabled on this system". So, to fix this issue we need to configure poweshell script ExecutionPolicy as RemoteSigned to allow all scripts and configuration files downloaded from the Internet be signed by a trusted publisher.

    - Open Powershell console with elevated privilege (Run as administrator).
    - Run below command to set ExecutionPolicy as RemoteSigned.
Set-ExecutionPolicy RemoteSigned -Force
Now, you can able connect Office 365 through powershell smoothly.


Read More...

C# - Sync AD Password with MS Office 365

We can change or reset Office 365 password through Microsoft 365 Online Service using powershell with C#. You need to install following components to sync Active Directory password with Office 365.

- Download and Install Microsoft Online Services Sign-In Assistant for IT Professionals RTW
- Download and Install Azure Active Directory Module for Windows PowerShell

In C# project, we need to add reference System.Management.Automation.dll to run powerShell commands.
using System.Management.Automation;
-----------------------------------
private static void ResetOffice365Password()
{
    try
    {
        string adminUser = "admin@office365domain.com";
        string adminPwd = "myadminpwd";

        //User account to sync password with office 365
        string userPrincipalName = "morgan@office365domain";
        string newPwd = "userpwd";

        string scriptText = "Import-Module MSOnline;\r\n" +
        "$Username=" + "\"" + adminUser + "\"" + ";\r\n" +
        "$Password=ConvertTo-SecureString -AsPlainText \"" + adminPwd + "\" -Force;\r\n" +
        "$Livecred = New-Object System.Management.Automation.PSCredential $Username, $Password;\r\n" +
        "Connect-MsolService -Credential $Livecred;\r\n" +
        "Set-MsolUserPassword -UserPrincipalName " + userPrincipalName + " -NewPassword \"" + newPwd + "\" -ForceChangePassword $false -WarningVariable warningVar -OutVariable outVar | Out-Null;\r\n" +
        "If ( !$warningVar -and !$Error ) { " +
        " If ( $outVar -eq \"" + newPwd + "\") { Echo OK; } Else { Echo Failed; } " +
        "} Else {" +
        " If ( $Error ) { Echo ERROR; $Error | fl Message; } Else { Echo WARNING; $warningVar | fl Message; }" +
        "}";

        PowerShell psExec = PowerShell.Create();
        psExec.AddScript(scriptText);
        psExec.AddCommand("Out-String");

        Collection<PSObject> results = psExec.Invoke();
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in results)
        {
            stringBuilder.AppendLine(obj.ToString());
        }
        Console.WriteLine(stringBuilder.ToString());
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception.Message);
    }
    Console.ReadKey();
}
Read More...

Sunday, 10 May 2015

Powershell - Create Bulk AD Users from CSV

Creating Bulk Active Directory Users in AD is one of important task for every Administrator either for testing or for set of actual new employees. Normally you can create new AD user using ADUC console. But it is time consuming job if you want create multiple ad users. To overcome this hurdle, every administrator should rely on any of a script technology like VBScript and Powershell. In this article. I am going write and explain Powershell Script to Create Bulk Active Directory Users from CSV.

Create Bulk AD Users from CSV file with OtherAttributes

   1. Consider the CSV file NewADUsers.csv which contains set of New AD Users to create with required Active Directory attributes (i.e. Name, samAccountName and ParentOU).


   Note: the value of ParentOU should be enclosed with double quote ("). like "OU=TestOU,DC=TestDomain,DC=Local" since it has the special character comma (,). because in csv file the comma (,) is the key character to split column headers. (Ex file: Download NewADUsers.csv).

   2. Copy the below Powershell script and paste in Notepad file.
   3. Change the NewADUsers.csv file path with your own csv file path.
   4. Change the domain name TestDomain.local into your own domain name.
   5. Add more other ad attributes with the parameter -OtherAttributes.
   6. SaveAs the Notepad file with the extension .ps1 like Create-Bulk-AD-Users-CSV.ps1

Click to download Powershell script as file Create-Bulk-AD-Users-CSV.ps1
Import-Module ActiveDirectory
Import-Csv "C:\Scripts\NewADUsers.csv" | ForEach-Object {
Write-Host "Creating AD user:" $_.Name
New-ADUser -Name $_.Name `
 -Path $_."ParentOU" `
 -SamAccountName  $_."samAccountName" `
 -UserPrincipalName $_."userPrinicpalName" `
 -OtherAttributes @{title=$_."JobTitle";mail=$_."userPrinicpalName";proxyaddresses=$_."proxyAddresses"}`
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true
Add-ADGroupMember "Remote Desktop Users" $_."samAccountName";
}
Write-Host "---------------------------------"
Write-Host "Bulk AD Users created successfully from CSV file."
Write-Host "---------------------------------"
   7. Now run the Create-Bulk-AD-Users-CSV.ps1 file in Powershell to create Bulk Active Directory users from CSV file.

Powershell - Create Bulk AD Users from CSV

Note: I have placed the script file in the location C:\Scripts, if you placed in any other location, you can change the file path (like "C:\Downloads\Create-Bulk-AD-Users-CSV.ps1").

   8. Now you can view the newly Created Active Directory Users though ADUC console.

Powershell Script to Create Bulk AD Users from CSV file
Read More...

Saturday, 9 May 2015

Stop the automatic launch of Initial Configuration Tasks at logon

The Initial Configuration Tasks ICT wizard provides information of computer settings, updates and customized settings. This configuration tasks wizard will be automatically launched at logon, you can disable or stop the automatic launch of Initial Configuration Tasks Extension at logon if its no longer required.

Method 1: Stop by the option "Do not show this windows at logon"

You can easily stop the automatic launch of Initial Configuration Tasks Extension at logon by checking the option "Do not show this windows at logon" and Close the wizard.

Stop the automatic launch of Initial Configuration Tasks at logon

Method 2: Disable through Registry Setting

You can also disable the automatic launch of Initial Configuration Tasks Extension at logon by setting value 1 in the registry HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ServerManager\Oobe\DoNotOpenInitialConfigurationTasksAtLogon.
KEY: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ServerManager\Oobe
Value Name: DoNotOpenInitialConfigurationTasksAtLogon
Value Data: 1=enabled, 0=disabled

How to re-launch Initial Configuration Tasks ICT wizard

You could launch ICT wizard anytime by running the command "oobe" in Run Window or you can type "oobe" in search box and hit enter.
w to re-launch Initial Configuration Tasks ICT wizard

Read More...

Monday, 4 May 2015

Exchange Server 2013 - ECP - Topology Provider coundn't find the Microsoft Exchange Active Directory Topology service on end point 'TopologyClientTcpEndpoint

Problem:

I have got the Microsoft Exchange Active Directory Topology service error with the error message "Topology Provider coundn't find the Microsoft Exchange Active Directory Topology service on end point 'TopologyClientTcpEndpoint" when I tried to access Exchange Admin Center through IE browser.
Server Error in '/ecp' Application.

Topology Provider coundn't find the Microsoft Exchange Active Directory Topology service on end point 'TopologyClientTcpEndpoint (localhost)'. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the 
error and where it originated in the code. 

 Exception Details: Microsoft.Exchange.Data.Directory.ADTopologyEndpointNotFoundException: Topology Provider coundn't find the Microsoft Exchange Active 
Directory Topology service on end point 'TopologyClientTcpEndpoint (localhost)'.

Source Error: 

 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be 
identified using the exception stack trace below.  

Fix/Solution:

This issue will occur when the Microsoft Active Directory Topology Service is stopped or in failed state.
- Go to Service Manager console (services.msc).
- Start the Microsoft Exchange Active Directory Topology Service.
- Reopen the Exchange Admin Center page.

Topology Provider coundn't find the Microsoft Exchange Active Directory Topology service on end point 'TopologyClientTcpEndpoint

Read More...

Exchange Server 2013 -Topology Provider coundn't find the Microsoft Exchange Active Directory Topology service on end point 'TopologyClientTcpEndpoint

Problem:

I have got the Microsoft Exchange Active Directory Topology service error with the error message "Topology Provider coundn't find the Microsoft Exchange Active Directory Topology service on end point 'TopologyClientTcpEndpoint" when I tried to access Outlook Web Application through IE browser.
Server Error in '/owa' Application.

Topology Provider coundn't find the Microsoft Exchange Active Directory Topology service on end point 'TopologyClientTcpEndpoint (localhost)'. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the 
error and where it originated in the code. 

 Exception Details: Microsoft.Exchange.Data.Directory.ADTopologyEndpointNotFoundException: Topology Provider coundn't find the Microsoft Exchange Active 
Directory Topology service on end point 'TopologyClientTcpEndpoint (localhost)'.

Source Error: 

 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be 
identified using the exception stack trace below.  

Fix/Solution:

This issue will occur when the Microsoft Active Directory Topology Service is stopped or in failed state.
 - Go to Service Manager console (services.msc).
 - Start the Microsoft Exchange Active Directory Topology Service.
 - Reopen the Outlook Web Application (OWA) page.

Topology Provider coundn't find the Microsoft Exchange Active Directory Topology service on end point 'TopologyClientTcpEndpoint


Read More...

Thursday, 16 April 2015

PowerShell - Testing if a String is NULL or EMPTY

Checking if a string is NULL or EMPTY is very common requirement in Powershell script. If we do not checked that we will get some unwanted results when we try to perform some operation on that string variable which is empty or null.

The following method is used to check if a string is NULL or empty.
$mystring ='hello'
if($mystring) {            
    Write-Host "Your string is not EMPTY"            
} else {            
    Write-Host "Your string is EMPTY or NULL"            
}
We can also use the .NET Class “System.String” to check null or empty string. It has a method IsNullOrEmpty() which returns true if the passed string is null or empty. Check the below example.
$mystring ='hello'
IF([string]::IsNullOrEmpty($mystring)) {            
    Write-Host "Your string is EMPTY or NULL"            
} else {            
    Write-Host "Your string is not EMPTY"            
}
We can also use the method IsNullOrWhiteSpace() from “System.String” class to detect a given string is NULL or EMPTY and whether it has WHITESPACE.
$mystring = " "            
IF([string]::IsNullOrWhiteSpace($mystring)) {            
    Write-Host "Your string is NULL or EMPTY or it has WHITESPACE"            
} else {            
    Write-Host "Your string is not EMPTY"            
}     
Note: The method IsNullOrWhiteSpace() is available only from .NET Frmaework 4.0, so, this method do not work in Powershell 2.0 and it will work only from Powershell 3.0.

You will get below error, when you run this method in Powershell 2.0.

IsNullOrWhitespace : Method invocation failed because [System.String] doesn’t contain a method named ‘IsNullOrWhiteSpace’
Read More...

Friday, 10 April 2015

Powershell - Get AD Users Group Membership

In this article, I am going write PowerShell script to find and list Active Directory Groups of an AD user is a Member Of using the PowerShell's cmdlet Get-ADPrincipalGroupMembership.

Powershell command to list AD User Group Membership:

Get-ADPrincipalGroupMembership [-Identity]
The Identity parameter specifies the user, computer, or group object that you want to determine group membership for. You can identify a user object by its distinguished name (DN), GUID, SID or SAMAccountName.

List Group Names of an AD User is Member Of

The below powershell command find and list all Active Directory Groups which contains the user account Morgan as member.
Import-Module ActiveDirectory
Get-ADPrincipalGroupMembership Morgan |
 Select Name,DistinguishedName

Export set of AD Users Group Membership to CSV

The below PowerShell script get AD users from the OU TestOU and enumerate membership of all AD Users. It writes the group membership output into csv file using the powershell cmdlet Add-Content.
Import-Module ActiveDirectory
$CSV_File_Path = "C:\ADGroupMembership.csv"
$Header = "UserName,Groups"
 
If (Test-Path $CSV_File_Path){
 Remove-Item $CSV_File_Path
}
 
Add-Content -Value $Header -Path $CSV_File_Path 

$users = Get-ADUser -SearchBase "OU=TestOU,DC=TestDomain,DC=Com" -Filter * 

foreach($user in $users){
  $groupNames = ""
  $groups = Get-ADPrincipalGroupMembership $user.SamAccountName 
  foreach($group in $groups){
    if($groupNames -eq "")
     {
       $groupNames = $group.name
     }
    else
     {
       $groupNames = $groupNames +","+$group.name
     }
  }

  $info=$user.SamAccountName+','+'"'+$groupNames+'"'
 Add-Content -Value  $info -Path $CSV_File_Path 
}

CSV Output of AD Users Group Membership:

Find and Export AD Users Group Membership to CSV
Read More...

C# - Get PowerShell Output from MultiValuedProperty Value

In C#, you can execute powershell commands and get output in separate runspace. The following C# example returns the exchange server's mailbox audit report. The audit setting fields (AuditDelegate,AuditAdmin,AuditOwner) are multi-valued property field, so we can not read value directly from this field. The datatype of this field is "Deserialized.Microsoft.Exchange.Data.Directory.ADMultiValuedProperty`1[[Microsoft.Exchange.Data.Directory.MailboxAuditOperations, Microsoft.Exchange.Data.Directory, Version=14.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]". So, here, I have written the C# code to extract value from ADMultiValuedProperty field.
public static void GetMailBoxAuditReport()
{
    string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
    var secured = new SecureString();
    foreach (char letter in "MyPassword")
    {
        secured.AppendChar(letter);
    }
    secured.MakeReadOnly();
    var credential = new PSCredential(@"MyExchDomain\Administrator", secured);
    var connectionInfo = new WSManConnectionInfo(false, "MyExchServer", 5985, "/wsman", shellUri, credential);
    Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript("Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010");
    pipeline.Commands.AddScript("Get-Mailbox | Select Name, AuditEnabled, AuditLogAgeLimit,AuditAdmin,AuditDelegate,AuditOwner");
    Collection<PSObject> results = pipeline.Invoke();
    if (results.Count > 0)
    {
        foreach (PSObject psObject in results)
        {
            List<string> output = new List<string>();
            foreach (PSPropertyInfo psInfo in psObject.Properties)
            {
                if (psInfo.Value != null)
                {
                    string dataType = psInfo.TypeNameOfValue;
                    if (dataType.Contains("ADMultiValuedProperty"))
                    {
                        string multiValueOutput = string.Empty;
                        PSObject childObj = (PSObject)psInfo.Value;
                        foreach (PSObject info in (ArrayList)childObj.ImmediateBaseObject)
                        {
                            multiValueOutput += info.ToString() + ";";
                        }
                        output.Add(multiValueOutput);
                    }
                    else if (dataType.Equals("System.String[]"))
                    {
                        string[] childObj = (string[])psInfo.Value;
                        output.Add(string.Join(";", childObj));
                    }
                    else
                    {
                        output.Add(psInfo.Value.ToString());
                    }
                }
            }
            Console.WriteLine(string.Join(";", output.ToArray()));
            Console.WriteLine("----------------------");
        }
    }
}

Read More...

Wednesday, 8 April 2015

PowerShell - Convert Ticks to Date Time and Vise Versa

You can convert Date to Ticks and Ticks to Date Time using the PowerShell Get-Date cmdlet.

Convert Ticks to Date Time

Use the below powershell command to convert ticks to date.
Get-Date 635641048517131910

Wednesday, April 08, 2015 3:47:31 PM
You can also convert ticks to datetime by simple DateTime type casting.
[DateTime]635641048517131910

Wednesday, April 08, 2015 3:47:31 PM

Convert Date Time to Ticks

Use the below powershell command to convert date to ticks.
(Get-Date).ticks

635641051132584348
(Get-Date "04/20/2014").ticks

635335488000000000
Read More...

PowerShell - Convert Large Integer value to Date Time string

If you are working with Active Directory, you should have come across the attributes like LastLogonTimestamp. This LastLogonTimestamp attribute is stored in the Active Directory database as a Large Integer (TimeStamp) value so we need to convert it to a normal date format string to make it readable.

Use the following PowerShell command to Convert Large Integer value to Date Time string

$lastLogonTimestamp = "130724281432636780"
[DateTime]::FromFiletime([Int64]::Parse($lastLogonTimestamp))
PowerShell - Convert Large Integer value to Date Time string
Read More...