Skip to content

Instantly share code, notes, and snippets.

@MatsAnd
Last active May 4, 2020 12:51
Show Gist options
  • Select an option

  • Save MatsAnd/5d575931896716ee73cc8a1d5d045621 to your computer and use it in GitHub Desktop.

Select an option

Save MatsAnd/5d575931896716ee73cc8a1d5d045621 to your computer and use it in GitHub Desktop.
PowerShell script to update Sharepoint user profile with properties from local Active Directory
Import-Module Logger # https://github.com/vtfk/Logger
Add-LogTarget -Name Console
Add-LogTarget -Name CMTrace -Configuration @{ Path = "SetSPOUserProperties" }
Write-Log -Message "Start script.. Connecting to Sharepoint PnP"
# Connect Sharepoint PnP
Connect-Office365 -SharePointPnP -SharePointTenantName "vtfk" -Target "<azure-user>" -ErrorAction Stop
Write-Log -Message "Connected! Get employees from AD..."
# Get all employeeeees - Not completely correct
$employees = .\Get-VTFKADUser -Domain login.top.no -OnlyAutoUsers
$employeesCount = $employees.Count
Write-Log -Message "$employeesCount employees loaded from AD"
# Loop-de-loop
for($i = 0; $i -lt $employeesCount; $i++)
{
$employee = $employees[$i]
$current = $i + 1
try
{
Write-Log -Message "[$current / $employeesCount] - $($employee.UserPrincipalName) - Set PnPUserProfileProperties - State = $($employee.State), extAttr7 = $($employee.extensionAttribute7)"
# Set custom sharepoint properties, State and extAttr7 if they have value.
if($employee.State) {
Set-PnPUserProfileProperty -Account $employee.UserPrincipalName -PropertyName 'State' -Value $employee.State
}
if($employee.extensionAttribute7) {
Set-PnPUserProfileProperty -Account $employee.UserPrincipalName -PropertyName 'extAttr7' -Value $employee.extensionAttribute7
}
}
catch
{
Write-Log -Message "[$current / $employeesCount] - $($employee.UserPrincipalName) - Unable to set PnPUserProfileProperties: $($_.Exception.Message)" -Exception $_.Exception -Level WARNING
}
}
Disconnect-PnPOnline
Write-Log -Message "Done!"
[CmdletBinding()]
param(
[ValidateSet("login.top.no","skole.top.no")]
[Parameter(Mandatory = $true)]
[String] $Domain,
[String] $Filter = "*",
[String[]] $Properties = "*",
[Switch] $OnlyAutoUsers
)
$SearchBase = "OU=USERS,OU=VTFK,DC=$($Domain.ToUpper().Split(".") -join ",DC=")"
if($OnlyAutoUsers)
{
$SearchBase = "OU=AUTO USERS,$SearchBase"
}
return Get-ADUser -Server $Domain -Filter $Filter -SearchBase $SearchBase -Properties $Properties
[CmdletBinding()]
param (
[Parameter()]
[switch]$Exchange,
[Parameter()]
[switch]$AzureAD,
[Parameter()]
[switch]$MSOnline,
[Parameter()]
[switch]$SecurityAndCompliance,
[Parameter()]
[switch]$SharePoint,
[Parameter()]
[switch]$SharePointPNP,
[Parameter()]
[string]$SharePointTenantName,
[Parameter()]
[switch]$SkypeForBusiness,
[Parameter()]
[switch]$Teams,
[Parameter(Mandatory = $True, ParameterSetName = "PSCredential")]
[PSCredential]$Credential,
[Parameter(Mandatory = $True, ParameterSetName = "WindowsCredential")]
[string]$Target,
[Parameter(Mandatory = $True, ParameterSetName = "MFA")]
[switch]$MFA,
[Parameter(ParameterSetName = "MFA", HelpMessage = "Only applicable for service 'Exchange' and 'SecurityAndCompliance'")]
[string]$UserPrincipalName
)
if (!$MFA)
{
# get credential
if ([string]::IsNullOrEmpty($Target) -and !$Credential)
{
Write-Verbose "Requesting credentials from user"
$_credential = Get-Credential -Message "Provide credentials for Office 365"
}
elseif (![string]::IsNullOrEmpty($Target))
{
if (!(Get-Command -Name "Get-StoredCredential" -ErrorAction SilentlyContinue))
{
Write-Error "Requires CredentialManager Module to access Windows Credential Manager!`nInstall Module with: 'Install-Module -Name CredentialManager'" -ErrorAction Stop
}
Write-Verbose "Getting credential from Windows Credential Manager for target '$Target'"
$_credential = Get-StoredCredential -Target $Target
}
elseif ($Credential)
{
Write-Verbose "Copying given credential to local variable"
$_credential = $Credential
}
if (!$_credential)
{
Write-Error "Credentials not found" -ErrorAction Stop
}
else
{
Write-Verbose "Using credential with username '$($_credential.UserName)'"
}
}
# stop if no module is given
if (!$Exchange -and !$AzureAD -and !$MSOnline -and !$SecurityAndCompliance -and !$SharePoint -and !$SharePointPNP -and !$SkypeForBusiness -and !$Teams)
{
Write-Error "Specify at least one module" -ErrorAction Stop
}
# connect to Exchange
if ($Exchange)
{
$service = "Exchange Online"
if (!$MFA)
{
Write-Verbose "Connecting to $service"
if (!(Confirm-Connectivity -Service $service))
{
Connect-ExchangeOnline -Credential $_credential
if ($null -ne (Get-PSSession | Where-Object { $_.ConfigurationName -like "*Exchange*" }))
{
Set-WindowTitle -Service $service
}
}
}
else
{
if (!(Confirm-Connectivity -Service $service))
{
Connect-ExchangeOnline -UserPrincipalName $UserPrincipalName
$exchSession = Get-PSSession | Where-Object { $_.ConfigurationName -like "*Exchange*" }
if ($null -ne $exchSession)
{
Set-WindowTitle -Service $service
}
}
}
}
# connect to AzureAD
if ($AzureAD)
{
$service = "Azure AD"
if (!(Get-Command -Name "Get-AzureADUser" -ErrorAction SilentlyContinue))
{
Write-Error "Requires AzureAD Module!`nInstall Module with: 'Install-Module -Name AzureAD'" -ErrorAction Stop
}
$connectionSplat = @{}
if (!$MFA)
{
Write-Verbose "Connecting to $service"
$connectionSplat.Add("Credential", $_credential)
}
else
{
Write-Verbose "Connecting to $service (MFA)"
}
if (!(Confirm-Connectivity -Service $service))
{
if ($null -ne (Connect-AzureAD @connectionSplat -ErrorAction Stop))
{
Set-WindowTitle -Service $service
}
}
}
# connect to MSOnline
if ($MSOnline)
{
$service = "MSOnline"
if (!(Get-Command -Name "Get-MsolUser" -ErrorAction SilentlyContinue))
{
Write-Error "Requires MSOnline Module!`nInstall Module with: 'Install-Module -Name MSOnline'" -ErrorAction Stop
}
$connectionSplat = @{}
if (!$MFA)
{
Write-Verbose "Connecting to $service"
$connectionSplat.Add("Credential", $_credential)
}
else
{
Write-Verbose "Connecting to $service (MFA)"
}
if (!(Confirm-Connectivity -Service $service))
{
Connect-MsolService @connectionSplat -ErrorAction Stop
if ($null -ne (Get-MsolCompanyInformation -ErrorAction SilentlyContinue))
{
Set-WindowTitle -Service $service
}
}
}
# connect to SecurityAndCompliance
if ($SecurityAndCompliance)
{
$service = "Security and Compliance Center"
if (!$MFA)
{
Write-Verbose "Connecting to $service"
if (!(Confirm-Connectivity -Service $service))
{
$secAndCompSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $_credential -Authentication Basic -AllowRedirection -ErrorAction Stop
# import module into global session
Import-Module (Import-PSSession $secAndCompSession -AllowClobber -ErrorAction Stop -Verbose:$False) -Global -Force -Verbose:$False
if ($null -ne (Get-PSSession | Where-Object { $_.ConfigurationName -like "*Exchange*" }))
{
Set-WindowTitle -Service $service
}
}
}
else
{
$exchModule = (Get-ChildItem -Path "$Env:LOCALAPPDATA\Apps\2.0\*\CreateExoPSSession.ps1" -Recurse -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Target -First 1)
if ($null -eq $exchModule)
{
Write-Error "The Exchange Online MFA Module was not found!`nhttps://docs.microsoft.com/en-us/powershell/exchange/exchange-online/connect-to-exchange-online-powershell/mfa-connect-to-exchange-online-powershell?view=exchange-ps" -ErrorAction Stop
}
else
{
Write-Verbose "Connecting to $service (MFA)"
if (!(Confirm-Connectivity -Service $service))
{
$connectionSplat = @{}
# set current location to top of the stack
Push-Location -StackName Scripts
Import-Module $exchModule -Global -Force -Verbose:$False
if ($UserPrincipalName)
{
$connectionSplat.Add("UserPrincipalName", $UserPrincipalName)
}
try
{
Connect-IPPSSession @connectionSplat -Verbose:$False -ErrorAction Stop -WarningAction SilentlyContinue
}
catch
{
Write-Host $_ -ForegroundColor Red
}
# set location back to orignial
Pop-Location -StackName Scripts
$secAndCompSession = Get-PSSession | Where-Object { $_.ConfigurationName -like "*Exchange*" }
if ($null -ne $secAndCompSession)
{
# import module into global session
Import-Module (Import-PSSession $secAndCompSession -AllowClobber -ErrorAction Stop -Verbose:$False -WarningAction SilentlyContinue) -Global -Force -Verbose:$False -WarningAction SilentlyContinue
Set-WindowTitle -Service $service
}
}
}
}
}
# connect to SharePoint
if ($SharePoint)
{
$service = "SharePoint Online"
if (!(Get-Command -Name "Get-SPOTenant" -ErrorAction SilentlyContinue))
{
Write-Error "Requires Microsoft.Online.SharePoint.PowerShell Module!`nInstall Module with: 'Install-Module -Name Microsoft.Online.SharePoint.PowerShell'" -ErrorAction Stop
}
if (!$SharePointTenantName)
{
Write-Error "Please provide your tenantname with -SharePointTenantName" -ErrorAction Stop
}
$sharePointUrl = "https://$SharePointTenantName-admin.sharepoint.com"
$connectionSplat = @{
"Url" = $sharePointUrl
}
if (!$MFA)
{
Write-Verbose "Connecting to $service with url '$sharePointUrl'"
$connectionSplat.Add("Credential", $_credential)
}
else
{
Write-Verbose "Connecting to $service with url '$sharePointUrl' (MFA)"
}
if (!(Confirm-Connectivity -Service $service))
{
Connect-SPOService @connectionSplat -ErrorAction Stop
if ($null -ne (Get-SPOTenant))
{
Set-WindowTitle -Service $service
}
}
}
# connect to SharePoint PnP
if ($SharePointPNP)
{
$service = "SharePoint Online PNP"
if (!(Get-Command -Name "Connect-PnPOnline" -ErrorAction SilentlyContinue))
{
Write-Error "Requires SharePointPnPPowerShellOnline Module!`nInstall Module with: 'Install-Module -Name SharePointPnPPowerShellOnline'" -ErrorAction Stop
}
if (!$SharePointTenantName)
{
Write-Error "Please provide your tenantname with -SharePointTenantName" -ErrorAction Stop
}
$sharePointUrl = "https://$SharePointTenantName-admin.sharepoint.com"
$connectionSplat = @{
"Url" = $sharePointUrl
}
if (!$MFA)
{
Write-Verbose "Connecting to $service with url '$sharePointUrl'"
$connectionSplat.Add("Credentials", $_credential)
}
else
{
Write-Verbose "Connecting to $service with url '$sharePointUrl' (MFA)"
$connectionSplat.Add("UseWebLogin", $true)
}
if (!(Confirm-Connectivity -Service $service))
{
try {
Connect-PnPOnline @connectionSplat -ErrorAction Stop
Set-WindowTitle -Service $service
}
catch {
Write-Error "Couldn't connect. Try again... :(" -ErrorAction Stop
}
}
}
# connect to SkypeForBusiness
if ($SkypeForBusiness)
{
$service = "Skype for Business Online"
if (!(Get-Command -Name "Get-AzureADUser" -ErrorAction SilentlyContinue))
{
Write-Error "Requires SkypeOnlineConnector Module!`nhttps://www.microsoft.com/en-us/download/details.aspx?id=39366" -ErrorAction Stop
}
$connectionSplat = @{}
if (!$MFA)
{
Write-Verbose "Connecting to $service"
$connectionSplat.Add("Credential", $_credential)
}
else
{
Write-Verbose "Connecting to $service (MFA)"
}
if (!(Confirm-Connectivity -Service $service))
{
$skypeSession = New-CsOnlineSession @connectionSplat -ErrorAction Stop
Import-Module (Import-PSSession $skypeSession -AllowClobber -ErrorAction Stop) -Global -Force
if ($null -ne (Get-CsOnlineDirectoryTenant))
{
Set-WindowTitle -Service $service
}
}
}
# connect to Teams
if ($Teams)
{
$service = "Teams"
if (!(Get-Command -Name "Get-Team" -ErrorAction SilentlyContinue))
{
Write-Error "Requires MicrosoftTeams Module!`nInstall Module with: 'Install-Module -Name MicrosoftTeams'" -ErrorAction Stop
}
$connectionSplat = @{}
if (!$MFA)
{
Write-Verbose "Connecting to $service"
$connectionSplat.Add("Credential", $_credential)
}
else
{
Write-Verbose "Connecting to $service (MFA)"
}
if (!(Confirm-Connectivity -Service $service))
{
if ($null -ne (Connect-MicrosoftTeams @connectionSplat -ErrorAction Stop))
{
Set-WindowTitle -Service $service
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment