Wednesday, 24 August 2016

Powershell - Check If String Contains Word

We can use the powershell's like operator with wildcard character to check if a string contains a word or another string with case-sensitive and case-insensitive.
Note: You can not use the comparison operator contains to check the contains string, because it's designed to tell you if a
collection of objects includes ('contains') a particular object
The following method is used to check if a string contains a word using like operator. By default like operator ignore the case-sensitive check.
$strVal ='Hello world'
if($strVal -like '*World*') {
      Write-Host 'Your string contains the word world'
} else {
      Write-Host 'Your string does not contains the word world'
}
To perform a Case-Sensitive comparison just prefix the word "c" with like operator ("clike").
$strVal ='Hello world'
if($strVal -clike '*world*') {
      Write-Host 'True'
} else {
      Write-Host 'False'
}
We can also use the built in .NET string extension function Contains to check whether a string contains a another string.
$strVal ='Hello world'
if($strVal.Contains('world')) {
     Write-Host 'True'
} else {
     Write-Host 'False'
}
The .Contains() function is case sensitive. If you want to use the Contains() method for case-insensitive check, convert both strings to one case before compare.
$strVal ='Hello world'
if($strVal.ToLower().Contains('world'.ToLower())) {
     Write-Host 'True'
} else {
     Write-Host 'False'
}
Read More...

Tuesday, 23 August 2016

Powershell - Check If String Starts With IgnoreCase

Checking a string is startswith some character(or a string) is common need for every kind of powershell script. We can use the powershell's like operator with wildcard character to check the startswith string for both case-sensitive and case-insensitive.

The following method is used to check if a string is starts with another string using like operator. By default like operator ignore the case-sensitive check.
$strVal ='Hello world'
if($strVal -like 'hello*') {
      Write-Host 'Your string is start with hello'
} else {
      Write-Host 'Your string does not start with hello"'
}
To perform a Case-Sensitive comparison just prefix the word "c" with like operator ("clike").
$strVal ='Hello world'
if($strVal -clike 'Hello*') {
      Write-Host 'True'
} else {
      Write-Host 'False'
}
We can also use the .NET's string extension function StartsWith to check whether a string is startswith a set of characters. The following method is used to check if a string is start with other string.
$strVal ='Hello world'
if($strVal.StartsWith('Hello')) {
     Write-Host 'True'
} else {
     Write-Host 'False'
}
Use the following method if you want to ignore the case in start with check.
$strVal ='Hello world'
if($strVal.StartsWith('hello','CurrentCultureIgnoreCase')) {
     Write-Host 'True'
} else {
     Write-Host 'False'
}
Read More...

Monday, 22 August 2016

Complete List of SharePoint List Template IDs

This post list the complete SharePoint List Templates and IDs. You should know the template id for every type of list to differentiate all the lists. When you work with client side object models(CSOM) or any other scripting technology, this template id will be used to filter the specified type of lists (i.e. if you want to get all the asset library lists, you need to filter the lists by the template id 851).

Template Type Id Description
100 Generic List
101 Document Library
102 Survey List
103 Links List
104 Announcements List
105 Contacts List
106 Events List
107 Tasks List
108 Discussion Board
109 Picture Library
110 DataSources List
111 WebTemplate Catalog
112 UserInformationList
114 ListTemplate Catalog
113 WebPart Catalog
115 XmlForm Library
116 MasterPage Catalog
117 NoCode Workflows
118 Workflow Process
119 WikiPage Library
120 Grid List
121 SolutionCatalog
122 NoCode Workflows Public
123 Theme Catalog
130 DataConnection Library
140 Workflow History
150 Gantt Tasks
151 Help Library
200 Meetings List
201 MeetingAgenda List
202 MeetingAttendees List
204 MeetingDecision List
207 MeetingObjectives List
210 MeetingTextBox
211 MeetingThingsToBring List
212 MeetingHomePage Library
301 BlogPosts List
302 BlogComments List
303 BlogCategories List
400 ScheduleAndReservations
401 ManageResources List
402 Resources List
403 Whereabouts List
404 CallTrackingPhoneMemo
405 Circulation
420 Timecard
421 Holidays
432 KPIStatus List
433 Report Library
450 PerformancePointContent List
460 PerformancePointDataSource Library
470 PerformancePointDataConnections Library
480 PerformancePointDashboards Library
499 MicrosoftIMEDictionary List
505 VisioProcessDiagram Library (Metric)
506 VisioProcessDiagram Library (US Units)
600 External List
850 Pages Library
851 Asset Library
1100 IssueTracking List
1200 AdministratorTasks List
1220 Health Rules
1221 Health Reports
1300 TranslationManagement Library
1301 LanguagesAndTranslators List
1302 Record Library
2002 PersonalDocument Library
2003 PrivateDocument Library
2100 Slide Library
Read More...

