Thursday, 24 November 2016

Get all checked out files in SharePoint Library using CSOM

If you are in business need to find and get the list of all checked out documents from a sharepoint document library, we can easily achieve it by using client object model (csom) in C#.

The following C# code find and lists the files which are checkout by current user and all other users.
public static void GetAllCheckedOutFilesInLibrary() 
{ 
    string sitrUrl = "https://spotenant.sharepoint.com/sites/contoso"; 
    using (var ctx = new ClientContext(sitrUrl)) 
    { 
        //ctx.Credentials = 
        ctx.Load(ctx.Web, a => a.Lists); 
        ctx.ExecuteQuery(); 
 
        var listName = "Documents"; 
        List list = ctx.Web.Lists.GetByTitle(listName); 
        var items = list.GetItems( 
            new CamlQuery() {  
            ViewXml = @"<View Scope='RecursiveAll'><Query> 
            <Where><IsNotNull><FieldRef Name='File_x0020_Type' /></IsNotNull></Where> 
            </Query></View>"  
        }); 
        ctx.Load(items, a => a.IncludeWithDefaultProperties(item => item.File, item => item.File.CheckedOutByUser)); 
        ctx.ExecuteQuery(); 
        foreach (var item in items) 
        { 
            if (item.File.CheckOutType != CheckOutType.None) 
            { 
                Console.WriteLine("File: " + item["FileRef"].ToString().Split('/').LastOrDefault()); 
                Console.WriteLine("Checked-Out By: " + item.File.CheckedOutByUser.Title); 
                Console.WriteLine("Checked-Out User Email: " +item.File.CheckedOutByUser.Email); 
                Console.WriteLine("Last Modified: " + DateTime.Parse(item["Last_x0020_Modified"].ToString())); 
                Console.WriteLine("-----------------------"); 
                Console.WriteLine(""); 
            } 
        } 
    } 
}
In the above code first we are retrieving all the files and check every file if it is checked out or not, this method may takes some time to process large document library. So alternatively we can use filter in caml query itself and retrieve checked out files alone.
public static void GetAllCheckedOutFilesWithCamlQuery() 
{ 
    string sitrUrl = "https://spotenant.sharepoint.com/sites/contoso"; 
    using (var ctx = new ClientContext(sitrUrl)) 
    { 
        //ctx.Credentials = 
        ctx.Load(ctx.Web, a => a.Lists); 
        ctx.ExecuteQuery();  
 
        var listName = "Documents"; 
        List list = ctx.Web.Lists.GetByTitle(listName); 
        var files = list.GetItems(  
            new CamlQuery()  
            { 
            ViewXml = @"<View Scope='RecursiveAll'><Query> 
            <Where><IsNotNull><FieldRef Name='CheckoutUser' /></IsNotNull></Where> 
            </Query></View>" 
            }); 
        ctx.Load(files); 
        ctx.ExecuteQuery(); 
        foreach (var file in files) 
        { 
            Console.WriteLine("File: " + file["FileRef"].ToString().Split('/').LastOrDefault()); 
            Console.WriteLine("Checked-Out By: " + (file["CheckoutUser"] as FieldUserValue).Email); 
            Console.WriteLine("Last Modified: " + DateTime.Parse(file["Last_x0020_Modified"].ToString())); 
            Console.WriteLine("-----------------------"); 
            Console.WriteLine(""); 
        } 
    } 
} 
The above caml query retrieves documents which are checkout by all the users. If you want to get all the documents that are checked out by the current user then you can use the following caml query.
<Where>
<And>
<IsNotNull>
<FieldRef Name='CheckoutUser' />
</IsNotNull>
<Eq>
<FieldRef Name='CheckoutUser' />
<Value Type=’Integer’>
<UserID Type=’Integer’ />
</Value>
</Eq>
</And>
</Where>
Read More...

Friday, 11 November 2016

Check if Office 365 user exists or not with Powershell

