Thursday, 31 March 2016

Get AD Computer Description using Powershell

We can find and get the description of Active Directory computers by using the AD powershell cmdlet Get-ADComputer. In this post, I am going to write powershell script samples to get description of AD computers and get list of computer names based on description.

Before proceed, first run the below command to import Active Directory module.
Import-Module ActiveDirectory

Summary:

Get description of all AD computers:

The following command find and list the name and description of all the available computers in Active Directory.
Get-ADComputer -Filter * -Property Name,Description |
 Select -Property Name,Description
You can also export the details to csv file by using the powershell cmdlet Export-CSV.
Get-ADComputer -Filter * -Property Name,DNSHostName,Description |
 Select -Property Name,DNSHostName,Description | 
 Export-CSV "C:\\AllComputers.csv" -NoTypeInformation -Encoding UTF8

Apply filter to get computers by description:

The Get-ADComputer cmdlet supports SQL like filter, we can easily use this filter to get only specific set of AD computers. The below script select all the computers whose description contains the text 'SVR'.
Get-ADComputer -Filter 'Description -like "*SVR*"' -Property Name,Description |
 Select -Property Name,Description

Apply LDAP Filter to get set of AD computers:

If your are familiar with LDAP filter, instead of normal filter, you can also use LDAP filter with to select particular set of AD computers.
Get-ADComputer -LDAPFilter '(Description=*SVR*)'  -Property Name,Description |
 Select -Property Name,Description

Get description of computers from specific OU:

We can set target OU scope by using the parameter SearchBase to select computers from specific OU. The following powershell script select all computers from the Organization Unit 'TestOU' and export it to CSV file.
Get-ADComputer -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=com"`
 -Property Name,DNSHostName,Description | `
 Select -Property Name,DNSHostName,Description | `
Export-CSV "C:\\TestOUComputers.csv" -NoTypeInformation -Encoding UTF8

Get description for list of computers:

The below powershell script gets description for list of AD computers. First create the text file computers.txt which includes one computer name in each line. You will get the name and description in the csv file ADComputers.csv.
Get-Content C:\computers.txt | Get-ADComputer -Property Name,Description |`
 Select -Property Name,Description |`
 Export-CSV C:\ADComputers.csv -NoTypeInformation -Encoding UTF8

Wednesday, 30 March 2016

Find AD Account Lockout Policy using Powershell

In this article, I am going to explain about how to find and read the settings of account lockout policy in current Active Directory domain by using Powershell.

Summary:

# Method 1 : Get-ADDefaultDomainPasswordPolicy

We can use the Active Directory powershell cmdet Get-ADDefaultDomainPasswordPolicy to gets the account lockout policy settings for an Active Directory domain. Before proceed, run the below command to import the Active Directory module.
Import-Module ActiveDirectory
The below command get the default account lockout policy from current logged on user domain.
Get-ADDefaultDomainPasswordPolicy | Select LockoutDuration,LockoutObservationWindow,`
LockoutThreshold | FL
This command returns the following results (LockoutDuration,LockoutObservationWindow and LockoutThreshold).
PS C:\> Get-ADDefaultDomainPasswordPolicy | Select LockoutDuration,LockoutObservationWindow,`
LockoutThreshold | FL

LockoutDuration             : 00:30:00
LockoutObservationWindow    : 00:30:00
LockoutThreshold            : 6

# Method 2 : Get-ADObject

We can also use Get-ADObject to retrieve account lockout policy associated properties from the domain naming context (defaultNamingContext).
$RootDSE = Get-ADRootDSE
$AccountPolicy = Get-ADObject $RootDSE.defaultNamingContext -Property lockoutDuration,`
                 lockoutObservationWindow, lockoutThreshold 
$AccountPolicy | Select Name,`
  @{n="Lockout duration";e={"$($_.lockoutDuration / -600000000) minutes"}},`
  @{n="Reset lockout counter";e={"$($_.lockoutObservationWindow / -600000000) minutes"}},`
  @{n="Lockout Threshold";e={"$($_.lockoutThreshold) invalid logon attempts"}} | FL
The above command returns the following results (Lockout duration, Reset lockout counter and Lockout Threshold).
Name                  : contoso
Lockout duration      : 30 minutes
Reset lockout counter : 30 minutes
Lockout Threshold     : 6 invalid logon attempts

# Method 3 : net accounts

We can also use the following net command to look at the account lockout policy details.
net accounts
This command returns the following results (Lockout duration (minutes), Lockout observation window (minutes) and Lockout threshold).
PS C:\> net accounts

Force user logoff how long after time expires?:       Never
Minimum password age (days):                          1
Maximum password age (days):                          42
Minimum password length:                              7
Length of password history maintained:                24
Lockout threshold:                                    6
Lockout duration (minutes):                           30
Lockout observation window (minutes):                 30
Computer role:                                        PRIMARY
The command completed successfully.

Find the settings of AD Domain Password Policy using Powershell

In this post, I am going to write different methods to find and read the settings of current Active Directory Domain Password Policy using Powershell.

Summary:

# Method 1 : Get-ADDefaultDomainPasswordPolicy

We can use the AD powershell cmdet Get-ADDefaultDomainPasswordPolicy to gets the default password policy for an Active Directory domain. Before proceed, import the Active Directory module first by running below command.
Import-Module ActiveDirectory
The below command get the default domain password policy from current logged on user domain.
Get-ADDefaultDomainPasswordPolicy
This command get the default domain password policy from a given domain.
Get-ADDefaultDomainPasswordPolicy -Identity contoso.com
This command returns the following results (ComplexityEnabled, MaxPasswordAge, MinPasswordAge and MinPasswordLength).
PS C:\> Get-ADDefaultDomainPasswordPolicy

