Get Expiring Certifikate from Skype Environment

# ===================
# Global Variables
# ===================

# For Testing Purpose
# New-TimeSpan -Start (get-date) -End 21-06-2019

$Days = "75" # ATTENTION a variable does not funktion at AddDays with Powershell Version 3 in combination with Invoke. Version5 and up Works
$OutFile = "C:\Temp\Certlist.txt"

# ============================
# Create Array
# ============================
$Serverliste = @(
                    "Server01.domain.local"
                    "Server02.domain.local"
                    "Server03.domain.local"
                    "Server04.domain.local"
                  )

"Serverliste `r`n===========" | Out-File $OutFile
# ============================
# Reading out Certificates
# ============================
$Zertliste = (
Invoke-Command -ComputerName  $Serverliste -ScriptBlock  {Get-ChildItem Cert:\LocalMachine\My  | 
  Where {$_.NotAfter -lt  (Get-Date).AddDays(75)}} | Select-Object Issuer, NotAfter, SerialNumber, Subject, Use, DnsNameList | ForEach { #Added Days manuall because of Powershel Version 3

  [pscustomobject]@{
  ".===========" = "======================================="
  FQDN =  $_.Subject
  Issuer = $_.Issuer
  Use = $_.Use
  #Computername =  $_.PSComputername
  ExpiresOn =  $_.NotAfter
  DNSListNames = $_.DnsNameList 
  "============" = "======================================="
  }
  } |Sort-Object -Descending ) |Out-File $OutFile -Append


"Get-CScertificate`r`n=================" | Out-File $OutFile -Append

  Get-CsCertificate | Select-Object Issuer, NotAfter, SerialNumber, Subject, Use, AlternativeNames | 
  Where {$_.NotAfter -lt  (Get-Date).AddDays($Days)}| ForEach {

  [pscustomobject]@{
  ".===========" = "======================================="
  FQDN =  $_.Subject
  Issuer = $_.Issuer
  Use = $_.Use
  Computername =  $_.PSComputername
  ExpiresOn =  $_.NotAfter
  AlternativeNames = $_.AlternativeNames 
  "============" = "======================================="
  }
  } |Sort-Object -Descending | Out-File $OutFile -Append

  "List of Dns Names expiring in Lync Or Skype`r`n===================================================" | Out-File $OutFile -Append
  Get-CsCertificate | Where {$_.NotAfter -lt  (Get-Date).AddDays($Days)} | Select-Object -ExpandProperty AlternativeNames -Unique|
  Sort-Object -Descending | Out-File $OutFile -Append
  "===================================================" | Out-File $OutFile -Append


# ===================================================================
# Sending Mail if file is bigger then Empty kb.
# ===================================================================
$ToAddress = "admin@domain.local"
$FromAddres = "$env:computername.$env:userdnsdomain <$ToAddress>"
#$SmtpServer = "smtp.office365.com"
$SmtpServer = "mrelay.domain.local" # INFO: server that runs script must be allowed in FW, on mailrelay and in Virus Console outgoing connection to port 25 must be allowed!
#$SmtpPort = "587"
$Attachment = "$OutFile"
$Subject = "Certliste with Certificates that will Expire in $days from the Skype Environment"
#Body as HTML
$BodyHead = "This mail has been automaticly generated by the GetCSertificate script. <br> This Task runs following script C:\Temp\GetCSCertifikate.ps1. <br><br>See Attachment for expiring Certificates.<br>Please do not reply<br><br><br>"
$Body = "$BodyHead" + "$Zertliste"
#Body as Text
#$Body = "This is an automated mail used by a script. `r`n Please do not reply. `r`n `r See Attachment with log"

$mailparam = @{
    To = $ToAddress
    From = $FromAddres
    Subject = $Subject
    Body = $Body 
    Smtpserver = $SmtpServer
    #Port = $SmtpPort
    #Credential = $SmtpCred
    Attachment = $Attachment
    }

# =========================
# Check File for testing
# =========================
# Get-ChildItem -File $OutFile | select length

if( (get-item $OutFile).length -eq 434) {"File is blank"}
#If ((Get-Content $Attachment) -eq 1kb) {"File is blank"}
    Elseif  ((Get-Content $Attachment) -gt 434) {Send-MailMessage @mailparam -UseSsl -BodyAsHtml}

 

Get Expiring Certificate from Server Array

# The Following Website explaines very well how it works with Certificates.
# https://blogs.technet.microsoft.com/scotts-it-blog/2014/12/30/working-with-certificates-in-powershell/

# ================= Folowing things has to be done before you can query Remote Server==========================
# Enable-PSRemoting has to be run on every server.
# 
# On Server that are not reachable on the Standard Ports 5985 and 5986 you have to change the Listener to Http and Https.
# Set-Item WSMan:\localhost\Service\EnableCompatibilityHttpListener -Value true
# Set-Item WSMan:\localhost\Service\EnableCompatibilityHttpsListener -Value true
# The option -Port 443 oder 80 also has to be set.
#
# Check Listener: dir WSMan:\localhost\Service
# =============================================================================================================

