Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Wednesday, January 3, 2018

Powershell code (local) to list user AD memberships

Powershell code snippet which you could run using PowerShell ISE window. Do not need to install additional modules, unlike Get-ADUser

 # Create searcher object  
 $Domain = "sub.domain.com"  
 $ADsPath = [ADSI]"LDAP://$Domain"  
 $searcher = New-Object System.DirectoryServices.DirectorySearcher($ADsPath)  
 $searcher.SearchScope = "Subtree"  
 $searcher.PageSize = 1000  
 # Restrict properties to load  
 # $searcher.PropertiesToLoad.Add("name")  
 # $searcher.PropertiesToLoad.Add("sAMAccountName")  
 # $searcher.PropertiesToLoad.Add("employeeID")  
 # $searcher.PropertiesToLoad.Add("mail")  
 # $searcher.PropertiesToLoad.Add("userPrincipalName")  
 $searcher.PropertiesToLoad.Add("memberOf")  
 
 $searcher.Filter = "(&(objectClass=User)(samAccountName=username))"   
 $colResults = $searcher.FindOne()  
 
 $objItem = $colResults.Properties  
 $objItem.Item("memberOf") | foreach-object {  
   write-host $_  
 }  

Monday, July 31, 2017

PowerShell and Exchange Web Services (EWS) script to parse bounced emails

In my previous post, I had shared how to run PowerShell scripts on a locally configured Outlook profile, with Windows 10 powershell.

In this post, we will be making use of EWS to connect to an exchange server, impersonate a system maibox, download the emails and parsing the email body to extract the bounced email recipient.

References:
https://goodworkaround.com/2015/01/29/powershell-and-ews-managed-api/
https://msdn.microsoft.com/en-us/library/office/jj900168(v=exchg.150).aspx
https://www.linkedin.com/pulse/how-use-date-range-search-query-ews-managed-api-using-sunil-chauhan

What you need:
Microsoft Exchange Web Services API (download from nuget)

If you do not know which version of Exchange server your outlook profile is hosted on, refer to this article:

The script will attempt to detect a pre-embedded header. I find that this is the easiest way of detection since I have control over the email sending mechanism as well.
Example: in my email sending script (vbs sample here), I embed a header field
With Flds
' Set custom header so that the email can be easily read from bounce back addresses
.Item("urn:schemas:mailheader:x-CustomHdr") = strRecipientEmail
.Update
End With

Full source code:

Friday, July 28, 2017

PowerShell script (client machine) to parse bounced emails from Outlook

PowerShell script tested on Windows 10, with Outlook 2016 installed.
This is only meant for machines with Outlook connected to at least one email.

The script will attempt to parse bounced emails based on certain text patterns and attempt to extract the recipient email from a custom header. Assuming the custom header is set during send time.
Emails are extracted and saved to a SQL server database by invoking a stored procedure.

 Clear-host  
 Add-Type -Assembly "Microsoft.Office.Interop.Outlook"  
 $Outlook = New-Object -ComObject Outlook.Application  
 $Namespace = $Outlook.GetNameSpace("MAPI")  
 $mb = $Namespace.Folders | ?{$_.name -match "testabc@test.com"}    
 $Inbox = $mb.Folders | ?{$_.Name -match "Inbox"}    
 
# Clear deleted items > 30 days  
 $cutOff = (get-date).AddDays(-30)  
 $DeletedItems = $mb.Folders | ? { $_.Name -match 'Deleted Items' };  
 Foreach($e in $DeletedItems.Items){  
   if ($item.SentOn -gt $cutOff) {  
     $e.delete()  
   }  
 }  
 