ComplexityEnabled           : True
DistinguishedName           : DC=testdomain,DC=com
LockoutDuration             : 00:30:00
LockoutObservationWindow    : 00:30:00
LockoutThreshold            : 0
MaxPasswordAge              : 42.00:00:00
MinPasswordAge              : 1.00:00:00
MinPasswordLength           : 7
objectClass                 : {domainDNS}
objectGuid                  : d43f2f55-c381-4fa7-871d-4c990434259c
PasswordHistoryCount        : 24
ReversibleEncryptionEnabled : False

# Method 2 : Get-ADObject

We can also use Get-ADObject to retrieve password policy associated properties from the domain naming context (defaultNamingContext)
$RootDSE = Get-ADRootDSE
$PasswordPolicy = Get-ADObject $RootDSE.defaultNamingContext -Property minPwdAge, maxPwdAge,`
                  minPwdLength, pwdHistoryLength, pwdProperties 

$PasswordPolicy | Select Name, @{n="Min Password Age";e={"$($_.minPwdAge/-864000000000) days"}},`
@{n="Max Password Age";e={"$($_.maxPwdAge / -864000000000) days"}},`
@{n="Max Password Length";e={"$($_.minPwdLength) characters"}},`
@{n="Pwd History Length";e={$_.pwdHistoryLength}},`
@{n="Password Complexity";e={Switch ($_.pwdProperties) {
         0 {"Passwords can be simple and the administrator account cannot be locked out"}
         1 {"Passwords must be complex and the administrator account cannot be locked out"}
         8 {"Passwords can be simple, and the administrator account can be locked out"}
         9 {"Passwords must be complex, and the administrator account can be locked out"}
         Default {$_.pwdProperties}}}}
The above command returns the following results (Min Password Age, Max Password Age, Max Password Length, Pwd History Length and Password Complexity).
Name             : contoso
Min Password Age    : 1 days
Max Password Age    : 42 days
Max Password Length : 7 characters
Pwd History Length  : 24
Password Complexity : Passwords must be complex and the administrator account cannot be locked out

# Method 3 : net accounts

We can also use the following net command to look at the password policy details.
net accounts
This command returns the following results (minimum password length, maximum password age and minimum password length).
PS C:\> net accounts

Force user logoff how long after time expires?:       Never
Minimum password age (days):                          1
Maximum password age (days):                          42
Minimum password length:                              7
Length of password history maintained:                24
Lockout threshold:                                    Never
Lockout duration (minutes):                           30
Lockout observation window (minutes):                 30
Computer role:                                        PRIMARY
The command completed successfully.

Tuesday, 29 March 2016

How to enable external sharing in SharePoint Online using Powershell

SharePoint online has feature called External Sharing to share your content with external vendors, clients or external customers in collaborative environment. Refer this article to know more about external sharing : Manage external sharing for your SharePoint Online environment

We can use the SharePoint online powershell cmdlet Set-SPOSite to enable or disable external sharing at site collection level by using the parameter -SharingCapability.

Enable external sharing for site collection:

The following command enable external sharing for the given site collection. It allows only external users who have to sign in as authenticated users.
$siteCollectionURL = "https://mytenant.sharepoint.com/sites/contoso"
Set-SPOSite -Identity $siteCollectionURL -SharingCapability ExternalUserSharingOnly
The following command enable external sharing to allow for both authenticated users and anonymous guest links.
$siteCollectionURL = "https://mytenant.sharepoint.com/sites/contoso"
Set-SPOSite -Identity $siteCollectionURL -SharingCapability ExternalUserAndGuestSharing

Disable external sharing for a site collection:

The following command disable external sharing for the given site collection.
$siteCollectionURL = "https://mytenant.sharepoint.com/sites/contoso"
Set-SPOSite -Identity $siteCollectionURL -SharingCapability Disabled

Check external sharing status for a site collection:

The following powershell command check the status of external sharing for the given site collection.
$siteCollectionURL = "https://mytenant.sharepoint.com/sites/contoso"
$site = Get-SPOSite -Identity $siteCollectionURL
if($site.SharingCapability -eq "Disabled")
{
     Write-Host "External sharing is disabled for"$site.URL -ForegroundColor Green
}
else
{
     Write-Host "External sharing is enabled" -ForegroundColor Yellow
}

Generate random password for AD using PowerShell

When we create new bulk of AD users from CSV or from any other system, first, we need to create strong random password to provide password for every new AD user. In Powershell, we don't have any built-in cmdlet to generate a random AD password string. However we can use the cmdlet Get-Random to select random number or random character from the given character array.

The following powershell command creates a 12 -character new password. But the password generated by this method may not accepted by Active Directory in some cases.
$chars = "abcdefghijkmnopqrstuvwxyzABCEFGHJKLMNPQRSTUVWXYZ23456789!#%&?".ToCharArray()
$newPassword=""
1..12 | ForEach {  $newPassword += $chars | Get-Random }
Write-Host $newPassword -ForegroundColor 'Yellow'
The problem with the above method is that we can not guarantee that the new password will be accepted by Active Directory that has strong password policy since it could return a password containing only lowercase letters a-z or only uppercase letters A-Z. To overcome this problem, we need to write a custom function to generate a strong random password that will be complex enough for Active Directory.

The function to create strong password is already written by Simon Wahlin. You can directly download the script from technet gallery: https://gallery.technet.microsoft.com/Generate-a-random-and-5c879ed5

The function can be run in two ways, either using the parameter -PasswordLength to set a fixed password length or using the parameters -MinPasswordLength and -MaxPasswordLength to use a random length.

Both ways takes the parameters -Count and -InputStrings. -Count specifies how many passwords to generate and -InputStrings specifies a list of strings defining which chars to use for password generation. Each generated password will contain atleast one char from each string (as long as PasswordLength => number of strings).

------- EXAMPLE 1 -------

C:\PS> New-SWRandomPassword
DUo&S7XJh
    
Will generate one password with a length between 8  and 12 chars.

------- EXAMPLE 2 -------

 C:\PS> New-SWRandomPassword -MinPasswordLength 8 -MaxPasswordLength 14
7d&5cnaB

Will generate a password with a length between 8  and 14 chars.

------- EXAMPLE 3 -------

C:\PS> New-SWRandomPassword -InputStrings abc, ABC, 123 -PasswordLength 4
3ABa
    
Generates a password with a length of 4 containing atleast one char from each InputString

How to generate random password using PowerShell

When we creating new bulk of users in any system, we need to create random password to provide unique password for every user. In Powershell, there is no cmdlet to create a random password string. However we can use many custom methods to generate random string.

# Method 1: (Using System.Random object)

We can use the .NET class object System.Random to extract values in the range of 33-126 that are the characters from the ASCII table. The following powershell code creates a 10 -character new password:
$randomObj = New-Object System.Random
$newPassword=""
1..10 | ForEach { $newPassword = $newPassword + [char]$randomObj.next(33,126) }
Write-Host $newPassword -ForegroundColor 'Yellow'

# Method 2: (Get-Random cmdlet)

We can also use the cmdlet Get-Random to select random number or random character from the given collection. The following powershell command creates a 10 -character new password. We need to pipe a bunch of chars to Get-Random to get a random character.
$chars = "abcdefghijkmnopqrstuvwxyzABCEFGHJKLMNPQRSTUVWXYZ23456789!#%&?".ToCharArray()
$newPassword=""
1..10 | ForEach {  $newPassword += $chars | Get-Random }
Write-Host $newPassword -ForegroundColor 'Yellow'

# Method 3: (With AD Password Policy)

The problem with above two methods is that we can not guarantee that the password will be accepted by system with strong password policy (i.e. Active Directory). AD system with complex password policy may not accept the above random password since it could return a password containing only lowercase letters a-z. To overcome this problem, we need to write a custom function to generate a random passwords that will be complex enough for Active Directory.

Now, I am not going write any function since this work already nicely done by Simon Wahlin. You can download the script from technet gallery: https://gallery.technet.microsoft.com/Generate-a-random-and-5c879ed5

The function can be run in two ways, either using the parameter -PasswordLength to set a fixed password length or using the parameters -MinPasswordLength and -MaxPasswordLength to use a random length.

Both ways takes the parameters -Count and -InputStrings. -Count specifies how many passwords to generate and -InputStrings specifies a list of strings defining which chars to use for password generation. Each generated password will contain atleast one char from each string (as long as PasswordLength => number of strings).

Thursday, 24 March 2016

Find the size of a subsite within a site collection

In this post, I am going to explain how to find the size of a subsite in a site collection. We don't have any direct powershell command to get the size of sub sites, the Get-SPSite cmdlet returns storage size only for site collection not for sub sites.

We can easily find the size of sub sites in Storage Metrics report under Site Collection Administration section.

1. Connect Site Collection home page.
2. Click Settings (gear-icon) on top-left of the page.
3. Go to Site Collection Administration > Storage Metrics

find subsite size sharepoint

4. Now, you can see the storage reports with sub-sites.

how to find the size of a subsite in sharepoint 2013

Get Site Collection Storage Information using Powershell

In this post, I am going to write powershell script to get storage data (Total Size, Storage Quota and Warning Size) of all site collections in a SharePoint farm. We can use the powershell cmdlet Get-SPSite to get site usage and quota details.

Summary:

Get Storage Info for a given Site Collection

The below command gets the size and storage quota details of a given site collection. The Get-SPSite cmdlet returns the property Usage and includes the property Storage, this is the storage size of the site collection. The get Get-SPSite also returns the property Quota and it includes the properties StorageMaximumLevel and StorageWarningLevel.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$sc = Get-SPSite http://sp01:85
$sc.Usage.Storage
$sc.Quota.StorageMaximumLevel
$sc.Quota.StorageWarningLevel
All these three values are in bytes, we need to manually convert the bytes value into MB or GB for friendly usage.
$sc = Get-SPSite http://sp01:85
$SizeinMB = [System.Math]::Round((($sc.Usage.Storage)/1MB),2) 
$MaxSizeInMB = [System.Math]::Round((($sc.Quota.StorageMaximumLevel)/1MB),2)
$WarningSizeInMB = [System.Math]::Round((($sc.Quota.StorageWarningLevel)/1MB),2)

Get Storage Info of all Site Collections

You can use the following powershell command to get the current size, storage quota and storage warning size details for all the site collections in SharePoint farm. The results are sorted by the site collection's total size in descending order.
Get-SPSite | Select-Object Url,  @{n="SizeInMB";e={(($_.Usage).Storage)/1MB}},
@{n="MaxSizeInMB";e={(($_.Quota).StorageMaximumLevel)/1MB }},
@{n="WarningSizeInMB";e={(($_.Quota).StorageWarningLevel)/1MB }} | 
Sort-Object -Descending -Property "SizeInMB" | FT
You can also export the output into csv file by using the powershell cmdlet Export-CSV.
Get-SPSite | Select-Object Url,  @{n="SizeInMB";e={(($_.Usage).Storage)/1MB}},
@{n="MaxSizeInMB";e={(($_.Quota).StorageMaximumLevel)/1MB }},
@{n="WarningSizeInMB";e={(($_.Quota).StorageWarningLevel)/1MB }} | 
Sort-Object -Descending -Property "SizeInMB" |
Export-CSV "C:\\site-collection-storage-info.csv" -NoTypeInformation -Encoding UTF8

Get Storage data of all Sites in a Web Application

The below powershell command retrieves all the site collections in a given webapplication and get the total size, maximum storage size and warning size of each site collection.
$CustomResult=@() 
$webAppUrl ="http://sp01/"
$SiteCollections =  Get-SPSite -WebApplication $webAppUrl -Limit All #get all site collections
$SiteCollections | ForEach-Object { 
 
     $CustomResult += [PSCustomObject] @{ 
     SiteColUrl = $_.Url 
     SizeinMB = [System.Math]::Round((($_.Usage.Storage)/1MB),2) 
     MaxSizeInMB = [System.Math]::Round((($_.Quota.StorageMaximumLevel)/1MB),2)
     WarningSizeInMB = [System.Math]::Round((($_.Quota.StorageWarningLevel)/1MB),2)     
}}
$CustomResult | Select SiteColUrl,SizeinMB,MaxSizeInMB,WarningSizeInMB

Thursday, 17 March 2016

Set the Storage Limit on a Site Collection using Powershell

We can set storage quota and storage warning quota for a SharePoint site collection by using the powershell cmdlet Set-SPSite with the parameters MaxSize and WarningSize.

Both parameter values are in bytes and work together to set the storage limits on a site collection (MaxSize and WarningSize). The MaxSize parameter can be any integer value but must be greater than or equal to the WarningSize value.

The following command sets the maximum storage size as 10 MB and storage warning size as 8 MB.
Set-SPSite -Identity http://sp01:85  -MaxSize (10 * 1024 * 1024) -WarningSize (8 * 1024 * 1024)
You can use the below command to get the available storage quota and storage warning quota details for all the site collections in SharePoint farm.
Get-SPSite | Select-Object Url,  @{n="Database";e={$_.ContentDatabase.Name}},
@{n="MaxSizeInMB";e={(($_.Quota).StorageMaximumLevel)/1MB }},
@{n="WarningSizeInMB";e={(($_.Quota).StorageWarningLevel)/1MB }} | 
Sort-Object -Descending -Property "MaxSizeInMB"

Get size of all Site Collections using Powershell

In this article, I am going to write Powershell script to get size of all site collections in SharePoint farm and find site collection size in a given web application. We can use the powershell cmdlet Get-SPSite to get site usage detail. The below command gets the size of a given site collection.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$sc = Get-SPSite http://sp01:85
$SizeinMB = [System.Math]::Round((($sc.Usage.Storage)/1MB),2) 
$SizeInGB = [System.Math]::Round((($sc.Usage.Storage)/1GB),2)

Find size of all site collections in SharePoint Farm

The following powershell command find and retrieves the size of all the site collections in SharePoint Farm. This command gets the storage usage in MB instead of bytes and sorted the site collections by size.
Get-SPSite | Select-Object Url, @{n="Database";e={$_.ContentDatabase.Name}},
@{n="SizeInMB";e={$_.Usage.storage/1MB}} | Sort-Object -Descending -Property "SizeInMB"
You can also export the site collection url, database and size details to csv file by using the powershell cmdlet Export-CSV.
Get-SPSite | Select-Object Url, @{n="Database";e={$_.ContentDatabase.Name}},
@{n="SizeInMB";e={$_.Usage.storage/1MB}} | Sort-Object -Descending -Property "SizeInMB" |
Export-CSV "C:\\site-collections-size.csv" -NoTypeInformation -Encoding UTF8

Get size of all site collections in a Web Application

The below powershell command retrieves all the site collections in a given webapplication and get the size of each site collection.
$CustomResult=@() 
$webAppUrl ="http://sp01/"
$SiteCollections =  Get-SPSite -WebApplication $webAppUrl -Limit All # get all site collections
$SiteCollections | ForEach-Object { 
 
     $CustomResult += [PSCustomObject] @{ 
     SiteColUrl = $_.Url 
     Database = $_.ContentDatabase.Name
     SizeinMB = [System.Math]::Round((($_.Usage.Storage)/1MB),2) 
     SizeInGB = [System.Math]::Round((($_.Usage.Storage)/1GB),2)
     }           
}
$CustomResult | Select SiteColUrl,Database,SizeinMB,SizeInGB

Get size of a SharePoint Site Collection using Powershell

In this post, I am going to write Powershell script to find size of a site collection using the powershell cmdlet Get-SPSite. The Get-SPSite cmdlet includes the property Usage, this property in-turn includes another property Storage, this is the actual value of current storage size of a site collection.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$sc = Get-SPSite http://spsvr:90
$sc.Usage.Storage
Use the below script to get size in MB or GB.
$sc = Get-SPSite http://sp01:85
$SizeinMB = [System.Math]::Round((($sc.Usage.Storage)/1MB),2) 
$SizeInGB = [System.Math]::Round((($sc.Usage.Storage)/1GB),2)

Get size of all site collections in SharePoint Farm

The below powershell script find and retrieves the size of all the site collections in SharePoint Farm. This command gets the storage usage in MB instead of bytes and sorted the site collections by size.
Get-SPSite | Select-Object Url, @{n="Database";e={$_.ContentDatabase.Name}},
@{n="SizeInMB";e={$_.Usage.storage/1MB}} | Sort-Object -Descending -Property "SizeInMB"
You can also export the details to csv file.
Get-SPSite | Select-Object Url,
@{n="Database";e={$_.ContentDatabase.Name}}, @{n="SizeInMB";e={$_.Usage.storage/1MB}} |
Export-CSV "C:\\site-collections-size.csv" -NoTypeInformation -Encoding UTF8

Wednesday, 16 March 2016

Get all users in AD group using Powershell

We can get a list of members of an AD group using the Powershell cmdlet Get-ADGroupMember. In this post, I am going to write powershell script to list group members in Active Directory group and export group members details to csv file. Before proceed, run the following command to import Active Directory Module.
Import-Module ActiveDirectory
Run the following command to list members of a given AD Group.
Get-ADGroupMember -Identity "<GroupName>" | Select Name, SamAccountName
The below command lists only users from the Domain Admins group.
Get-ADGroupMember -Identity "Domain Admins" | Where-Object {$_.ObjectClass -eq "User"} |
Select Name, SamAccountName

Export AD group members to csv:

The following Powershell command find and gets a list of users of a given AD group and exports member details to CSV file.
$GroupName = "<GroupName>"
Get-ADGroupMember -Identity $GroupName | Where-Object {$_.ObjectClass -eq "User"} | 
Select Name, SamAccountName |
Export-CSV "C:\\ADGroupMembers.csv" -NoTypeInformation -Encoding UTF8

Export group membership of multiple groups:

You can use the below script, if you want to export group membership of multiple groups. First create the text file groups.txt which includes one group name in each line. You will get the group name in first column and group member in second column in the csv file ad-group-members.csv.
$CustomResult=@() 
$groups = Get-Content "C:\\groups.txt"            
$Groups | ForEach-Object {
$group = $_
Get-ADGroupMember $group | ForEach-Object {
$CustomResult += [PSCustomObject] @{ 
                GroupName = $group
                Member = $_.Name
            }           
  }
}
$CustomResult | Export-CSV "C:\\ad-group-members.csv" -NoTypeInformation -Encoding UTF8

Friday, 11 March 2016

Get all lists in a Sharepoint Site using Powershell

In this article, I am going to write powershell script to find all lists and libraries in a SharePoint site. The following powershell script find and displays all lists from the given SharePoint site. You need to replace your own site url.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$Site = Get-SPSite "http://MySharePointWeb:81/"
# get the all sub sites of site
$SubSites = $Site.AllWebs
$SubSites | ForEach-Object { 
$Site = $_
# get all lists from site
$lists = $Site.Lists | Where-Object { $_.BaseType -eq 'GenericList' }
$lists | ForEach-Object {                 
    New-Object -TypeName PSObject -Property @{
              ListName = $_.Title
              SiteName = $Site.Title
              SiteUrl = $Site.Url
}}}

Get all Document Libraries in a SharePoint site

The below powershell script find and lists all the document libraries from a given sharepoint site. You just need to change the BaseType filter in the above query to get document libraries.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$Site = Get-SPSite "http://MySharePointWeb:81/"
# get the all sub sites of site
$SubSites = $Site.AllWebs
$SubSites | ForEach-Object { 
$Site = $_
# get all document Libraries from site
$lists = $Site.Lists | Where-Object { $_.BaseType -eq 'DocumentLibrary' }
$lists | ForEach-Object {                                     
    New-Object -TypeName PSObject -Property @{
              LibraryName = $_.Title
              SiteName = $Site.Title
              SiteUrl = $Site.Url
}}}

Get all lists in a SharePoint Web Application using Powershell

In this article, I am going to write powershell script to find all lists and libraries in a SharePoint farm server. The following powershell script export all lists from a SharePoint web application to csv file. You need to replace your own web application url.
Add-PSSnapin Microsoft.SharePoint.PowerShell
 
$SPWebApp = Get-SPWebApplication "http://MySharePointWeb:81/" -ErrorAction SilentlyContinue
# get all the site collections
$SiteCollections = $SPwebApp.Sites
$SiteCollections | ForEach-Object { 
# get the all sub sites of site collection
$SubSites = $_.AllWebs
$SubSites | ForEach-Object { 
$Site = $_
# get all lists from site
$lists = $Site.Lists | Where-Object { $_.BaseType -eq 'GenericList' }
$lists | ForEach-Object {                 
    New-Object -TypeName PSObject -Property @{
              ListName = $_.Title
              SiteName = $Site.Title
              SiteUrl = $Site.Url
}}}}| Export-CSV "C:\\All-Lists.csv" -NoTypeInformation -Encoding UTF8

Get all Document Libraries in a SharePoint web application

The below powershell script find and export all the document libraries from a SharePoint web application to csv file. You just need to change the BaseType filter in the above query to get document libraries.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$SPWebApp = Get-SPWebApplication "http://MySharePointWeb:81/"
# get all the site collections  
$SiteCollections = $SPwebApp.Sites
$SiteCollections | ForEach-Object { 
# get the all sub sites of site collection
$SubSites = $_.AllWebs
$SubSites | ForEach-Object { 
$Site = $_
 # get all document Libraries from site
$lists = $Site.Lists | Where-Object { $_.BaseType -eq 'DocumentLibrary' }
$lists | ForEach-Object {                                     
    New-Object -TypeName PSObject -Property @{
              LibraryName = $_.Title
              SiteName = $Site.Title
              SiteUrl = $Site.Url
}}}}| Export-CSV "C:\\All-Libraries.csv" -NoTypeInformation -Encoding UTF8

Thursday, 10 March 2016

Read Message Tracking Logs from Exchange Online using Powershell

In this article, I am going explain how to retrieve message tracking logs from Office 365 and export message traffic logs to csv file. We can use the Exchange Online powershell cmdlet Get-MessageTrace to get logs. Exchange Online stores logs for 30 days, but if you need to store them for longer, you can download logs and store it in your own database.

Before proceed, first connect a PowerShell session to Exchange Online by using the following commands, enter Office 365 admin credentials when prompted:
$365Logon = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Logon -Authentication Basic -AllowRedirection
Import-PSSession $Session
After connecting Exchange Online service, run the following command to retrieve message trace logs for last 7 days:
$dateStart = ([system.DateTime]::Now.AddDays(-7))
$dateEnd = ([system.DateTime]::Now) 
Get-MessageTrace -StartDate $dateStart -EndDate $dateEnd | Select Received,SenderAddress,
RecipientAddress,Subject,Status | FT

Export message trace logs to CSV:

You can export the message tracking logs to csv file by using below command:
$dateStart = ([system.DateTime]::Now.AddDays(-7))
$dateEnd = ([system.DateTime]::Now) 
Get-MessageTrace -StartDate $dateStart -EndDate $dateEnd | Select Received,SenderAddress,
RecipientAddress,Subject,Status,Size | Export-Csv C:\MessageTraceLogs.csv -NoTypeInformation

Filter message trace Logs:

You can apply filter by using the options available in Get-MessageTrace cmdlet. The following command retrieves message trace logs sent by mike@mts.contoso.com between Mar 1, 2016 and Mar 10, 2016.
Get-MessageTrace -SenderAddress mike@mts.contoso.com -StartDate 03/01/2016 -EndDate 03/10/2016
The following command retrieves only successfully Delivered messages for last 7 days:
Get-MessageTrace -Status Delivered -StartDate 03/01/2016 -EndDate 03/10/2016
You can also filter logs by using Where-Object cmdlet after getting logs from Get-MessageTrace. The following command retrieves logs that successfully delivered and sent by mike@mts.contoso.com
Get-MessageTrace -StartDate 03/01/2016 -EndDate 03/10/2016 |
Where-Object {$_.SenderAddress -eq 'mike@mts.contoso.com' -and $_.Status -eq 'Delivered' }

Page Size (Result Size):

By default the Get-MessageTrace cmdlet returns only 1000 logs, you can control this size by using the parameter PageSize. The PageSize parameter specifies the maximum number of entries per page. Valid input for this parameter is an integer between 1 and 5000.
Get-MessageTrace -StartDate 03/01/2016 -EndDate 03/10/2016 -PageSize 5000
The Get-MessageTrace cmdlet will returns only maximum of 5000 logs. You have to restrict results by using the options available in the cmdlet ( like Status,SenderAddress.StartDate,etc... ) to get more specific logs.

If you have large number of records (over 5000) to fetch in last 30 days, you have to read logs page by page and store results in csv. You can achieve this by downloading this technet gallery script: https://gallery.technet.microsoft.com/scriptcenter/Export-Mail-logs-to-CSV-d5b6c2d6

Wednesday, 9 March 2016

Connect-SPOService : Method not found: 'Boolean System.Net.WebResponse.get_SupportsHeaders()'.

I have successfully installed the SharePoint Online Management Shell in my Windows 2008 R2 Server machine and successfully loaded the SharePoint Online Powershell module by using below command.
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
But when I try to connect Sharepoint Online service by using the command Connect-SPOService, I am getting the error Connect-SPOService : Method not found: 'Boolean System.Net.WebResponse.get_SupportsHeaders()'.
Connect-SPOService -Url https://mytanant-admin.sharepoint.com/ -Credential (Get-Credential)

Receiving below error:

Connect-SPOService : Method not found: 'Boolean System.Net.WebResponse.get_SupportsHeaders()'.
At line:1 char:1
+ Connect-SPOService -Url https://mytanant-admin.sharepoint.com/ -Credential $PSCred ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : NotSpecified: (:) [Connect-SPOService], MissingMethodException
  + FullyQualifiedErrorId : System.MissingMethodException,Microsoft.Online.SharePoint.PowerShell.ConnectSPOService

Fix/Solution:

For me the problem is due to .NET Framework. In my machine, I have already installed .NET 4.0 before installing SharePoint Online Management Shell. But the SharePoint Online Management Shell is developed over .NET 4.5, so the problem was solved after installing .NET Framework 4.5 in my server.

Connect-SPOService : Could not connect to SharePoint Online.

I am trying to connect the SharePoint Online service by using the cmdlet Connect-SPOService after importing SharePoint Online PowerShell module, but I am receiving the error 'Connect-SPOService : Could not connect to SharePoint Online.'.

PowerShell Command:

Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
Connect-SPOService –Url https://tenant-admin.sharepoint.com –Credential admin@tenant.onmicrosoft.com

Receiving below error:

Connect-SPOService : Could not connect to SharePoint Online.
At line:1 char:1
+ Connect-SPOService –Url https://tenant-admin.sharepoint.com –Credential admin@te ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-SPOService], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.Online.SharePoint.PowerShell.ConnectSPOService

Fix/Solution:

For me, the problem was due to invalid credentials. Yes, I have entered the wrong password, after providing the correct username and password, the issue was solved for me. You might also receive this error due to incorrect Admin url. So you have to carefully check the Admin url (the url should be like this: https://tenant-admin.sharepoint.com).

Import-Module : The specified module 'Microsoft.Online.SharePoint.PowerShell' was not loaded

When I import the SharePoint Online PowerShell module in PowerShell console, I am getting the error "Import-Module : The specified module 'Microsoft.Online.SharePoint.PowerShell' was not loaded".

Import Module Command:
PS C:\> Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
Error:
Import-Module : The specified module 'Microsoft.Online.SharePoint.PowerShell' was not loaded because no valid module file was found in any module directory.
At line:1 char:1
+ Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (Microsoft.Online.SharePoint.PowerShell:String) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

Fix/Solution:

The problem was solved for me after running the PowerShell console with elevated privilege (Run as administrator).

SharePoint Timer Service - OWSTIMER.EXE

What is OWSTIMER.EXE

OWSTIMER.EXE is a SharePoint Timer Service from Microsoft Corporation belonging to Microsoft SharePoint. The SharePoint Timer Service is a Window service that is installed with Windows SharePoint Services. This program is used to handled scheduled jobs related to Windows SharePoint.

File Location: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\50\bin\OWSTIMER.EXE 
Service Name: SPTimer 
Display Name: SharePoint Timer Service

Why OWSTIMER.EXE is taking high memory usage on the server?

Sometimes, you have noticed that your system consumes high memory due to owstimer.exe. The possible reason for this high memory usage on the server is due to the existing timer jobs over lapping with each other. You can also check the following things to narrow down the issue.

1) Check if you have any timer jobs over lapping with each other

2) As the owstimer.exe is spiking up there should be particular time slot in this happens If yes whats the user hit on server on the particular slot

3) Can you stop sharepoint timer service and check with the behavior.

4) Can you check the Application pool setting are they getting recycled often ?.

Source: https://social.technet.microsoft.com/Forums/sharepoint/en-US/cf64983a-3de0-4056-864d-b67f91179f0c/owstimerexe-memory-usage-maxing-on-the-server?forum=sharepointadminprevious

Tuesday, 8 March 2016

Get all Workflow Associated Lists in SharePoint Online

We can easily get all the lists and document libraries that are associated with workflow in SharePoint Online using CSOM. In this article, I am going to write C# code example to find and get all workflow enabled lists in a given site using CSOM (Client-Object Model).

Get all workflow enabled lists in a given site

using Microsoft.SharePoint.Client;
//-------------------------------------
static void GetWorkFlowAssociatedListsInSPO()
{
    string siteUrl = "https://tenant-name.sharepoint.com";

    var siteCtx = new ClientContext(siteUrl);

    var secPwd = new SecureString();
    foreach (char c in "MyPassword".ToCharArray()) secPwd.AppendChar(c);

    siteCtx.Credentials = new SharePointOnlineCredentials("admin@tenant.onmicrosoft.com", secPwd);
    Web site = siteCtx.Web;
    siteCtx.Load(site.Lists, li => li.Include(w => w.WorkflowAssociations,
                               w => w.Title, w => w.BaseType));
    siteCtx.ExecuteQuery();
    // Getting all workflow enabled lists
    foreach (List list in site.Lists.Where(a => a.WorkflowAssociations.Count > 0
                                           && a.BaseType == BaseType.GenericList))
    {
        Console.WriteLine("List Name: " + list.Title);
        Console.WriteLine("SubscribedWorkflows: " + 
                     string.Join(";", list.WorkflowAssociations.Select(a => a.Name)));
        Console.WriteLine("---------------------");
    }
}

Get all workflow enabled document libraries in a SharePoint Online site

using Microsoft.SharePoint.Client;
//-------------------------------------
static void GetWorkFlowAssociatedLibrariesInSPO()
{
    string siteUrl = "https://tenant-name.sharepoint.com/sites/contosopartners/News";

    var siteCtx = new ClientContext(siteUrl);

    var secPwd = new SecureString();
    foreach (char c in "MyPassword".ToCharArray()) secPwd.AppendChar(c);

    siteCtx.Credentials = new SharePointOnlineCredentials("admin@tenant.onmicrosoft.com", secPwd);
    Web site = siteCtx.Web;
    siteCtx.Load(site.Lists, li => li.Include(w => w.WorkflowAssociations, 
                       w => w.Title, w => w.BaseType));
    siteCtx.ExecuteQuery();
    // Getting all workflow enabled Document Libraries
    foreach (List list in site.Lists.Where(a => a.WorkflowAssociations.Count > 0
                            && a.BaseType == BaseType.DocumentLibrary))
    {
        Console.WriteLine("List Name: " + list.Title);
        Console.WriteLine("SubscribedWorkflows: " + 
                      string.Join(";", list.WorkflowAssociations.Select(a => a.Name)));
        Console.WriteLine("---------------------");
    }
}

Get all Workflow Associated Lists in SharePoint 2013

You can easily get all the lists and document libraries that are associated with workflow in a SharePoint farm server. In this article, I am going to write C# code example to find and get all the workflow enabled lists using CSOM (Client-Object Model).

Get all workflow enabled lists in a given site

using Microsoft.SharePoint.Client;
//-------------------------------------
static void GetWorkFlowAssociatedLists()
{
    string siteUrl = "http://sharepointsvr/sites/2/TestSite";

    var siteCtx = new ClientContext(siteUrl);
    siteCtx.Credentials = new NetworkCredential("SP\Administrator", "MyPassword");
    Web site = siteCtx.Web;
    siteCtx.Load(site.Lists, li => li.Include(w => w.WorkflowAssociations, 
                               w => w.Title, w => w.BaseType));
    siteCtx.ExecuteQuery();
    // Getting all workflow associated lists
    foreach (List list in site.Lists.Where(a => a.WorkflowAssociations.Count > 0 
                                           && a.BaseType == BaseType.GenericList))
    {
        Console.WriteLine("List Name: " + list.Title);
        Console.WriteLine("SubscribedWorkflows: " + 
                           string.Join(";", list.WorkflowAssociations.Select(a => a.Name)));
        Console.WriteLine("---------------------");
    }
}


Get all workflow enabled document libraries in a given SharePoint site

using Microsoft.SharePoint.Client;
//-------------------------------------
static void GetWorkFlowAssociatedLibraries()
{
    string siteUrl = "http://sharepointsvr/sites/2/TestSite";

    var siteCtx = new ClientContext(siteUrl);
    siteCtx.Credentials = new NetworkCredential("SP\Administrator", "MyPassword");
    Web site = siteCtx.Web;
    siteCtx.Load(site.Lists, li => li.Include(w => w.WorkflowAssociations,
                                             w => w.Title, w => w.BaseType));
    siteCtx.ExecuteQuery();
    // Getting all workflow associated Document Libraries
    foreach (List list in site.Lists.Where(a => a.WorkflowAssociations.Count > 0 
                                                 && a.BaseType == BaseType.DocumentLibrary))
    {
        Console.WriteLine("Libarary: " + list.Title);
        Console.WriteLine("SubscribedWorkflows: " + 
                      string.Join(";", list.WorkflowAssociations.Select(a => a.Name)));
        Console.WriteLine("---------------------");
    }
}

Thursday, 3 March 2016

Get all computers from OU in AD using PowerShell

We can get a list of all computers in Active Directory using the Powershell cmdlet Get-ADComputer. In this article, I am going to write powershell script to find and get a list of all computers from ceratin OU in AD and export computer details to csv file.

Before proceed run the following command to import Active Directory module.
Import-Module ActiveDirectory
The following command find and list all the available computers in Active Directory.
Get-ADComputer -Filter * -Properties * |
 Select -Property Name,DNSHostName,LastLogonDate

Get list of all computers in OU:

We can find and get a list of all computers from a certain OU by setting target OU scope by using the parameter SearchBase. The following powershell command select all computers from the Organization Unit 'TestOU'.
Get-ADComputer -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=com" -Properties *  |
 Select -Property Name,DNSHostName,LastLogonDate

Export all computers in OU to CSV:

We can export all computer details to csv file by using the powershell cmdlet Export-CSV.
Get-ADComputer -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=com" -Properties *  |
 Select -Property Name,DNSHostName,Enabled,LastLogonDate | 
 Export-CSV "C:\\AllComputersInOU.csv" -NoTypeInformation -Encoding UTF8

Get All Web Applications in SharePoint using powershell

You can get all the available web applications in a given sharepoint server by using the powershell cmdlet Get-SPWebApplication. Before proceed you need to run the following command to load SharePoint management cmdlets.
Add-PSSnapin Microsoft.SharePoint.PowerShell
The below powershell command list all the web applications in SharePoint Farm server.
Get-SPWebApplication | Select-Object -Property Name, Url, Status, @{n="Farm";e={$_.Farm.Name}}
You can export all the webapplications to csv file by using the powershell cmdlet Export-CSV.
Get-SPWebApplication | Select-Object  -Property Name, Url, Status, @{n="Farm";e={$_.Farm.Name}} |
Export-CSV "C:\\All-WebApplications.csv" -NoTypeInformation -Encoding UTF8

Get all Mail Enabled Lists and Libraries in SharePoint

In this article, I am going to write powershell script to find all mail enabled lists and libraries in SharePoint server. The following powershell script export all the mail enabled lists from a SharePoint web application to csv file. You need to replace your own web application url in the below script.
Add-PSSnapin Microsoft.SharePoint.PowerShell
 
$SPWebApp = Get-SPWebApplication "http://MySharePointWeb.com/"
# get all the site collections
$SiteCollections = $SPwebApp.Sites
$SiteCollections | ForEach-Object { 
# get the all sub sites of site collection
$SubSites = $_.AllWebs
$SubSites | ForEach-Object { 
$Site = $_
# get all lists from site
$lists = $Site.Lists | Where-Object { $_.BaseType -eq 'GenericList' }
$lists | ForEach-Object {                 
if (($_.CanReceiveEmail) -and ($_.EmailAlias) )
{
    New-Object -TypeName PSObject -Property @{
              ListName = $_.Title
              SiteUrl = $Site.Url
              EmailAlias = $_.EmailAlias 
}}}}}| Export-CSV "C:\\All-Mail-Enabled-Lists.csv" -NoTypeInformation -Encoding UTF8

Get all Mail Enabled Document Libraries in a SharePoint web application

The below powershell script find and export all the incoming e-mail enabled document libraries from a SharePoint web application to csv file.
Add-PSSnapin Microsoft.SharePoint.PowerShell

$SPWebApp = Get-SPWebApplication "http://MySharePointWeb.com/"
# get all the site collections  
$SiteCollections = $SPwebApp.Sites
$SiteCollections | ForEach-Object { 
# get the all sub sites of site collection
$SubSites = $_.AllWebs
$SubSites | ForEach-Object { 
$Site = $_
 # get all document Libraries from site
$lists = $Site.Lists | Where-Object { $_.BaseType -eq 'DocumentLibrary' }
$lists | ForEach-Object {                                     
if (($_.CanReceiveEmail) -and ($_.EmailAlias) )
{
    New-Object -TypeName PSObject -Property @{
              ListName = $_.Title
              SiteUrl = $Site.Url
              EmailAlias = $_.EmailAlias 
}}}}}| Export-CSV "C:\\All-Mail-Enabled-Libraries.csv" -NoTypeInformation -Encoding UTF8