# Example 1
#Get-ChildItem -Path Cert:\LocalMachine\My -Recurse | where { $_.notafter -le (get-date).AddDays(50) -AND $_.notafter -gt (get-date)} | select Friendlyname, subject, NotAfter

# Example 2
#Get-ChildItem –Recurse | where {$_.Notafter -le (get-date).AddDays(50) -AND $_.notafter -gt (get-date)}| select Friendlyname, subject, NotAfter | Format-Table NotAfter, FriendlyName, Subject
#Invoke-Command -Computername $Serverliste -ScriptBlock {Get-ChildItem Cert:\LocalMachine\My -Recurse | where {$_.Notafter -le (get-date).AddDays(750) -AND $_.notafter -gt (get-date)}| select subject, Friendlyname, NotAfter} | Format-Table subject, NotAfter, FriendlyName, DaysUntilExpired

Import-Module PKI
Set-Location Cert:\LocalMachine\My

# Treshold days that will expire
$treshold = 50

# ============================
# Create Array
# ============================
$Serverlist = @("server01.domain.local"
                "server02.domain.local"
                "server03.domain.local"
                "server04.domain.local"
                "server05.domain.local"
                  )

# ============================
# Das auslesen von Zertifikaten
# ============================
$Certlist = (
Invoke-Command -ComputerName  $Serverlist -ScriptBlock  {Get-ChildItem Cert:\LocalMachine\My  | 
  Where {$_.NotAfter -lt  (Get-Date).AddDays($treshold)}} | ForEach {

  [pscustomobject]@{
  FQDN =  $_.Subject
  #Computername =  $_.PSComputername
  ExpiresOn =  $_.NotAfter
  }
  } |Sort-Object -Descending |Out-File C:\Temp\Certlist.txt )


#===================================================================
$ToAddress = 'admin@domain.local'
$FromAddres = "$env:computername.$env:userdnsdomain <admin@domain.local>"
#$SmtpServer = 'smtp.office365.com'
$SmtpServer = "mrelay.domain.local" 
#$SmtpPort = '587'
$Attachment = "C:\Temp\Certlist.txt"
$Subject = "Certlist with Server that having a Certifcatite expring in $treshold days"
#Body as HTML
$BodyHead = 'This mail has been automaticly generated by the GetCertificate script. <br> This Task runs following script C:\Temp\GetCertifikate.ps1. <br><br>See Attachment for expiring Certificates.<br>Please do not reply<br><br><br>'
$Body = "$BodyHead" + "$Certlist"
#Body as Text
#$Body = "This is an automated mail used by a script. `r`n Please do not reply. `r`n `r See Attachment with log"

$mailparam = @{
    To = $ToAddress
    From = $FromAddres
    Subject = $Subject
    Body = $Body 
    Smtpserver = $SmtpServer
    #Port = $SmtpPort
    #Credential = $SmtpCred
    Attachment = $Attachment
    

    }

If ((Get-Content $Attachment) -eq $Null) {"File is blank"}
    Elseif  ((Get-Content $Attachment) -ne $Null) {Send-MailMessage @mailparam -UseSsl -BodyAsHtml}

 

7 Zip Usage

Expand-7Zip
[-ArchiveFileName]
[-TargetPath]
[-Password ] | [-SecurePassword ]
[-CustomInitialization ]
[]

Compress-7Zip
[-ArchiveFileName]
[-Path]
[[-Filter] ]
[-Format {Auto | SevenZip | Zip | GZip | BZip2 | Tar | XZ}]
[-CompressionLevel {None | Fast | Low | Normal | High | Ultra}]
[-CompressionMethod {Copy | Deflate | Deflate64 | BZip2 | Lzma | Lzma2 | Ppmd | Default}]
[-Password ] | [-SecurePassword ]
[-CustomInitialization ]
[-EncryptFilenames]
[-VolumeSize ]
[-FlattenDirectoryStructure]
[-SkipEmptyDirectories]
[-DisableRecursion]
[-Append]
[]

Get-7Zip
[-ArchiveFileName]
[-Password ] | [-SecurePassword ]
[]

Get-7ZipInformation
[-ArchiveFileName]
[-Password ] | [-SecurePassword ]
[]

7 Zip Compress directory

 

# This script can be used to zip a dirctory with plain powershell.
$source = "C:\temp"
$destination = "D:\temp.zip"
 
If(Test-path $destination) {Remove-item $destination}
Add-Type -assembly "system.io.compression.filesystem"
 
[io.compression.zipfile]::CreateFromDirectory($Source, $destination)

Delegate AD Group to Edit one Attribute

Import-Module ActiveDirectory
#Bring up an Active Directory command prompt so we can use this later on in the script
cd ad:
#Get a reference to the RootDSE of the current domain
$rootdse = Get-ADRootDSE
#Get a reference to the current domain
$domain = Get-ADDomain

