#------------------------------------------------------------------------------------------------------- # Functions #------------------------------------------------------------------------------------------------------- #------------------------ function cupwdFile { param ($id, $Environment, $computer, $EnvironmentUser, $path) $cred = get-credential $id $cred.password|convertFrom-SecureString| % {$pwd=$_} $uid=$($cred.UserName) $uid=$uid.replace("\","-") $uid=$uid.replace("@","-") $fn = ("{0}\init-pwd-{1}-{2}-{3}-{4}.ps1" -f $path, $Environment, $computer, $EnvironmentUser, $uid) remove-item $fn -ErrorAction SilentlyContinue Add-Content -path $fn "# ***********************************************************************************************" Add-Content -path $fn "# Variables" Add-Content -path $fn "#ServiceAccount with secured password" Add-Content -path $fn "`$Acc1 = `"$($cred.UserName)`"" Add-Content -path $fn "`$pwd1 = `"$pwd`"" Add-Content -path $fn "# ***********************************************************************************************" write-host "encryption file $fn created" } $Delimiter = "," $ArrayDelimiter = "|" if (!$Environment) { Write-Host "please invoke first global domains first" exit } #------------------------ function Get-Hash { param ( [string]$Env, [string]$EnvUser, [string]$compi, [string]$id, [string]$path) $uid=$id.replace("\","-") $uid=$uid.replace("@","-") $fn = ("{0}\init-pwd-{1}-{2}-{3}-{4}.ps1" -f $path, $env, $compi, $EnvUser, $uid) write-host $fn if (!(Test-Path $fn)) { write-warning ("No hash exists in environment/computer {0}/{1} for EnvUser/userID {2}/{3}`n`nCreate hash file with .\create-ini-pwdfile.ps1 -id" -f $env,$compi, $envuser, $id) cupwdFile $id $Environment $compi $EnvUser $path } . $fn # check if we can decryp $pwdHash = ConvertTo-SecureString $pwd1 -ErrorAction SilentlyContinue -ErrorVariable E if (![string]::IsNullOrEmpty($e)) { write-Warning "$E" write-Warning "$user" cupwdFile $id $Environment $compi $EnvUser $path } return $pwd1 } #------------------------------------------------------------------------------------------------------- # #------------------------------------------------------------------------------------------------------- # logging function function Logging { param ( [string]$Msg="*", [string]$Logfile, [switch]$addtionalLogonly, [string]$addtionalLogFile = $addtionalLogFile, [switch]$NoTimeStamp, #no time stamp [Switch]$OutputToScreen, [ValidateSet("Black","DarkBlue","DarkGreen","DarkCyan","DarkRed","DarkMagenta","DarkYellow","Gray","DarkGray","Blue","Green","Cyan","Red","Magenta","Yellow","White")] [String]$ForegroundColor=(Get-Host).ui.RawUI.ForegroundColor, [ValidateSet("Black","DarkBlue","DarkGreen","DarkCyan","DarkRed","DarkMagenta","DarkYellow","Gray","DarkGray","Blue","Green","Cyan","Red","Magenta","Yellow","White")] [String]$BackgroundColor= "DarkBlue" #(Get-Host).ui.RawUI.BackgroundColor ) if ($ForegroundColor -eq "-1") {$ForegroundColor = "white"} if ($addtionalLogonly.IsPresent) { if (!(Test-Path $addtionalLogFile)) { Write-Output "Creating log file $addtionalLogFile" $addtionalLogFile = New-Item $addtionalLogFile -Type file } $datetime = (Get-Date).ToString('yyyyMMdd HH:mm:ss') if ($NoTimeStamp.IsPresent) { $StringToWrite = $Msg } else { $StringToWrite = "$datetime | $Msg" } #if ($OutputToScreen) {Write-Host $StringToWrite -ForegroundColor $ForegroundColor -BackgroundColor $BackgroundColor} Add-Content -Path $addtionalLogFile -Value $StringToWrite } else { if ($LogFile -eq "") { $LogFile = ('.\'+(Get-History -Id ($MyInvocation.HistoryId -1) | select StartExecutionTime).startexecutiontime.tostring('yyyyMMdd-HHmm')+'-'+[io.path]::GetFileNameWithoutExtension($MyInvocation.ScriptName)+'.log') } if (!(Test-Path $LogFile)) { Write-Output "Creating log file $LogFile" $LogFile = New-Item $LogFile -Type file } $datetime = (Get-Date).ToString('yyyyMMdd HH:mm:ss') $StringToWrite = "$datetime | $Msg" if ($OutputToScreen) {Write-Host $StringToWrite -ForegroundColor $ForegroundColor -BackgroundColor $BackgroundColor} Add-Content -Path $LogFile -Value $StringToWrite } } #------------------------------------------------------------------------------------------------------- # compare hash tables function checkHashEqual { param ($o, $n) $flag=$true $o.Keys | % { if ($o.Item($_) -ne $n.Item($_)) {$flag=$false}} return ,$flag } #------------------------------------------------------------------------------------------------------- # compare hash tables function createDictionaryFromCSV { param ( $csvFile ,$key ,$columns ,$Delim ,$descr ) $dic = New-Object 'System.Collections.Generic.Dictionary[String,String[]]' write-verbose "Loading data from $csvFile..." $data = Import-CSV $csvFile -Delimiter $Delim -Encoding UTF8 write-verbose "Creating data dictionary $descr..." $data | foreach { $arr = @() foreach ($col in $columns) { $arr += @($_."$col") } $dic.add($($_."$key").ToLower(),$arr) } $nbr = $dic.count write-verbose "Creating data dictionary $descr (records: $nbr)...done" return $dic } #------------------------------------------------------------------------------------------------------- # compare hash tables function createDictionary2FromCSV { param ( $csvFile ,$key ,$columns ,$Delim ,$descr ) $dic = @{} $dic2 = @{} $errList = @{} write-verbose "Loading data from $csvFile..." $data = Import-CSV $csvFile -Delimiter $Delim -Encoding UTF8 write-verbose "Creating data dictionary $descr..." $data | foreach { $checkkey = $($_."$key") if($dic.ContainsKey($($_."$key").ToLower())) { $str= "existing key " foreach ($col in $columns) { $str = $str + $_.$col + " " } $errList.add($checkkey,$str) } else { $dic2 = @{} foreach ($col in $columns) { #if ($col -eq $key) {continue} $dic2.add($col.ToLower(),($_."$col")) } $dic.add($($_."$key").ToLower(),$dic2) } } $nbr = $dic.count write-verbose "Creating data dictionary $descr (records: $nbr)...done" return $dic,$errList } #------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------- # create dictionary function createHashFromArray { param ( $data ,$key ,$columns ,$Delim ,$descr ,$ErrorList ,[switch]$skipemptykey ) $dic = @{} $errList = @() write-verbose "Creating hash table $descr..." $i = 0 [int]$steps = [math]::pow(10,( [math]::truncate([math]::log10( $($data.Count))))) write-progress -Activity "createDictionary: $descr" -Status "Progress:" -PercentComplete 0 $data | foreach { if ($skipemptykey.isPresent -and [string]::IsNullOrEmpty($_."$key")) {return} $arr = @() ++$i [Int32]$percent = $i/$($data.count)*100 write-progress -Activity "createDictionary: $descr" -Status "Progress:$percent" -PercentComplete $percent foreach ($col in $columns) { if ($col -eq "objectGUID") { $to64 = [Convert]::ToBase64String(($_."$col").ToByteArray()) $arr += $to64.ToString() #} elseif ($col -eq 'proxyaddresses') { # if ([string]::isNullorEmpty($global:ArrayDelimiter)) {$del="|"} else {$del = $global:ArrayDelimiter = "|"} # $arr = $_ -join $del }else { $arr += @($_."$col") } } if ($key -eq "objectGUID") { $to64 = [Convert]::ToBase64String(($_."objectGUID").ToByteArray()) $newkey = $to64.ToString() if ($dic.ContainsKey($newkey)) { $userOri = $dic.Item($newkey) $usermail = $userori[1] $str = $checkkey + "," + $($arr -join ",") + ",$usermail" $errList += ("$str") } else { $dic.add($newkey,$arr) } } else { $checkkey = $($_."$key") if (![string]::IsNullOrEmpty($checkkey)) { $checkkey = $($_."$key").ToLower() # don't add again add to err list if ($dic.ContainsKey($checkkey)) { $userOri = $dic.Item($checkkey) $str = $checkkey + "," + $($arr -join ",") $errList += ("$str") } else { $dic.add($checkkey,$arr) } } } } Write-progress -Activity "createDictionary: $descr" -PercentComplete 100 -Completed if (-Not ([string]::IsNullOrEmpty($errList) -and [string]::IsNullOrEmpty($ErrorList))) { "EmpNo,Email",$errlist | Set-Content -path $ErrorList -force -encoding UTF8 } $nbr = $dic.count write-verbose "Creating data dictionary $descr (records: $nbr)...done" return $dic } #------------------------------------------------------------------------------------------------------- # function EmailAlert { param ($Subject, $body, $SMTPServer, [string[]]$to, $from, $cc, $attachment,$BodyAsHtml=$false) $cmdargs = "Send-MailMessage -SmtpServer $MailHost -From $MailFrom -To $MailTo -Body $body -Subject $Subject" write-verbose $cmdargs if ($body -eq $null) {$body = " "} if ($SMTPserver -eq $null) {$SMTPserver = $MailHost} if ($to -eq $null) {$to = $MailAlertEmail} if ($from -eq $null) {$from = $Mailfrom} write-verbose "$body" if ($BodyAsHtml) { $BodyAsHtml=1 } else { $BodyAsHtml=0 } $cmd = ("Send-MailMessage -SmtpServer {0} -From {1} -To {2} -Body ""{3}"" -Subject ""{4}"" -BodyAsHtml:{5}" -f $SMTPserver, $from, $to, $body, $Subject, $BodyAsHtml ) if (![string]::isNullorEmpty($attachment)) { $cmd = ("$cmd -attachment {0}" -f $attachment) } if (![string]::isNullorEmpty($cc)) { $cmd = ("$cmd -cc {0}" -f$cc) } if ([string]::isNullorEmpty($attachment) -and [string]::isNullorEmpty($cc)) { Send-MailMessage -SmtpServer $SMTPserver -From $from -To $to -Body $body -Subject $Subject -BodyAsHtml:$BodyAsHtml } elseif (![string]::isNullorEmpty($attachment) -and [string]::isNullorEmpty($cc)) { Send-MailMessage -SmtpServer $SMTPserver -From $from -To $to -Body $body -Subject $Subject -attachment $attachment -BodyAsHtml:$BodyAsHtml } elseif ([string]::isNullorEmpty($attachment) -and ![string]::isNullorEmpty($cc)) { Send-MailMessage -SmtpServer $SMTPserver -From $from -To $to -Body $body -Subject $Subject -cc $cc -BodyAsHtml:$BodyAsHtml } elseif (![string]::isNullorEmpty($attachment) -and ![string]::isNullorEmpty($cc)) { Send-MailMessage -SmtpServer $SMTPserver -From $from -To $to -Body $body -cc $cc -Subject $Subject -attachment $attachment -BodyAsHtml:$BodyAsHtml } } #-------------------------------------------------------------------------------------------------------