Skip to content

Commit 381e9f7

Browse files
committed
update
1 parent 4486c44 commit 381e9f7

4 files changed

Lines changed: 690 additions & 178 deletions

File tree

Delta.Run.ex.ps1

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,32 @@
33
. .\MIM.syncservice.run.ma.ps1
44
. .\MIM.portal.funtions.OP.ps1
55

6+
function TriggerTemporalEventsJob{
7+
$startTime = [DateTime]::Now
8+
$log.Info("Start FIM_TemporalEventsJob")
9+
#"" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString > "C:\Script\Run\sqlpassword"
10+
#$sqlpassword = (New-Object System.Net.NetworkCredential "",((gc "C:\Script\Run\sqlpassword") | ConvertTo-SecureString)).Password
11+
#$resualt = start-SQLJob -ServerName "ServerName.se" -JobName "FIM_TemporalEventsJob" -StepName "step1" -Login "MIM-TaskRun" -LoginPassword $sqlpassword
12+
13+
#$resualt = start-SQLJob -ServerName "ServerName.se" -JobName "FIM_TemporalEventsJob" -StepName "step1"
14+
$resualt = start-SQLJobSQL -ServerName "ServerName.se" -JobName "FIM_TemporalEventsJob" -Wait
15+
16+
if($resualt -eq "last_run_outcome 1"){
17+
$log.Info("FIM_TemporalEventsJob run: $resualt")
18+
}else{
19+
$log.Error("FIM_TemporalEventsJob run: $resualt")
20+
}
21+
$log.Info("End FIM_TemporalEventsJob RunTime: {0}s",([DateTime]::Now - $startTime).TotalSeconds)
22+
}
23+
624
$ScriptstartTime = [DateTime]::Now
725

826
#Set up log
927
$Name = $MyInvocation.MyCommand.Name
10-
$logg = [NLog.LogManager]::GetLogger("MIM.syncservice.run.ma.$Name")
11-
$logg.Info("Start run $Name")
28+
$log = [NLog.LogManager]::GetLogger("MIM.syncservice.run.ma.$Name")
29+
$log.Info("Start run $Name")
1230

13-
if((Get-AnyMAInProgress)){ $log.Error("Agent running"); return }
31+
if((Get-AnyMAInProgress)){ $log.Error("Agent running in progress: '$((Get-AnyMAInProgress -List)[0])'"); return }
1432

1533
#Set up timer
1634
$timer = New-Object System.Timers.Timer
@@ -21,25 +39,38 @@ $timer.AutoReset = $false
2139

2240
#Set timeoutacction
2341
$Timeoutaction = Register-ObjectEvent -InputObject $timer -SourceIdentifier $Name -EventName Elapsed -Action {
24-
$logg.Error("Error Message")
42+
$log.Error("Run time exceeded time frame")
2543
#exit
2644
#[Environment]::Exit(0)
2745
}
2846
$timer.Enabled = $true
2947

48+
#Refresch-synchronizationRule
49+
$result = Refresch-synchronizationRule
50+
foreach($error in $result.Previews.error){
51+
$log.Error($error)
52+
}
3053

3154
#Run MAs
32-
Start-MA -maName "AD-MA" -profile "Delta Import"
55+
Start-MA -maName "AD-MA" -profile "Delta Import" -DontWait
56+
Start-MA -maName "AD2-MA" -profile "Delta Import"
57+
#while((Get-AnyMAInProgress)){sleep 5}
58+
do{ sleep 5; $log.Info("AnyMAInProgress: $(Get-AnyMAInProgress -List)") }While((Get-AnyMAInProgress))
59+
3360
Start-MA -maName "AD-MA" -profile "Delta Sync" -RunOnChange
61+
Start-MA -maName "AD2-MA" -profile "Delta Sync" -RunOnChange
3462
Start-MA -maName "AD-MA" -profile "Export" -RunOnChange
3563