#Create a hashtable to store the GUID value of each schema class and attribute
$guidmap = @{}
Get-ADObject -SearchBase ($rootdse.SchemaNamingContext) -LDAPFilter `
"(schemaidguid=*)" -Properties lDAPDisplayName,schemaIDGUID | 
% {$guidmap[$_.lDAPDisplayName]=[System.GUID]$_.schemaIDGUID}

#Create a hashtable to store the GUID value of each extended right in the forest
$extendedrightsmap = @{}
Get-ADObject -SearchBase ($rootdse.ConfigurationNamingContext) -LDAPFilter `
"(&(objectclass=controlAccessRight)(rightsguid=*))" -Properties displayName,rightsGuid | 
% {$extendedrightsmap[$_.displayName]=[System.GUID]$_.rightsGuid}


# ============= Define Groups to Set Delegation =======
$grpName = "RTCUniversalUserAdmins"
# Get Group DistinguishedName
$grp = Get-ADGroup -Identity "$grpName" | Select-Object DistinguishedName
# =====================================================

# ============= OU Delegation =========================
#E-Mail-Addresses attribute bf967961-0de6-11d0-a285-00aa003049e2
#Get a reference to the OU we want to delegate
$ou = Get-ADOrganizationalUnit -Identity ("OU=Benutzer,OU=RDI,"+$domain.DistinguishedName)

#Get a copy of the current DACL on the OU
$acl = Get-ACL -Path ($ou.DistinguishedName)

#Get the SID values of each group we wish to delegate access to
$grpNameDelegate = "RTCUniversalUserAdmins"
$WriteProperty = New-Object System.Security.Principal.SecurityIdentifier (Get-ADGroup "$grpNameDelegate").SID

$ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule(
    $WriteProperty,
    [System.DirectoryServices.ActiveDirectoryRights]::WriteProperty,
    [System.Security.AccessControl.AccessControlType]::Allow,
    #"bf967961-0de6-11d0-a285-00aa003049e2",
    $guidmap["Mail"],
    [DirectoryServices.ActiveDirectorySecurityInheritance]::All
)
$ACL.AddAccessRule($ACE)
Set-ACL -AclObject $ACL -Path ("AD:\"+($ou.DistinguishedName))

# Example to Write all Properties
#$acl.AddAccessRule((New-Object System.DirectoryServices.ActiveDirectoryAccessRule `
#$WriteProperty,"WriteProperty","Allow","Descendents",$guidmap["user"]))

# =====================================================

Delegate AD Group to Edit Group Member

 

 

Import-Module ActiveDirectory
#Bring up an Active Directory command prompt so we can use this later on in the script
cd ad:
#Get a reference to the RootDSE of the current domain
$rootdse = Get-ADRootDSE
#Get a reference to the current domain
$domain = Get-ADDomain

#Create a hashtable to store the GUID value of each schema class and attribute
$guidmap = @{}
Get-ADObject -SearchBase ($rootdse.SchemaNamingContext) -LDAPFilter `
"(schemaidguid=*)" -Properties lDAPDisplayName,schemaIDGUID | 
% {$guidmap[$_.lDAPDisplayName]=[System.GUID]$_.schemaIDGUID}

#Create a hashtable to store the GUID value of each extended right in the forest
$extendedrightsmap = @{}
Get-ADObject -SearchBase ($rootdse.ConfigurationNamingContext) -LDAPFilter `
"(&(objectclass=controlAccessRight)(rightsguid=*))" -Properties displayName,rightsGuid | 
% {$extendedrightsmap[$_.displayName]=[System.GUID]$_.rightsGuid}


# ============= Define Groups to Set Delegation =======
$grpName = "RTCUniversalUserAdmins"
# Get Group DistinguishedName
$grp = Get-ADGroup -Identity "$grpName" | Select-Object DistinguishedName
# =====================================================

# ============= Group Delegation ======================
#Get the SID values of each group we wish to delegate access to
$grpNameDelegate1 = "SkypeUser group name"
$SkypeUser = New-Object System.Security.Principal.SecurityIdentifier (Get-ADGroup "$grpNameDelegate1").SID
$grpNameDelegate2 = "SkypeUser group name Enterprise Voice"
$SkypeUserEv = New-Object System.Security.Principal.SecurityIdentifier (Get-ADGroup "$grpNameDelegate2").SID


#Get a copy of the current DACL on the Group
$acl = Get-ACL -Path ($grp.DistinguishedName)

#Grant the Delegategroup to edit the Group
$acl.AddAccessRule(
    (New-Object System.DirectoryServices.ActiveDirectoryAccessRule $SkypeUser,
    "WriteProperty",
    "Allow",
    $guidmap["Member"])
    )
$acl.AddAccessRule(
    (New-Object System.DirectoryServices.ActiveDirectoryAccessRule $SkypeUserEv,
    "WriteProperty",
    "Allow",
    $guidmap["Member"])
    )

Set-ACL -ACLObject $acl -Path ("AD:\"+($grp.DistinguishedName))
# ==============================================