Wednesday, August 29, 2012

Functions in ps1 files

To call a function from a ps1 file you have to have it loaded in the MyFunctions module.

The module can be found here:
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\MyFunctions

Add the function in the MyFunctions.psm1 file (have to run Notepad++ as admin in order to edit) or edit the one in C:\Powershell and copy over top.

Then add this line into the ps1 file:
Import-Module MyFunctions

To view all functions in the MyFunctions module run this command in Powershell window:
Get-Command -module MyFunctions




Run ps1 Powershell files

Open SharePoint 2010 Management Shell (run as administrator)

cd \
.\Powershell\NameOfFile.ps1

Put functions in there rather than having to copy paste from txt file.

Currently have ps1 files for:
Updating Photo Store - sync images to SharePoint from AD
Update AD Group Work Email attribute - doesn't sync correctly from AD
Profile Sync - user attributes don't get updated with automatic sync sometimes

Update User Information for an AD Group email in SharePoint...must be set for Group Alerts

If email won't sync in from AD correctly.

Open SP Management Shell (Powershell) and copy and paste:

function Sync-SPGroupEmail([string]$userName, [string]$email) {
  Get-SPSite -Limit All | foreach {
    $web = $_.RootWeb
    if ($_.WebApplication.UseClaimsAuthentication) {
      $claim = New-SPClaimsPrincipal $userName -IdentityType WindowsSamAccountName
      $user = $web | Get-SPUser -Identity $claim -ErrorAction SilentlyContinue
    } else {
      $user = $web | Get-SPUser -Identity $userName -ErrorAction SilentlyContinue
    }
    if ($user -ne $null) {
      $web | Set-SPUser -Identity $user -SyncFromAD
     
      $list = $web.Lists["User Information List"]
      $query = New-Object Microsoft.SharePoint.SPQuery
      $query.Query = "<Where><Eq><FieldRef Name='Name' /><Value Type='Text'>$userName</Value></Eq></Where>"
      foreach ($item in $list.GetItems($query)) {
        $item["EMail"] = $email
        $item.SystemUpdate()
      }
    }
    $web.Dispose()
    $_.Dispose()
  }
}

Or can run function above from C:\Powershell\SPGroupEmail.ps1

cd \
.\Powershell\SPGroupEmail.ps1

Then put in:

Sync-SPGroupEmail "PMC1\group_name" "test@phmic.com"

This Work e-mail must be set for Alerts to be sent to AD groups from SharePoint Lists.



Reference Link