Thursday, 18 August 2016

Export Office 365 Email Addresses to CSV using Powershell

In this post, I am going write steps to export the list of exchange online users and their email addresses from Office 365 to csv file. We can use the powershell cmdlet Get-Mailbox to get mailbox information and use the cmdlet Export-CSV to export content to csv file.

Note: Before proceed, Connect Exchange Online Remote PowerShell.

Then run the below powershell command to list the mailbox users and its primary email address.
Get-Mailbox -ResultSize Unlimited |Select-Object DisplayName,PrimarySmtpAddress
The following command export all the exchange online users and its associated email addresses to csv file.
Get-Mailbox -ResultSize Unlimited |
Select-Object DisplayName,PrimarySmtpAddress, @{n="EmailAddresses";e={$_.EmailAddresses |
Where-Object {$_ -like "smtp*"} | ForEach-Object {$_.Substring(5)}}} | 
Export-Csv "C:\\o365-email-addresses.csv" -NoTypeInformation -Encoding UTF8
Read More...

Thursday, 11 August 2016

Convert a distribution group to an Office 365 group from Admin Center

Finally, the support for migrating Distribution list to Office 365 group comes to live through Office 365 Admin center. The introduction of Office 365 groups gives the next level for cloud first and mobile first agenda since it gives the rich collaboration experiences.

The office 365 group is the next generation type of group that replaces the function of a traditional distribution list, and it includes the benefits of a security group, along with many other rich collaboration that enables teams to come together and establish a single team identity and a single set of permissions across different Office 365 apps including Outlook, Planner, OneNote,OneDrive, Skype for Business, etc.

Using new DL migration option, you can now migrate a distribution group to an Office 365 group directly from the Exchange Admin Center.

For more details read this thread: https://network.office.com/t5/Exchange/Migrate-a-distribution-group-to-an-Office-365-group-with-one/m-p/4340/highlight/true#M81

migrate a distribution list to an Office 365 groupr
Read More...

Wednesday, 10 August 2016

Export Office 365 Users to CSV using PowerShell

We can easily export users using Office 365 Admin center UI, but in this way we can get only set of attributes and we can't easily filter our required set of users. In this article, I am going to write powershell script to export all office 365 users and export only licensed users to csv file.

Note: Before proceed, Install and Configure Azure AD PowerShell

Use the below command to export all the office 365 users. You can add more columns to export.
Get-MsolUser -All  | Select-Object UserPrincipalName, DisplayName, isLicensed |
Export-CSV "C:\\all-office-365-users.csv" -NoTypeInformation -Encoding UTF8
In some scenarios, you might want to get details of only licensed office 365 users. To get only licensed users, you need to apply where filter in the output of Get-MsolUser cmdlet.
Get-MsolUser -All | Where-Object { $_.isLicensed -eq ”TRUE” } | 
Select-Object UserPrincipalName, DisplayName, Department  |
Export-CSV "C:\\licensed-office-365-users.csv" -NoTypeInformation -Encoding UTF8
You can also extract what are the licenses has been assigned to every users. The below command export all the licensed users and applied license details to csv file.
Get-MSOLUser -All | Where-Object { $_.isLicensed -eq ”TRUE” } | 
Select-Object UserPrincipalName, DisplayName, {$_.Licenses.AccountSkuId} |
 Export-CSV "C:\\office-365-users-license.csv" -NoTypeInformation -Encoding UTF8
Note: Checkout this post ( Manage Office 365 License using Powershell ) to add a new license, remove an existing license and update existing license options (enable or disable license plans) using PowerShell command.
Read More...

Thursday, 4 August 2016

Mailbox : WhenCreated vs WhenMailboxCreated