# A bug in Outlook 2013 and 2016 will not display bounced emails properly  
 $uEnc = New-Object System.Text.UnicodeEncoding  
 $enc = [system.Text.Encoding]::UTF8  
 $dataSource = "dbservername"  
 $database = "dbname"  
 $dbUser = "user"  
 $pwd = "pwd"  
 $connectionString = "Data Source=$dataSource; User Id=$dbUser; Password=$pwd; Initial Catalog=$database"  
 $connection = new-object system.data.SqlClient.SQLConnection($connectionString)  
 $connection.Open()  
 #---------------------------------------------------------------------------------  
 # Function to pass in SQL query and return results as a table  
 #---------------------------------------------------------------------------------  
 function Invoke-SQL {  
   param(  
     [string] $sqlCommand = $(throw "Please specify a query.")  
    )  
   $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)  
      if ($command.ExecuteNonQuery() -ne 1)  
      {  
           Write-Host "Failed to execute SQL: $sqlCommand";  
      }  
 }  
 function Update-InvalidEmail  
 {  
   param(  
     [string] $email,  
     [string] $subject  
   )  
   If ($email.length -gt 100)  
   {  
     $email = $email.Substring(0,100)  
   }   
   If ($subject.length -gt 500)  
   {  
     $subject = $subject.Substring(0,500)  
   }   
      $email = $email.Replace("'", "''")  
   $subject = $subject.Replace("'", "''")  
      $strSQL = "sp_UpdateInvalidEmails '$email', '$subject'"  
   $dt = Invoke-SQL -sqlCommand $strSQL -returnResults $false  
   $dt  
 }  
 #checks newest messages  
 $Inbox.items | select -first 100 | foreach {  
   $subject = $_.Subject  
   $body = $enc.GetString($uEnc.GetBytes($_.Body))  
   if ($body -like "*Delivery has failed to these recipients*") {  
     write-host "failed delivery detected" -ForegroundColor Cyan  
     # look for lines like this: x-CustomHdr: email@test.com  
     # x-CustomHdr is a custom header 
     $regex = '\sx-CustomHdr:\s*([\w_.+-]+@[\w-]+\.[\w-.]+)\s'  
     $found = $body -match $regex  
     if ($found) {  
       $emailAddr = $matches[1]  
       write-host $emailAddr  
       Update-InvalidEmail -email $emailAddr -subject $subject  
     }  
   }  
   $_.Delete()  
 }  
 $connection.Close()  
 $connection.Dispose()  

Wednesday, January 4, 2017

PowerShell SharePoint to cancel workflows

$ver = $host | select version
if ($ver.Version.Major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"}
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$TargetWeb = "http://sharepoint/"
$TargetLibrary = "Library"
$Filename = 133 # the item ID
 
$MyWeb = Get-SPWeb $TargetWeb
$list = $MyWeb.Lists[$TargetLibrary]
$item = $list.GetItemById($Filename)

foreach ($wf in $item.Workflows) {
#Cancel Workflows      
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);    
}

WRITE-HOST "Discarded workflows"

Tuesday, January 3, 2017

SharePoint and PowerShell: Updating an individual user profile properties

When a user cannot be found from SharePoint central administration by going to Service Applications - User Profile Service - Manage User Profiles, it is likely that this user had some synchronization issues that is preventing detection from the UI.

In my situation the user was originally sync'd from Active Directory, but we had some OU changes and broke the hierarchy.
It's PowerShell to the rescue!

This example will retrieve a user profile from the web application, and updates the preferred name and user manager.

#Set up default variables
$mySiteUrl = "http://mysites"
$adAccount = "DOMAIN\username"
$upAttribute = "PreferredName"
$upAttributeValue = "My New Name"

#Get site objects and connect to User Profile Manager service
$site = Get-SPSite $mySiteUrl
$context = Get-SPServiceContext $site
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)

#Check to see if user profile exists
if ($profileManager.UserExists($adAccount))
{
    #Get user profile and change the value
    $up = $profileManager.GetUserProfile($adAccount)
    $up["PreferredName"]
    $up["Manager"]
    
    #$up["PreferredName"].Value = $upAttributeValue
    #$up.Commit()

    $up["Manager"].Value = "DOMAIN\manager"
    $up.Commit()
}
else
{
    write-host "Profile for user"$adAccount "cannot be found"
}


#Dispose of site object
$site.Dispose()

Tuesday, August 23, 2016

Calling AgilePoint web services with PowerShell

AgilePoint has 2 main APIs that are really handy - Workflow.asmx and Admin.asmx. You could also access it via REST.
Today I'm going to show an example of how you could batch reassign tasks to users by making use of the workflow web service.

The services could be found here.
  • Workflow API - http://[qualified machine name]:[port]/[AgilePoint virtual directory]/workflow.asmx?WSDL
  • Administration API - http://[qualified machine name]:[port]/[AgilePoint virtual directory]/admin.asmx?WSDL

With PowerShell here is a very straightforward example of a classic web service that accepts simple data types.
Using a CSV file that contains user account mapping from DOMAIN1\user to NEWDOMAIN\user, first declare the variables you need. Here is a sample CSV

oldlogin,newlogin
DOMAIN1\user1,NEWDOMAIN\user1new
DOMAIN1\user2,NEWDOMAIN\user2new

 #****************************************************  
 # Variables  
 #****************************************************  
 $username = "DOMAIN\admin"  
 $password = "Password"  
 $wsWorkflowUrl = "http://agilepointserver:8000/AgilePointServer/Workflow.asmx?WSDL"  
 $wsAdminUrl = "http://agilepointserver:8000/AgilePointServer/Admin.asmx?WSDL"  
 $csvFile = "Users.csv"  