In this article I am going write powershell script to check if an Office 365 user exists or not with the Azure AD Powershell cmdlet Get-MsolUser. First run the below command to connect Office 365 Powershell module.
Import-Module MSOnline
$msolCred = Get-Credential
Connect-MsolService –Credential $msolCred
The below command checks if the given user account already exists in Office 365 or not. You can retrieve user by using ObjectId or UserPrincipalName of the user.
$upn = "alexd@MyTenant.onmicrosoft.com"
$User = Get-MsolUser -UserPrincipalName $upn -ErrorAction SilentlyContinue
If ($User -ne $Null) { 
"User exists in Azure AD" 
} Else {
"User not found in Azure AD"}
You need to use the parameter -ErrorAction SilentlyContinue to skip error when user not found, otherwise you will get the error message 'Get-MsolUser : User Not Found'.

Check if multiple Azure AD accounts are exists or not

First set list of user's userprincipalname as array object and enumerate the array to find user account in Office 365.
$users = @("alexd@MyTenant.onmicrosoft.com","sarad@MyTenant.onmicrosoft.com","kevin@MyTenant.onmicrosoft.com")
foreach ($user in $users) {
$userobj = Get-MsolUser -UserPrincipalName $user -ErrorAction SilentlyContinue
If ($userobj -ne $Null) {
    Write-Host "$user already exists" -foregroundcolor "green"
} else {
    Write-Host "$user not found " -foregroundcolor "red"
}}
Read More...

Thursday, 10 November 2016

Check if AD user exists with PowerShell

In this article I am going write powershell commands to check if an Active Directory user exists or not with the AD Powershell cmdlet Get-ADUser. First run the below command to import the Active Directory module.
Import-Module ActiveDirectory
The below command checks if the given user account exists in AD or not. You can identify a user by its distinguished name (DN), GUID, SID,SamAccountName or Name.
$Name = "kevin"
$User = $(try {Get-ADUser $Name} catch {$null})
If ($User -ne $Null) { 
"User exists in AD" 
} Else {
"User not found in AD"}
You need to use try-catch block to skip error when user not found, otherwise you will receive the error message 'Get-ADUser : Cannot find an object with identity'.

Find if multiple AD users are exists or not

We can set list of user names as array object and enumerate the users to find user account in AD.
$users = @("kevin","smith","nick")
foreach ($user in $users) {
$userobj = $(try {Get-ADUser $user} catch {$Null})
If ($userobj -ne $Null) {
    Write-Host "$user already exists" -foregroundcolor "green"
} else {
    Write-Host "$user not found " -foregroundcolor "red"
}}
Read More...

Tuesday, 1 November 2016

Check if AD Users from OU are Member of a Group using Powershell

We can use the Active Directory powershell cmdlet Get-ADGroupMember to check if an AD user is member of an AD group. In this article, I am going to write powershell script to find if users of specific OU are member of a Group.

Run the following command to import Active Directory cmdlets.
Import-Module ActiveDirectory

Find AD Users from OU are Member of a Group:

We can use the cmdlet Get-ADUser to get AD users from specific OU and enumerate the users to check their membership in the particular group. We can use the parameter -Recursive with Get-ADGroupMember cmdlet to get nested group members along with direct group members. The following powershell command select users from the Organization Unit 'TestOU' and check the users are member of 'Domain Admins' group.
$users = Get-ADUser -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=com"
$group = "Domain Admins"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name
$users | ForEach-Object {
$user = $_.Name
If ($members -contains $user) {
      Write-Host "$user exists in the group"
} Else {
      Write-Host "$user not exists in the group"
}}

Check if Single User is Member of a Group:

The following powershell command find if particular single user is member of 'Domain Admins' group.
$user = "TestUser"
$group = "Domain Admins"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name

If ($members -contains $user) {
      Write-Host "$user exists in the group"
 } Else {
        Write-Host "$user not exists in the group"
}
Read More...

Thursday, 27 October 2016

Connect-MsolService through Proxy in Powershell

Problem:

I used to connect Azure AD Powershell module using Connect-MsolService command. I can always able to successfully connect via proxy server and without proxy. But for some reason, today, I am receiving the errors Exception of type Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown and There was no endpoint listening at https://provisioningapi.microsoftonline.com/provisioningwebservice.svc that could accept the message when I use Connect-MsolService command.