You should have noticed the two attributes WhenCreated and WhenWhenMailbox while fetching the information through powershell using the cmdlet Get-Mailbox. The WhenMailboxCreated attribute shows the time when the mailbox was created or license assigned (in office 365). On the other side, the WhenCreated attribute gives time when the mailbox associated AD user or Azure AD user was actually created. So, the value of these two attributes may or may not equal.

WhenMailboxCreated : Gives the time when the mailbox was created.

WhenCreated : The time of when the AD user or Azure AD user of the associated mailbox was created.

So, if you want to get the list of mailboxes that are created in last 7 days. You need to use following powershell command.
Get-Mailbox | Where-Object {$_.WhenMailboxCreated –ge ((Get-Date).Adddays(-7))}
You may get incorrect results when you use whencreated to get mailboxes that are created in past N days. But, you can use below command to get actual AD users who are created in last 7 days.
Get-Mailbox | Where-Object {$_.WhenCreated –ge ((Get-Date).Adddays(-7))}
Read More...

Wednesday, 13 July 2016

whenCreated vs createTimeStamp

Both are Active Directory schema attributes which specifies the date and time of when an AD object was created. Both attributes return the same values, but the actual value is stored in whenCreated attribute alone, because createTimeStamp is a constructed attribute and it reads the data from whenCreated attribute.

WhenCreated attribute was implemented first, and to be complaint with LDAP standards the createTimeStamp was added later on as constructed attribute, the data is really stored only once in the Active Directory database.

Both attributes are replicated to all DC's, the createTimeStamp should not be replicated to the Global Catalog server since the isMemberOfPartialAttributeSet property of the attribute is not TRUE. However, you can also get a value from the GC.

Sources:

whenCreated vs createTimeStamp
Active directory attributes - createTimeStamp & whenCreated
Read More...

Tuesday, 12 July 2016

UserAccountControl Attribute Flag Values - Active Directory

UserAccountControl attribute is bitwise attribute and it control the behavior of the AD user and computer account.

This attribute value can be zero or a combination of one or more of the following values.

Property flagValue in hexadecimalValue in decimal
SCRIPT0x00011
ACCOUNTDISABLE0x00022
HOMEDIR_REQUIRED0x00088
LOCKOUT0x001016
PASSWD_NOTREQD0x002032
PASSWD_CANT_CHANGE
Note You cannot assign this permission by directly modifying the UserAccountControl attribute. For information about how to set the permission programmatically, see the "Property flag descriptions" section.
0x004064
ENCRYPTED_TEXT_PWD_ALLOWED0x0080128
TEMP_DUPLICATE_ACCOUNT0x0100256
NORMAL_ACCOUNT0x0200512
INTERDOMAIN_TRUST_ACCOUNT0x08002048
WORKSTATION_TRUST_ACCOUNT0x10004096
SERVER_TRUST_ACCOUNT0x20008192
DONT_EXPIRE_PASSWORD0x1000065536
MNS_LOGON_ACCOUNT0x20000131072
SMARTCARD_REQUIRED0x40000262144
TRUSTED_FOR_DELEGATION0x80000524288
NOT_DELEGATED0x1000001048576
USE_DES_KEY_ONLY0x2000002097152
DONT_REQ_PREAUTH0x4000004194304
PASSWORD_EXPIRED0x8000008388608
TRUSTED_TO_AUTH_FOR_DELEGATION0x100000016777216
PARTIAL_SECRETS_ACCOUNT0x04000000  67108864

Note: In a Windows Server 2003-based domain, LOCK_OUT and PASSWORD_EXPIRED have been replaced with a new attribute called ms-DS-User-Account-Control-Computed. For more information, check this article:https://msdn.microsoft.com/en-us/library/ms677840.aspx.

All the information available in Microsoft KB Article: https://support.microsoft.com/en-in/kb/305144