Then, create the credentials object and connect to the webservice. PowerShell has a built-in WebServiceProxy class which is really handy.

 #****************************************************  
 # Credentials and proxy to connect to web service  
 #****************************************************  
 $cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))  
 $workflowProxy = New-WebServiceProxy -Uri $wsWorkflowUrl -Credential $cred  
 $adminProxy = New-WebServiceProxy -Uri $wsAdminUrl -Credential $cred  

In order to consume the service, here is a function to search for tasks assigned to a user, list all tasks, and reassign it to the new (migrated) user. It makes use of GetWorkListByUserID and ReassignWorkItem services.

 Function Reassign-AgilePointTasks ($originalUser, $migratedUser)   
 {  
   $response = $workflowProxy.GetWorkListByUserID($originalUser, "Assigned;Overdue")  
   ForEach ($item in $response) {  
     # Reassigns each task to the migrated user account in AgilePoint.  
     Write-Host "Reassigning task $($item.Name) $($item.WorkItemID)" -foregroundcolor "Yellow"  
     $reassign = $workflowProxy.ReassignWorkItem($item.WorkItemID, $migratedUser)  
     $textLogFileOK = "Reassignment to $($reassign.UserID) complete. $($reassign.Error)"  
        Add-Content -path $LogFileOK -value $textLogFileOK  
     Write-Host "Reassignment to $($reassign.UserID) complete. $($reassign.Error)" -backgroundcolor "Green"  
   }    
 }  

Finally, put all the pieces together by looping through the csv file, and reassigning the tasks user by user:

 #****************************************************  
 # Start Bulk AgilePoint migration  
 #****************************************************  
 Import-Csv $csvFile | ForEach-Object{  
         $originalUser = $_.oldlogin  
         $migratedUser = $_.newlogin  
         Reassign-AgilePointTasks -originalUser $originalUser -migratedUser $migratedUser  
         Write-Host "Migrated User " + $originalUser + " to " + $migratedUser  
}   

And we're done!

Wednesday, August 17, 2016

SharePoint online: Add site collection administrator using PowerShell

Prerequisites: You need Microsoft SharePoint Online Management Shell installed on your machine.

Script:

 $loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")  
 $loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")  
 $loadInfo3 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")  
 #Must be SharePoint Administrator URL  
 $webUrl = "https://tenant-admin.sharepoint.com"  
 $username = "admin@tenant.onmicrosoft.com"  
 $password = "password"  
 $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)  
 Connect-SPOService -Url $webUrl -Credential $cred  
 $site = Get-SPOSite -Identity https://tenant-my.sharepoint.com/personal/mysites_domain_com  
 Set-SPOUser -Site $site.Url -LoginName username@email.com -IsSiteCollectionAdmin $true  

Wednesday, August 10, 2016

PowerShell: Pull AD user information from multiple forests into CSV

