# encoding: ascii
# api: powershell
# title: Renew Certificates
# description: Fair warning: This is a messy scrip, not even parameterized.  It ain’t pretty.
# version: 0.1
# type: script
# author: Steve Whitcher
# license: CC0
# x-poshcode-id: 5907
# x-archived: 2015-06-27T00:15:58
# x-published: 2015-06-24T21:18:00
#
# After configuring the variables as appropriate, this script will check the computers in $workstations to confirm they are online, then contact each computer to check for certificates issued before $NewCACertDate and renew them.  It uses CredSSP to authenticate to the client computers, and delegation of fresh credentials must be allowed.  The script, as is, also requires the ActiveDirectory module, for the use of “Get-ADComputer”.
#
$cred = Get-Credential  # Credential with admin rights on client computers
$workstations = Get-adcomputer LEN5555 # Modify this to get the only the client computers to be contacted
$NewCACertDate = get-date "01/01/1901" # Set this date to match the date your new root CA certificate was issued. 


workflow Get-onlinecomputers
{
    [CmdletBinding()]
    [Alias()]
    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
                   [Alias("ComputerName","cn")]
        $Name
    )


    foreach -parallel ($computer in $Name)
    {
        if (Test-connection -computername $computer -count 1 -erroraction SilentlyContinue) {
            $computer
        }
    
    }
}

$OnlinePCs = get-onlinecomputers $workstations.dnshostname

$RenewCertificates = {
    Param([Datetime]$NewCACertDate)
    $Certs = get-childitem -path Cert:\LocalMachine\My
    $OldCerts = $Certs | Where-Object {$_.NotBefore -lt $NewCACertDate}
    #write-output $oldcerts
    foreach ($cert in $OldCerts)
    {
        $Serial = $cert.SerialNumber
        Write-Output $Serial
        certreq -enroll -machine -cert $Serial -q Renew ReuseKeys
    }
}

foreach ($computer in $OnlinePCs) {
        if ($computer) {
                    write-output $computer
                    invoke-command -computername $computer -ScriptBlock $RenewCertificates -argumentlist $NewCACertDate -authentication credssp -cred $cred
        }
    }