UserAccountControl flag descriptions:

  • SCRIPT - The logon script will be run.
  • ACCOUNTDISABLE - The user account is disabled.
  • HOMEDIR_REQUIRED - The home folder is required.
  • PASSWD_NOTREQD - No password is required.
  • PASSWD_CANT_CHANGE - The user cannot change the password. This is a permission on the user's object. For information about how to programmatically set this permission, visit the following Web site:
  • ENCRYPTED_TEXT_PASSWORD_ALLOWED - The user can send an encrypted password.
  • TEMP_DUPLICATE_ACCOUNT - This is an account for users whose primary account is in another domain. This account provides user access to this domain, but not to any domain that trusts this domain. This is sometimes referred to as a local user account.
  • NORMAL_ACCOUNT - This is a default account type that represents a typical user.
  • INTERDOMAIN_TRUST_ACCOUNT - This is a permit to trust an account for a system domain that trusts other domains.
  • WORKSTATION_TRUST_ACCOUNT - This is a computer account for a computer that is running Microsoft Windows NT 4.0 Workstation, Microsoft Windows NT 4.0 Server, Microsoft Windows 2000 Professional, or Windows 2000 Server and is a member of this domain.
  • SERVER_TRUST_ACCOUNT - This is a computer account for a domain controller that is a member of this domain.
  • DONT_EXPIRE_PASSWD - Represents the password, which should never expire on the account.
  • MNS_LOGON_ACCOUNT - This is an MNS logon account.
  • SMARTCARD_REQUIRED - When this flag is set, it forces the user to log on by using a smart card.
  • TRUSTED_FOR_DELEGATION - When this flag is set, the service account (the user or computer account) under which a service runs is trusted for Kerberos delegation. Any such service can impersonate a client requesting the service. To enable a service for Kerberos delegation, you must set this flag on the userAccountControl property of the service account.
  • NOT_DELEGATED - When this flag is set, the security context of the user is not delegated to a service even if the service account is set as trusted for Kerberos delegation.
  • USE_DES_KEY_ONLY - (Windows 2000/Windows Server 2003) Restrict this principal to use only Data Encryption Standard (DES) encryption types for keys.
  • DONT_REQUIRE_PREAUTH - (Windows 2000/Windows Server 2003) This account does not require Kerberos pre-authentication for logging on.
  • PASSWORD_EXPIRED - (Windows 2000/Windows Server 2003) The user's password has expired.
  • TRUSTED_TO_AUTH_FOR_DELEGATION - (Windows 2000/Windows Server 2003) The account is enabled for delegation. This is a security-sensitive setting. Accounts that have this option enabled should be tightly controlled. This setting lets a service that runs under the account assume a client's identity and authenticate as that user to other remote servers on the network. 
  • PARTIAL_SECRETS_ACCOUNT - (Windows Server 2008/Windows Server 2008 R2) The account is a read-only domain controller (RODC). This is a security-sensitive setting. Removing this setting from an RODC compromises security on that server.
Read More...

Tuesday, 5 July 2016

How to call a function in a ps1 file from powershell

In Powershell world, the user defined function is one of the easiest way to reuse the set of powershell commands. In some scenarios, this function might be too big, so having functions in separate ps1 file and load a function by importing .ps1 file is a good choice. In this post, I am going to explain how to import a powershell function from ps1 file.

Load Powershell function from ps1 file:

You just imagine the ps1 file MyScript.ps1, and the file contains the following content:
Write-Host "Loading functions"
function MyFunc
{
    Write-Host "MyFunc is running!"
}
Write-Host "Done"
To register the function MyFunc, we need to run the .ps1 file with the dot(.) operator prefix.
 . C:\Scripts\MyScript.ps1
The dot operator is used to include script.
PS C:>  . C:\Scripts\MyScript.ps1
Loading functions
Done

PS C:\> MyFunc
MyFunc is running!

Import Powershell function from psm1 file:

We can also import a function from PSM1 file by using Import-Module command. The major advantage of using Import-Module is that you can unload them from the shell if you need to, and it keeps the variables in the functions from creeping into the shell. First, save the MyScript.ps1 as MyScript.psm1 and load the file by using below command.
Import-Module C:\Scripts\MyScript.psm1
PS C:\> Import-Module C:\Scripts\MyScript.psm1
Loading functions
Done
PS C:\> MyFunc
MyFunc is running!
Read More...

Tuesday, 21 June 2016

Create Office 365 Group using Powershell

Office 365 Groups provide a platform for collaboration that enables teams to come together and establish a single team identity and a single set of permissions across different Office 365 apps including Outlook, OneDrive, OneNote, Skype for Business, Power BI and Dynamics CRM. In this article, I am going write powershell commands to create Office 365 Groups, add members and owners to an Office 365 Group.