3664
Start-MA -maName "MIMPortal-MA" -profile "Export" -RunOnChange
37-
While($PostProcessingCount -gt 0){ $PostProcessingCount = get-PostProcessingCount }
65+
do{ sleep 5; $log.Info("PostProcessingCount: $(get-PostProcessingCount)") }While((get-PostProcessingCount) -gt 0)
3866
Start-MA -maName "MIMPortal-MA" -profile "Delta Import"
39-
Start-MA -maName "MIMPortal-MA" -profile "Delta Sync" -RunOnChange
67+
Start-MA -maName "MIMPortal-MA" -profile "Delta Sync" -RunOnChange -CountChangeOn @(@{ Attribute = "extSyncStatusAD"; Threshold = 500; Ratio = 10 })
68+
4069

70+
$PurgeExecHistory = Run-PurgeExecHistory 14
71+
$log.Info($PurgeExecHistory)
4172

42-
#Unreg timeout
73+
#Unreg timeout event
4374
Unregister-Event $Name
4475

45-
$logg.Info("End RunTime: {0}s",([DateTime]::Now - $ScriptstartTime).TotalSeconds)
76+
$log.Info("End RunTime: {0}s",([DateTime]::Now - $ScriptstartTime).TotalSeconds)

MIM.portal.funtions.OP.ps1

Lines changed: 173 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11