Script example to discover the forests available on a domain, and retrieve user information, outputting in a CSV format. It makes use of System.DirectoryServices interface so there is no need to be a domain administrator or install additional ActiveDirectory components/features. All you need is Windows running PowerShell. I tested this on a 64bit machine.

 # Get the user's Distinguished Name   
 Function Get-UserInfo ()   
 {   
   $Target = @()  
   #Get Domain List  
   $objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()  
   $DomainList = @($objForest.Domains | Select-Object Name)  
   $Domains = $DomainList | foreach {$_.Name}  
   foreach($Domain in ($Domains))  
   {  
    Write-Host "Checking $Domain" -fore red  
    $ADsPath = [ADSI]"LDAP://$Domain"  
    $searcher = New-Object System.DirectoryServices.DirectorySearcher($ADsPath)  
    $searcher.Filter = "(&(objectClass=User)(extensionAttribute1>=1)(company=SAMPLEFILTER))"   
    $searcher.SearchScope = "Subtree"  
    $searcher.PageSize = 1000  
    $searcher.PropertiesToLoad.Add("name")  
    $searcher.PropertiesToLoad.Add("sAMAccountName")  
    $searcher.PropertiesToLoad.Add("mailNickname")  
    $searcher.PropertiesToLoad.Add("altRecipient")  
    $searcher.PropertiesToLoad.Add("extensionAttribute1")  
    $searcher.PropertiesToLoad.Add("co")  
    $colResults = $searcher.FindAll()   
    foreach ($objResult in $colResults)  {
      $objItem = $objResult.Properties  
      $objUser = new-object System.Object   
      $objUser | Add-Member -MemberType NoteProperty -Name "userName" -Value ([string]$objItem.Item("name"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "login" -Value ([string]$objItem.Item("sAMAccountName"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "altRecipient" -Value ([string]$objItem.Item("altRecipient"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "mailAccount" -Value ([string]$objItem.Item("mailNickname"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "customID" -Value ([string]$objItem.Item("extensionAttribute1"))  
      $objUser | Add-Member -MemberType NoteProperty -Name "country" -Value ([string]$objItem.Item("co"))  
      $Target += $objUser  
   }  
 }  
   $Target | select userName, login, alternateRecipient, mailAccount, customID, co | Export-csv "c:temp\QueryUser.csv"  
 }   
 Get-UserInfo  

Tuesday, February 2, 2016

PowerShell to upload a file into multiple sites under Project Web App (Office 365)

This is a powershell script custom written to upload an Excel report to multiple Project Online sites, but you could easily customize it to suit your own purposes. The same method works on Office 365 and SharePoint Online sites.

Prerequisites:
You will need to install the SharePoint 2013 client components on your client machine. I am running it on Windows 7 so I am actually using the PowerShell 64 bit version and 64bit client components.

 # Load SharePoint Client  
 Add-Type –Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"   
 Add-Type –Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"   

I am using the newest version on Project online, hence the 16 hive. 15 hive works as well!

Tuesday, January 26, 2016

PowerShell to update and refresh Excel data connections

Scenario:
You have multiple Excel files that applies the same template and formatting, but uses different data sources.
*** My requirement was to replace oData connections. I needed a simple script that would open an Excel file, loop through the data connections, and replace the data connection string.

Tested on Excel 2013, run PowerShell 64bit using Windows 7 Pro.

Wednesday, January 13, 2016

PowerShell script to list and export top navigation links

This PowerShell snippet will parse a single site for the top or global navigation links, display in the shell window, and output to an XML file in the following format:

 <Navigation>  
 <Group Title="Regions" Url="http://regions">  
 <Link>  
      <Name>Asia Pacific</Name>  
      <Url>http://apac</Url>  
      <Target />  
 </Link>  
 <Link>  
      <Name>EMEA</Name>  
      <Url>http://emea</Url>  
      <Target />  
 </Link>  
 <Link>  
      <Name>US</Name>  
      <Url>http://us</Url>  
      <Target />  
 </Link>  
 </Group>  
</Navigation>  

Tuesday, October 20, 2015

PowerShell: SharePoint 2010 Add top/Global navigation links and sublinks

This works for SharePoint 2010 sites with the Publishing feature enabled.
Before getting started, populate the header, title and URLs in an XML file (I am saving this in a file called topNav.xml).

Sample format:

 <Navigation>  
      <Group Title="Sites">  
           <Link>  
                <Name>Asia Pacific</Name>  
                <Url>http://asiapac</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Canada</Name>  
                <Url>http://canada</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Europe</Name>  
                <Url>http://eu</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Japan</Name>  
                <Url>http://japan</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Penang</Name>  
                <Url>http://penang</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>United States</Name>  
                <Url>http://states</Url>  
                <Target />  
           </Link>  
      </Group>  
 </Navigation>  

And here is the powerShell script to grab the values and populate the Global Navigation section.

Thursday, October 15, 2015

PowerShell: Update target Audience of a SharePoint 2010 Web Part

 # Get reference to the SPSite object  
 $SPWeb = Get-SPWeb "http://sharepoint"  
 # Get reference to the landing page. Since it is a publishing site so default.aspx is the landing page   
 $page = $SPWeb.GetFile("Pages/index.aspx")   
 ### Uncomment the lines below to perform the update  
 #$page.CheckOut()   
 # //Get reference to the webpartmanager class   
 $webpartmanager = $SPWeb.GetLimitedWebPartManager("Pages/index.aspx", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)    
 # Double check the web part that you wish to update. Iterate through webparts in webpartmanager class   
 for ($i=0;$i -lt $webpartmanager.WebParts.Count;$i++)   
 {    
      #write-host $webpartmanager.WebParts[$i].title  
      # Check for the name of required web part    
      if($webpartmanager.WebParts[$i].title -eq "Content Query Web Part")    
      {    
           #Get reference to the web part   
           $wp = $webpartmanager.WebParts[$i];   
           write-host $wp.title " " $i  
           # If there is any existing filter, copy it  
           write-host $wp.AuthorizationFilter  
           # In the filter (empty: ;;;;;;), first two semicolons: individual users as target audience; second two semicolons: distribution list; last two semicolons: can be replaced to include sharepoint groups    
           # e.g. "174e7e9d-ff39-4856-85a6-9247b02e59fb,124f1234-3998-4b54-83d1-abc4048fb9b4;;;;"  
           ### Optionally perform direct update while in for loop  
           # Other properties e.g. chrome property   
           #$wp.ChromeType="TitleAndBorder";   
           # Save changes to webpartmanager. This step is necessary. Otherwise changes wont be reflected   
           #$webpartmanager.SaveChanges($wp);   
  }    
  }    
 ### Uncomment the lines below to perform the update  
 #$wp = $webpartmanager.WebParts[26];  
 #write-host "begin update: " $wp.Title  
 #$wp.AuthorizationFilter = "174e7e9d-ff39-4856-85a6-9247b02e59fb,124f1234-3998-4b54-83d1-abc4048fb9b4,3a87dc31-9067-4996-b4c2-5efc6ff3eab7,68d2a840-bdbb-44ee-aacd-395b5551c473,7add71c2-dbea-4218-b8ff-f6b112f225e4,577550be-616e-41cd-90a4-493c030ddd72,9f113155-7c70-4d18-9417-851d82ba8b6a,c664006b-ec7f-4798-9acc-c48766be68a8,e26f7ece-615c-474d-9db9-0f60953e113a,ee912564-4f77-43c4-aced-55d387bc4e8e,51d2b9df-7ca3-42ad-a307-f9fdf28fe417,59500291-5912-47c0-b6a2-9c9adf24f2da;;;;";  
 #$webpartmanager.SaveChanges($wp);  
 #write-host "saving webpart target audience done...";  
 ### Uncomment the lines below to check in and Publish the page   
 #$page.CheckIn("Update Audience(batch powershell)")   
 #$page.Publish("Update Audience batch powershell)")   
 #$SPWeb.Update();    
 # Dispose SPWeb object   
 $SPWeb.Dispose();   

Wednesday, September 30, 2015

PowerShell list SharePoint Global Navigation headers and subheader links

This script will traverse the top navigation bar links in a SharePoint site and retrieve all the main headers plus dropdown links, and optionally list the link URLs.

Tried on SharePoint publishing sites.
How do you know if publishing is turned on?
If you see the Navigation link instead of Top Link Bar / Quick Launch, the feature is turned on.


Wednesday, September 9, 2015

SharePoint PowerShell: Adding complex rules to existing audience

Here is a PowerShell script to modify an existing Audience.

As you know, in SP2010, audience rules configured from the Central Administration can only have 2 choices:
1. Meet any condition listed
2. Meet ALL conditions listed

So if I want to have more complex conditions like nested conditions, I will either need to write a program (C#) to do it, or run some powershell commands in the web front end.

DO take note that once an audience is programmatically modified, you WILL NOT BE ABLE TO MAKE CHANGES from the Central Administation console anymore.

Sample script below:


Tuesday, June 23, 2015

SharePoint 2010 PowerShell: Batch assign permissions to each list item

PowerShell script to add permissions to all items in a list or library, where each item already has its unique set of permissions. Useful when you have hundreds of items in your library and can't be bothered to assign one by one.

Tuesday, June 16, 2015

SharePoint 2010 "Add to My Links" error: Page not found

Today I came across an interesting issue where users from a certain remote location were reporting a 'Page not found' error when trying to use 'Add to My Links' for documents stored under mysites.

Interestingly, the URL was malformed each time they attempted to click on the function.
It would end up looking like http://_vti_bin/portalapi.aspx?cmd=PinToMyPage&IconUrl=/_layouts/images/null&ListViewURL=xxxxxxxx 

Monday, February 23, 2015

SharePoint PowerShell - Set Site Collection Owner

Set-SpSite "http://sharepoint" -owneralias "DOMAIN\username"
Set-SpSite "http://sharepoint" -SecondaryOwnerAlias "DOMAIN\username2"

or alternatively, set the secondary site collection owner to null.

Set-SpSite "http://sp2010:90" -SecondaryOwnerAlias $null

Wednesday, February 11, 2015

SharePoint PowerShell: Recursively checkin files in a folder

This is a script that will try to parse a certain folder in a SharePoint 2010 site and recursively check for files that are checked out.
If found, the files would be checked in,

This is useful in situations where you are unable to move files and folders because someone had the files checked out.

Tuesday, September 16, 2014

SharePoint powershell to cancel workflows

I got stuck into a situation where the workflows in SharePoint were stuck during the "In Progress" stage, and there was no way to cancel the workflow from the UI.

After googling around, I found a simple powershell solution and adapted it slightly to suit my needs.

The concept is very simple - Load the site, load the library, and either traverse all items, or retrieve a single item based on the ID. For that item, loop through the workflows and cancel it!

Related Posts Plugin for WordPress, Blogger...