Error Message 1:
Connect-MsolService : There was no endpoint listening at 
https://provisioningapi.microsoftonline.com/provisioningwebservice.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details. 
At line:1 char:1 
+ Connect-MsolService -Credential $Livecred; 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo          : OperationStopped: (:) [Connect-MsolService], EndpointNotFoundException 
    + FullyQualifiedErrorId : System.ServiceModel.EndpointNotFoundException,Microsoft.Online.Administration.Automation 
   .ConnectMsolService
Error Message 2:
Connect-MsolService : Exception of type 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown. 
At line:1 char:1 
+ Connect-MsolService -Credential $Livecred; 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo          : OperationStopped: (:) [Connect-MsolService], MicrosoftOnlineException 
    + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.MicrosoftOnlineException,Microsoft.Online.Adm 
   inistration.Automation.ConnectMsolService 

Fix/Solution:

The problem was solved for me after configuring Powershell to use proxy authentication for Microsoft Online endpoint (https://provisioningapi.microsoftonline.com/provisioningwebservice.svc) using Invoke-WebRequest command in Powershell.
Invoke-WebRequest -Proxy http://myporxyerver:myport -ProxyUseDefaultCredentials https://provisioningapi.microsoftonline.com/provisioningwebservice.svc
After running the above command, now the Powershell uses my proxy settings to connect Microsoft Office 365.

Note: replace myporxyerver with your proxy server and myport with your proxy server port.
Read More...

Tuesday, 25 October 2016

Set Office 365 User Password Never Expire using Powershell

We may have a requirement to set a password for an individual user to never expire and in some cases requirement would be set a group of user's password to never expire. We can set passwordneverexpires flag to Office 365 user by using the Azure AD powershell cmdlet Set-MsolUser.

Before porceed run the following command to connect Azure AD powershell module:
Import-Module MSOnline
$msolCred = Get-Credential
Connect-MsolService –Credential $msolCred
Run the below command to set an individual user’s password to never expire.
Set-MsolUser -UserPrincipalName user@yourdomain.onmicrosoft.com -PasswordNeverExpires $true
If you want to verify the PasswordNeverExpires setting has been applied or not, you can check it by using Get-MsolUser cmdlet.
Get-MsolUser -UserPrincipalName user@yourdomain.onmicrosoft.com | Select PasswordNeverExpires

Set Password Never Expire for Group of Users

In some situations, we may required to set specific type of user's password to never expire (i.e. users who are in same department or same office). In this case, we need to first get users by applying filter in Get-MsolUser cmdlet and pipe the results to Set-MsolUser cmdlet.
Get-MsolUser -All | Where-Object { $_.Department -like '*Admin*'} | Set-MsolUser -PasswordNeverExpires $true
You can just remove the where-object check in above command if you want to set it for all users.

Set Bulk AD Users Password Never Expire from CSV

We can import users from csv file and set passwordneverexpires setting. Consider the CSV file office365users.csv which contains set of Office 365 users with the column header UserPrincipalName.
Import-Csv 'C:\office365users.csv' | ForEach-Object {
$upn = $_."UserPrincipalName"
Set-MsolUser -UserPrincipalName $upn -PasswordNeverExpires $true;
}

Get all Users whose Password Never Expire

We can select all Azure AD users whose password never expire by using below command.
Get-MsolUser -All | Where-Object { $_.PasswordNeverExpires -eq $true} |
Select DisplayName,UserPrincipalName
Use below command to export output to csv file.
Get-MsolUser -All | Where-Object { $_.PasswordNeverExpires -eq $true} | 
Select DisplayName,UserPrincipalName |
Export-CSV "C:\\PwdNeverExpireUsers.csv" -NoTypeInformation -Encoding UTF8
Read More...

Tuesday, 18 October 2016

Connecting to remote server failed with the following error message - ps.outlook.com

Problem:

I am receiving the error '[ps.outlook.com] Connecting to remote server failed with the following error message : The SSL connection cannot be established' when I try to connect remote Exchange Online powershell by using below command.
Import-Module MSOnline
$O365Cred = Get-Credential
$O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred - 
Authentication Basic -AllowRedirection
Import-PSSession $O365Session
Error Message:
[ps.outlook.com] Connecting to remote server failed with the following error message : The SSL connection cannot be established. Verify that the service on the remote host is properly 
configured to listen for HTTPS requests. Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is 
the WinRM service, run the following command on the destination to analyze and configure the WinRM service: "winrm quickconfig -transport:https". For more information, see the about_Re
mote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionOpenFailed

Fix/Solution:

For me the problem was fixed after changing the Exchange Online ConnectionUri https://ps.outlook.com/powershell as https://outlook.office365.com/powershell-liveid/. The below command is working fine for me now.
Import-Module MSOnline
$O365Cred = Get-Credential
$O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $O365Cred -Authentication Basic -AllowRedirection
Import-PSSession $O365Session
Read More...

Thursday, 13 October 2016

Check Mailbox Size and Usage Report using Powershell

In this collaborative business world mail communication is one of the best platform to share messages and files with customers and colleague. So, we often required to check mailbox size and quota for every user's mailbox. In this post, I am going write Powershell script to find mailbox size and usage status and find users who are going to reach their storage quota.

We can use the Exchange Online powershell cmdlet Get-MailboxStatistics to get mailbox size, and other mailbox related statistics data. This cmdlet will be available for both Exchange On-Premises server and Exchange Online (Office 365). Before proceed, first we need to connect Remote Exchange Online powershel module by running below command:
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Run the below command to get mailbox statistics for a single user.
Get-MailboxStatistics -Identity [username]
By default this command returns the DisplayName, ItemCount, StorageLimitStatus, and LastLogonTime fields for the specified user. But what we need is mailbox size, so we need to alter the command to return required fields.
Get-MailboxStatistics [username] | Select DisplayName, TotalItemSize,StorageLimitStatus, ItemCount
The field StorageLimitStatus indicates whether the user is above or below the storage limit. The field TotalItemSize shows the total size of a mailbox in bytes, we need to convert this size into MB or GB to make the value as user friendly.
Get-MailboxStatistics [username] | Select DisplayName, @{n=”Total Size (MB)”;e={[math]::Round(($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),2)}}, StorageLimitStatus

Find Mailbox Size for all Office 365 users:

You can use the powershell cmdlet Get-Mailbox to get all the mailboxes and pipe the results into Get-MailboxStatistics cmdlet to get mailbox size for all users.
Get-Mailbox -ResultSize Unlimited  | Get-MailboxStatistics |
Select DisplayName, @{n=”Total Size (MB)”;e={[math]::Round(($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),2)}}, StorageLimitStatus

Export Mailbox Size, Quota and Storage Limit Status Report to CSV:

The below powershell script export mailbox name, userprincipalname, current mailbox usage size (TotalItemSize), storage warning quota (IssueWarningQuota), maximum size limit (ProhibitSendQuota) and size limit status (StorageLimitStatus) to csv file
$Result=@() 
$mailboxes = Get-Mailbox -ResultSize Unlimited
$totalmbx = $mailboxes.Count
$i = 1 
$mailboxes | ForEach-Object {
$i++
$mbx = $_
$mbs = Get-MailboxStatistics $mbx.UserPrincipalName
 
Write-Progress -activity "Processing $mbx" -status "$i out of $totalmbx completed"
 
if ($mbs.TotalItemSize -ne $null){
$size = [math]::Round(($mbs.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),2)
}else{
$size = 0 }

$Result += New-Object PSObject -property @{ 
Name = $mbx.DisplayName
UserPrincipalName = $mbx.UserPrincipalName
TotalSizeInMB = $size
SizeWarningQuota=$mbx.IssueWarningQuota
StorageSizeLimit = $mbx.ProhibitSendQuota
StorageLimitStatus = $mbs.ProhibitSendQuota
}
}
$Result | Export-CSV "C:\\MailboxSizeReport.csv" -NoTypeInformation -Encoding UTF8
Read More...