2-
Add-PSSnapin FIMAutomation
3-
42
function get-FIMConfig{
53
<#
64
.SYNOPSIS
@@ -56,6 +54,9 @@ function get-FIMConfig{
5654
[switch]$SelectOnMulit
5755
)
5856
process{
57+
58+
Add-PSSnapin FIMAutomation
59+
5960
if([string]::IsNullOrEmpty($XpathFilter)){
6061
$XpathFilter = "/$ObjectType"
6162
if($ObjectID){
@@ -137,6 +138,8 @@ function set-FIMConfig{
137138
[switch]$ImportConfig
138139
)
139140
begin{
141+
Add-PSSnapin FIMAutomation
142+
140143
if(-NOT $Objects){
141144
if(test-path $ImportFileName){
142145
$Objects = ConvertTo-FIMResource -File $ImportFileName
@@ -240,6 +243,42 @@ function set-FIMConfig{
240243
}
241244
}
242245

246+
function Get-LithnetClient{
247+
param(
248+
$Hosturl
249+
)
250+
251+
if(-NOT (Test-Path (join-path ($PSScriptRoot) Lithnet.ResourceManagement.Client.dll)))
252+
{
253+
$FileName = "Lithnet.nuget.zip"
254+
Invoke-WebRequest "https://www.nuget.org/api/v2/package/Lithnet.ResourceManagement.Client/" -OutFile $FileName
255+
Add-Type -AssemblyName System.IO.Compression.FileSystem
256+
$zip = [System.IO.Compression.ZipFile]::OpenRead((join-path ($PSScriptRoot) $FileName))
257+
$zip.Entries|?{$_.FullName.StartsWith("lib/net40/")}|%{[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, (join-path ($PSScriptRoot) $_.Name), $true)}
258+
$zip.Dispose()
259+
rm $FileName
260+
}
261+
262+
Add-Type -Path (join-path ($PSScriptRoot) Lithnet.ResourceManagement.Client.dll)
263+
264+
try{
265+
if($Hosturl){ $client = new-object Lithnet.ResourceManagement.Client.ResourceManagementClient $Hosturl }
266+
lse{ $client = new-object Lithnet.ResourceManagement.Client.ResourceManagementClient }
267+
268+
}
269+
catch{
270+
if(-NOT $Global:DetectedAddress){
271+
. (join-path ($PSScriptRoot) "MIM.syncservice.funtions.OP.ps1")
272+
$Global:DetectedAddress = Get-FIMServiceHosturl
273+
}
274+
$Address = $Global:DetectedAddress
275+
276+
$client = new-object Lithnet.ResourceManagement.Client.ResourceManagementClient $Address
277+
}
278+
279+
return $client
280+
}
281+
243282
function get-BindingDescriptionConfig{
244283
param(
245284
$ObjectTypeName,
@@ -437,6 +476,9 @@ function add-Admin{
437476
[switch]$OverWriteSID
438477
)
439478
begin{
479+
480+
Add-PSSnapin FIMAutomation
481+
440482
#Get AD user
441483
$ADParam = @{
442484
Identity = $username
@@ -825,22 +867,12 @@ function new-NewGroupByCreteria{
825867
[parameter(Mandatory=$true)]
826868
[Guid]$Owner,
827869

828-
[switch]$Commit
870+
[switch]$Commit,
871+
872+
$Hosturl
829873
)
830874
begin{
831-
if(-NOT (Test-Path (join-path ($PSScriptRoot) Lithnet.ResourceManagement.Client.dll)))
832-
{
833-
$FileName = "Lithnet.nuget.zip"
834-
Invoke-WebRequest "https://www.nuget.org/api/v2/package/Lithnet.ResourceManagement.Client/" -OutFile $FileName
835-
Add-Type -AssemblyName System.IO.Compression.FileSystem
836-
$zip = [System.IO.Compression.ZipFile]::OpenRead((join-path ($PSScriptRoot) $FileName))
837-
$zip.Entries|?{$_.FullName.StartsWith("lib/net40/")}|%{[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, (join-path ($PSScriptRoot) $_.Name), $true)}
838-
$zip.Dispose()
839-
rm $FileName
840-
}
841-
842-
Add-Type -Path (join-path ($PSScriptRoot) Lithnet.ResourceManagement.Client.dll)
843-
$client = new-object Lithnet.ResourceManagement.Client.ResourceManagementClient
875+
$client = Get-LithnetClient -Hosturl $Hosturl
844876

845877
$FilterXml = "<Filter xmlns:xsd=`"http://www.w3.org/2001/XMLSchema`" xmlns:xsi=`"http://www.w3.org/2001/XMLSchema-instance`" Dialect=`"http://schemas.microsoft.com/2006/11/XPathFilterDialect`" xmlns=`"http://schemas.xmlsoap.org/ws/2004/09/enumeration`">{0}</Filter>"
846878
}
@@ -877,46 +909,91 @@ function get-PostProcessingCount{
877909
#>
878910
param(
879911
[DateTime]$Date = [datetime]::Now.AddDays(-1),
880-
[String]$Address,
881-
[switch]$DetectAddress
882-
912+
$Hosturl
883913
)
884914
begin{
885-
if(-NOT (Test-Path (join-path ($PSScriptRoot) Lithnet.ResourceManagement.Client.dll)))
886-
{
887-
$FileName = "Lithnet.nuget.zip"
888-
Invoke-WebRequest "https://www.nuget.org/api/v2/package/Lithnet.ResourceManagement.Client/" -OutFile $FileName
889-
Add-Type -AssemblyName System.IO.Compression.FileSystem
890-
$zip = [System.IO.Compression.ZipFile]::OpenRead((join-path ($PSScriptRoot) $FileName))
891-
$zip.Entries|?{$_.FullName.StartsWith("lib/net40/")}|%{[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, (join-path ($PSScriptRoot) $_.Name), $true)}
892-
$zip.Dispose()
893-
rm $FileName
894-
}
895-
896-
Add-Type -Path (join-path ($PSScriptRoot) Lithnet.ResourceManagement.Client.dll)
897-
#$client = new-object Lithnet.ResourceManagement.Client.ResourceManagementClient
898-
899-
if($DetectAddress){
900-
if(-NOT $Global:DetectedAddress){
901-
. (join-path (PWD) "MIM.syncservice.funtions.OP.ps1")
902-
$Global:DetectedAddress = Get-FIMServiceHosturl
903-
}
904-
$Address = $Global:DetectedAddress
905-
}
906-
907-
if($Address){ $client = new-object Lithnet.ResourceManagement.Client.ResourceManagementClient $Address }else{ $client = new-object Lithnet.ResourceManagement.Client.ResourceManagementClient }
915+
$client = Get-LithnetClient -Hosturl $Hosturl
908916
}
909917

910918
process{
919+
#^(NotFound|Denied|Validating|Canceling|Validated|Authenticating|Authenticated|Authorizing|Authorized|Failed|Canceled|Committed|CanceledPostProcessing|PostProcessing|PostProcessingError|Completed)$
920+
921+
911922
#$Request = $client.GetResources("/Request[RequestStatus = 'PostProcessing']")
912923
#$Request = $client.GetResources("/Request[RequestStatus = 'PostProcessing' or RequestStatus = 'Validating' or RequestStatus = 'Committed']")
913924
#$Request = $client.GetResources("/Request[(CreatedTime > op:subtract-dayTimeDuration-from-dateTime(fn:current-dateTime(), xs:dayTimeDuration('P1D'))) and ((RequestStatus = 'Validating') or (RequestStatus = 'PostProcessing') or (RequestStatus = 'Committed'))]")
914925
$DateString = $Date.ToUniversalTime().ToString("s")
915-
$Request = $client.GetResources("/Request[(CreatedTime > '$DateString') and ((RequestStatus = 'Validating') or (RequestStatus = 'PostProcessing') or (RequestStatus = 'Committed'))]")
926+
$Request = $client.GetResources("/Request[(CreatedTime > '$DateString') and ((RequestStatus = 'Validated') or (RequestStatus = 'Validating') or (RequestStatus = 'PostProcessing') or (RequestStatus = 'Committed'))]")
916927
$Request.Count
917928
}
918929
}
919930

931+
function start-SQLJobSQL{
932+
<#
933+
934+
#>
935+
param
936+
(
937+
[string]$ServerName,
938+
[string]$JobName = "FIM_TemporalEventsJob",
939+
[string]$Login,
940+
[string]$LoginPassword,
941+
[switch]$Wait
942+
)
943+
944+
begin{
945+
}
946+
947+
process{
948+
try{
949+
$connection = New-Object System.Data.SQLClient.SQLConnection
950+
$Connection.ConnectionString = "server={0};database=msdb;trusted_connection=true;" -f $ServerName
951+
952+
if($Login){
953+
$Connection.ConnectionString = "server={0};database=msdb;user id={1};password={2};" -f $ServerName,$Login,$LoginPassword
954+
}
955+
$connection.Open()
956+
957+
$cmd = New-Object System.Data.SQLClient.SQLCommand
958+
$cmd.Connection = $connection
959+
$cmd.CommandText = "exec msdb.dbo.sp_start_job '{0}'" -f $JobName
960+
961+
#Write-host "Executing job $JobName on $SQLServer"
962+
[void]$cmd.ExecuteNonQuery()
963+
sleep 3
964+
965+
if($Wait){
966+
$cmd = New-Object System.Data.SQLClient.SQLCommand
967+
$cmd.Connection = $connection
968+
#$cmd.CommandText = "msdb.dbo.sp_help_job @job_name='{0}', @execution_status = 4" -f $JobName
969+
$cmd.CommandText = "msdb.dbo.sp_help_job"
970+
[void]$cmd.Parameters.AddWithValue("@job_name",$JobName)
971+
[void]$cmd.Parameters.AddWithValue("@execution_status",4)
972+
#$cmd.Parameters.Add("@execution_status","Int").Value = 4
973+
#$cmd.Parameters.Add( "@results", "Int" ).Direction = "ReturnValue"
974+
$cmd.CommandType = "StoredProcedure"
975+
976+
#$cmd.ExecuteNonQuery()
977+
$reader = $cmd.ExecuteReader()
978+
979+
while(!$reader.Read())
980+
{
981+
#Write-host "Job is still executing. Sleeping..."
982+
sleep 1
983+
984+
$reader.Close()
985+
$reader = $cmd.ExecuteReader()
986+
}
987+
"$($reader.GetName(21)) $($reader[21])"
988+
$reader.Close()
989+
}
990+
$connection.Close()
991+
}Catch{
992+
return $_
993+
}
994+
}
995+
}
996+
920997
function start-SQLJob{
921998
<#
922999
.SYNOPSIS
@@ -927,12 +1004,16 @@ function start-SQLJob{
9271004
start-SQLJob -ServerName "sql.server.namn" -JobName "sql job name" -StepName "step1"
9281005
.EXAMPLE
9291006
start-SQLJob -ServerName "SQL01.adm.namn.se" -JobName "FIM_TemporalEventsJob" -StepName "step1"
1007+
https://www.microsoft.com/en-us/download/confirmation.aspx?id=56833
1008+
Get-Module -ListAvailable -Name SQLPS
9301009
#>
9311010
param
9321011
(
9331012
[string]$ServerName,
9341013
[string]$JobName,
9351014
[string]$StepName,
1015+
[string]$Login,
1016+
[string]$LoginPassword,
9361017
[switch]$DontWait
9371018
)
9381019

@@ -943,6 +1024,15 @@ function start-SQLJob{
9431024
process{
9441025
try{
9451026
$srv = New-Object Microsoft.SqlServer.Management.SMO.Server($ServerName)
1027+
if($Login){
1028+
$pass = ConvertTo-SecureString $LoginPassword -AsPlainText -Force
1029+
$securecred = New-Object System.Management.Automation.PSCredential ($Login, $pass)
1030+
1031+
$credential = get-Credential $securecred
1032+
$srv.ConnectionContext.LoginSecure = $false
1033+
$srv.ConnectionContext.Login = $Login
1034+
$srv.ConnectionContext.set_SecurePassword($credential.Password)
1035+
}
9461036
$job = $srv.jobserver.jobs[$JobName]
9471037
$step = $job.JobSteps[$StepName]
9481038

@@ -969,4 +1059,43 @@ function start-SQLJob{
9691059
return $_
9701060
}
9711061
}
972-
}
1062+
}
1063+
1064+
function Copy-PersistentFlow{
1065+
param
1066+
(
1067+
[string]$SourceDisplayName,
1068+
[guid]$SourceGuid,
1069+
[string]$TargetDisplayName,
1070+
[guid]$TargetGuid,
1071+
[switch]$InitialFlow,
1072+
$Hosturl
1073+
)
1074+
1075+
$client = Get-LithnetClient -Hosturl $Hosturl
1076+
1077+
if($SourceGuid){
1078+
$Source = $client.GetResource($SourceGuid)
1079+
}else{
1080+
$Source = $client.GetResourceByKey("SynchronizationRule","DisplayName",$SourceDisplayName)
1081+
}
1082+
1083+
if(!$Source){
1084+
throw "Error no Source found $SourceDisplayName $SourceGuid"
1085+
}
1086+
1087+
if($TargetGuid){
1088+
$Target = $client.GetResource($TargetGuid)
1089+
}else{
1090+
$Target = $client.GetResourceByKey("SynchronizationRule","DisplayName",$TargetDisplayName)
1091+
}
1092+
1093+
if(!$Target){
1094+
throw "Error no Target found $TargetDisplayName $TargetGuid"
1095+
}
1096+
1097+
write-host "Copy from '$($Source.DisplayName)' PersistentFlow to '$($Target.DisplayName)' PersistentFlow"
1098+
$Target.Attributes["PersistentFlow"].Value = $Source.Attributes["PersistentFlow"].Value
1099+
if($InitialFlow){ $Target.Attributes["InitialFlow"].Value = $Source.Attributes["InitialFlow"].Value }
1100+
$Target.Save()
1101+
}

0 commit comments

Comments
 (0)