Before proceed, first connect Exchange Online Powershell session by using the following commands.
$365Logon = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Logon -Authentication Basic -AllowRedirection
Import-PSSession $Session
We can use the PowerShell cmdlet New-UnifiedGroup to create a new Office 365 group. This cmdlet includes the following key parameters:

DisplayName – display name of the new group
Alias – Email alias of the group. If you omit the parameter, it will generate an alias by using display name.
AccessType – Privacy type of the group (Public or Private)
AutoSubscribeNewMembers – Add this parameter to auto subscribe new members to the group

Use the below command to create a new group with minimal parameters.
New-UnifiedGroup –DisplayName "Test O365 Group 1"
Create the group with key parameters.
New-UnifiedGroup –DisplayName "Test O365 Group 2" -Alias "TestO365Group2" -AccessType Public
Once we created the group, we can use Get-UnifiedGroup cmdlet to list all the available groups.

Add Members and Owners to Office 365 Group

We can use Add-UnifiedGroupLinks cmdlet to add members and owners to the group. This cmdlet includes the following key parameters:

Identity – Alias, Display name, or Email address of the group
Links – Alias, Display name, or Email address of the user being added
LinkType – Members, Owners, or Subscribers

Add an user as owner: To add an user as owner to the group, first we need the user as a member to the specified group.
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Members –Links Morgan
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Owners –Links Morgan
Add member:
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Members  –Links AlexD
Add subscriber: A subscriber who receives updates by email can be added by changing the LinkType to "Subscribers"
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Subscribers  –Links AlexD
The parameter Links accept multiple values, use the following syntax: value1,value2.... If the values contain spaces or otherwise require quotation marks, use the following syntax: "value1","value2",....

Add members to multiple office 365 groups:

$Groups = "group 01","group 02","group 03"
$Groups | ForEach-Object {
Add-UnifiedGroupLinks –Identity $_ –LinkType Members  –Links "Morgan" }

Import office 365 group members from a CSV File:

You can use the below powershell commands to add members to an office 365 group by importing users from csv file. Consider the csv file members.csv that includes the column member which holds the member identity in each row of the csv file.
Import-CSV "C:\members.csv" | ForEach-Object {
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Members  –Links $_.member
}

Find members and owners of a group:

Once we added the members and owners, we can use Get-UnifiedGroupLinks cmdlet to get members or owners of a specific group. The below command lists all members of the given group.
Get-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Members
List owners of a group.
Get-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Owners
Read More...

Friday, 17 June 2016

Set Storage Quota for Office 365 Group Site using PowerShell

As you know, Office 365 Group is nothing but a hidden site collection that are not visible in Site Collections view in Office 365 Admin portal. You can only access these site collections by using PowerShell or through URL (https://<tanentname>.sharepoint.com/sites/<group-name>/Shared documents”). Since you can't view the site in Office 365 Admin portal, the only way set storage size limit is using Powershell. In this article, I am going to write powershel script to set maximum storage size and storage warning level for Office 365 group site.

We can use the SharePoint Online Powershell cmdlet Set-SPOSite to set storage quota and storage warning size limit. Before proceed, run the following command to connect Sharepoint Online powershell module.
Connect-SPOService -Url https://<tanentname>-admin.sharepoint.com -Credential admin@o365domain.com
Now, run the following script to set storage quota and warning level.
$StorageQuota= 2048 # 2GB or 2048MB
$WarningLevel = 1800 # 1800MB

$siteUrl ="https://<tanentname>.sharepoint.com/sites/<group-name>"
Set-SPOSite -Identity $siteUrl -StorageQuota $StorageQuota -StorageQuotaWarningLevel $WarningLevel

Set Storage Quota for all Office 365 Groups Site:

To set the storage quota for all the Office 365 Groups, first, we need to get sharepoint site url for all the office 365 groups by using Exchange Online cmdlet Get-UnifiedGroup. The following powershell script update storage quota and warning level for all the office 365 groups. You need to replace your own Office 365 tenant name and admin credentials.
$userName ="admin@<tanentname>.onmicrosoft.com" 
$o365Cred = Get-Credential -UserName $userName -Message "Enter Office 365 Admin Credentials"
$o365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $o365Cred -Authentication Basic -AllowRedirection
Import-PSSession $o365Session

$spoAdminUrl ="https://<tanentname>-admin.sharepoint.com/" 
Connect-SPOService -Url $spoAdminUrl -Credential $o365Cred 

$O365Groups = Get-UnifiedGroup -ResultSize Unlimited

$StorageQuota= 2048 # 2GB or 2048MB
$WarningLevel = 1800 # 1800MB

ForEach ($O365Group in $O365Groups){ 
If($O365Group.SharePointSiteUrl -ne $null) {
$siteUrl = $O365Group.SharePointSiteUrl
Set-SPOSite -Identity $siteUrl -StorageQuota $StorageQuota -StorageQuotaWarningLevel $WarningLevel 
}
}
Once you set the storage quota, you can use the Powershell cmdlet Get-SPOSite to get current storage quota and warning level. The following script list storage quota of all the office 365 groups site.

$O365Groups = Get-UnifiedGroup -ResultSize Unlimited
$CustomResult=@() 
ForEach ($O365Group in $O365Groups){ 
If($O365Group.SharePointSiteUrl -ne $null) 
{ 
   $O365GroupSite=Get-SPOSite -Identity $O365Group.SharePointSiteUrl 
   $CustomResult += [PSCustomObject] @{ 
     GroupName =  $O365Group.DisplayName
     SiteUrl = $O365GroupSite.Url 
     StorageQuota_inGB = $O365GroupSite.StorageQuota/1024
     WarningSize_inGB =  $O365GroupSite.StorageQuotaWarningLevel/1024
     CurrentStorage_inMB = $O365GroupSite.StorageUsageCurrent
  }
}} 
 
$CustomResult | FT
Read More...

Thursday, 16 June 2016

Get the storage used by Office 365 groups using Powershell

Office 365 Groups are nothing but a hidden site collection with mailbox that are not visible in Site Collections view in Office 365 tenant Admin portal. You can only access these site collections by using PowerShell or through URL (https://<tanentname>.sharepoint.com/sites/<group-name>/Shared documents”). Often, Office 365 administrators need to find the storage used by Office 365 groups since this storage gets the storage quota of the SharePoint Site Collections. In this post, I am going to write powershel script to find storage used by office 365 groups.

We can use the SharePoint Online Powershell cmdlet Get-SPOSite to get current site storage size and storage quota. Before proceed, run the following command to connect Sharepoint Online powershell module.
Connect-SPOService -Url https://<tanentname>-admin.sharepoint.com -Credential admin@o365domain.com
Now run the below script after replacing the <tanentname> and <group-name> with your own tenant name and group name.
$O365GroupSiteUrl ="https://<tanentname>.sharepoint.com/sites/<group-name>"
$O365GroupSite = Get-SPOSite -Identity $O365GroupSiteUrl
$StorageSize =$O365GroupSite.StorageUsageCurrent 
                
Write-Host "Storage  used (MB): " $StorageSize " MB" -ForegroundColor Yellow
Write-Host "Storage  used (GB): " ($StorageSize/1024) " GB" -ForegroundColor Yellow

Get the current Storage Size for all Office 365 Groups:

To get the storage used by all Office 365 Groups, first, we need to get sharepoint site url for all the office 365 groups by using Exchange Online cmdlet Get-UnifiedGroup. The following powershell script gets current storage size and storage quota of all the office 365 groups. You need to replace your own Office 365 tenant name and admin credentials.
$userName ="admin@<tanentname>.onmicrosoft.com" 
$o365Cred = Get-Credential -UserName $userName -Message "Enter Office 365 Admin Credentials"

$o365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $o365Cred -Authentication Basic -AllowRedirection
Import-PSSession $o365Session

$spoAdminUrl ="https://<tanentname>-admin.sharepoint.com/" 
Connect-SPOService -Url $spoAdminUrl -Credential $o365Cred 

$O365Groups = Get-UnifiedGroup -ResultSize Unlimited

$CustomResult=@() 

ForEach ($O365Group in $O365Groups){ 
If($O365Group.SharePointSiteUrl -ne $null) 
{ 
   $O365GroupSite=Get-SPOSite -Identity $O365Group.SharePointSiteUrl 
   $CustomResult += [PSCustomObject] @{ 
     GroupName =  $O365Group.DisplayName
     SiteUrl = $O365GroupSite.Url 
     StorageUsed_inMB = $O365GroupSite.StorageUsageCurrent
     StorageQuota_inGB = $O365GroupSite.StorageQuota/1024
     WarningSize_inGB =  $O365GroupSite.StorageQuotaWarningLevel/1024
  }
}} 
 
$CustomResult | FT
You can also export the output into csv file:
$CustomResult | Export-CSV "C:\\O365-Group-Storage-Info.csv" -NoTypeInformation -Encoding UTF8
Read More...

Thursday, 9 June 2016

Convert Int64 TimeStamp to DateTime in Powershell

Some Applications (Ex: Active Directory ) stores DateTime value as TimeStamp value in a way to support different time zone. The Int64 TimeStamp is nothing but Windows file time. The Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).

In Powershell, we can use the .Net function FromFileTime and convert the output to DateTime format.
$timestamp = "131099683087123361"
[DateTime]::FromFileTimeutc($timestamp)
You can also convert the standard datetime to timestamp value by using the function ToFileTimeUtc.
$date = Get-Date
$date.ToFileTimeUtc()
In Active Directory environment, the attributes LastLogonTimeStamp and PwdLastSet are stored as Int64 TimeStamp. When you query these properties by using Get-ADUser cmdlet, you need to explicitly convert LastLogonTimeStamp value into datetime value.
Get-ADUser -Identity 'Smith' -Properties LastLogonTimeStamp | 
Select-Object -Property "Name", @{n="LastLogon";e={[datetime]::FromFileTime($_."LastLogonTimeStamp")}}
The following powershell command convert AD user's PwdLastSet value to datetime value.
Get-ADUser -Identity 'Smith' -Properties PwdLastSet | 
Select-Object -Property "Name", @{n="PwdLastSet";e={[datetime]::FromFileTime($_."PwdLastSet")}}
Read More...

Wednesday, 8 June 2016

List Office 365 Group Members using Powershell

The post helps you to list office 365 group (not distribution group) members by using powershell script. We can list all the office 365 groups by using the powershell cmdlet Get-UnifiedGroup and its group members by Get-UnifiedGroupLinks cmdlet.

Note: Before proceed, Connect Exchange Online Remote PowerShell.

The following command lists all the office 365 groups.
Get-UnifiedGroup | Select DisplayName,GroupType,PrimarySmtpAddress

List Office 365 Group Members

We can use the powershell cmdlet Get-UnifiedGroupLinks to view the members of an existing group. The key parameters for this cmdlet are:

Identity – the alias of the group
LinkType – Members, Owners, or Subscribers. Required.

Use the below powershell command to select members of a single office 365 group.
Get-UnifiedGroupLinks -Identity '<group-name>' -LinkType Members
If you want to list members of all the office 365 groups, first, we need to get the results of Get-UnifiedGroup, then we can pipe the output to ForEach-Object and get members for all the office 365 groups.
$Groups = Get-UnifiedGroup -ResultSize Unlimited
$Groups | ForEach-Object {
$group = $_
Get-UnifiedGroupLinks -Identity $group.Name -LinkType Members | ForEach-Object {
      New-Object -TypeName PSObject -Property @{
       Group = $group.DisplayName
       Member = $_.Name
       EmailAddress = $_.PrimarySMTPAddress
       RecipientType= $_.RecipientType
}}}

Export All Office 365 Group Members to CSV

We can export powershell output into CSV file using Export-CSV cmdlet. The following command exports all the office 365 group members to CSV file.
$Groups = Get-UnifiedGroup -ResultSize Unlimited
$Groups | ForEach-Object {
$group = $_
Get-UnifiedGroupLinks -Identity $group.Name -LinkType Members | ForEach-Object {
      New-Object -TypeName PSObject -Property @{
       Group = $group.DisplayName
       Member = $_.Name
       EmailAddress = $_.PrimarySMTPAddress
       RecipientType= $_.RecipientType
}}} |

Export-CSV "C:\\Office365GroupMembers.csv" -NoTypeInformation -Encoding UTF8
Read More...