Parsing Function return in PowerShell Script - powershell

I am trying to parse the response from one of the functions in PowerShell Script and based on the response I have to make some decision.
The function is returning JSON object successfully but not able to parse the response from the function. I need to check if validnodes count is 0 or not.
[String[]] $NodeList = 'a1572dev00e001','a1572dev00q001'
$Response = Get-Nodes
Write-Output "Response $Response"
$JSRes = $Response | ConvertFrom-Json
Write-Output "Parsing response $JSRes"
#$Result = "success"
if($JSRes.ValidNodes.Count -gt 0)
{
Write-Output "$JSRes.ValidNodes"
$Result = "success"
}
else
{
Write-Output "All nodes are Invalid"
Write-Output "Invalid Nodes: $JSRes.Invalid"
$Result = "failed"
$ErrorMessage = "All nodes are Invalid"
}
Write-Output $Result
#Function
function Get-Nodes
{
$ValidNodes=#()
$InvalidNodes=#()
foreach($Node in $NodeList)
{
if(Get-ADComputer -filter {Name -eq $Node})
{
$ValidNodes +=$Node
}
else
{
$InvalidNodes +=$Node
}
}
$JRes = #{"ValidNodes"=$ValidNodes;"Invalid"=$InvalidNodes} | ConvertTo-Json -Compress
Write-Output $JRes
return $JRes
}
Output:
Response {"ValidNodes":["a1572dev00e001","a1572dev00q001"],"Invalid":[]} {"ValidNodes":["
a1572dev00e001","a1572dev00q001"],"Invalid":[]}
Parsing response
All nodes are Invalid
Invalid Nodes:
failed

One issue is you are outputting the $Jres twice.
Write-Output $JRes
return $JRes
These effectively do the exact same thing. Next, you're using ConvertFrom-String when it seems you should be using ConvertFrom-Json
$JSON = $Response | ConvertFrom-String
Finally, you're trying to output $ValidNodes and $InvalidNodes that only exist in your function. Change these to $JSON.ValidNodes and $JSON.InvalidNodes
One more suggestion is to parameterize the Nodelist so you can just pass the nodes to the function.
#Function
function Get-Nodes
{
Param([string[]]$nodelist)
$ValidNodes=#()
$InvalidNodes=#()
foreach($Node in $NodeList)
{
if(Get-ADComputer -filter {Name -eq $Node})
{
$ValidNodes +=$Node
}
else
{
$InvalidNodes +=$Node
}
}
$JRes = #{"ValidNodes"=$ValidNodes;"Invalid"=$InvalidNodes} | ConvertTo-Json -Compress
$JRes
}
$Response = Get-Nodes a1572dev00e001,a1572dev00q001
Write-Output "Response $Response"
$JSON = $Response | ConvertFrom-Json
Write-Output "Parsing response $JSON"
if($JSON.ValidNodes.Count -gt 0)
{
Write-Output "Valid Nodes: $($JSON.ValidNodes)"
$Result = "success"
}
else
{
Write-Output "All nodes are Invalid"
Write-Output "Invalid Nodes: $($JSON.InValidNodes)"
$Result = "failed"
$ErrorMessage = "All nodes are Invalid"
}
Write-Output $Result

Related

PowerShell: Working with the error from Standard Out (using Nessus Essentials)

Trying to use PowerShell to capture the running status of the "Nessus Essentials" software product. Simply trying to capture product status: running, not running, or other. Getting the below error each time. I've tried changing -like to -match and changing string [warn] [scanner] Not linked to a manager to various other shorter versions, with wildcards and without, to no avail. I still get several lines of an ugly error message when all I want is one line with the string Not linked to a manager returned to console with nothing beneath that.
Pertinent snippet working incorrectly:
} elseif(($agentStatus.stdOut -like "[warn] [scanner] Not linked to a manager")) {
Throw "Not linked to a manager"
The Error:
The Code:
Function Start-ProcessGetStreams {
[CmdLetBinding()]
Param(
[System.IO.FileInfo]$FilePath,
[string[]]$ArgumentList
)
$pInfo = New-Object System.Diagnostics.ProcessStartInfo
$pInfo.FileName = $FilePath
$pInfo.Arguments = $ArgumentList
$pInfo.RedirectStandardError = $true
$pInfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pInfo.CreateNoWindow = $true
$pInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
$proc = New-Object System.Diagnostics.Process
$proc.StartInfo = $pInfo
Write-Verbose "Starting $FilePath"
$proc.Start() | Out-Null
Write-Verbose "Waiting for $($FilePath.BaseName) to complete"
$proc.WaitForExit()
$stdOut = $proc.StandardOutput.ReadToEnd()
$stdErr = $proc.StandardError.ReadToEnd()
$exitCode = $proc.ExitCode
Write-Verbose "Standard Output: $stdOut"
Write-Verbose "Standard Error: $stdErr"
Write-Verbose "Exit Code: $exitCode"
[PSCustomObject]#{
"StdOut" = $stdOut
"Stderr" = $stdErr
"ExitCode" = $exitCode
}
}
Function Get-NessusStatsFromStdOut {
Param(
[string]$stdOut
)
$stats = New-Object System.Collections.Hashtable
$StdOut -split "`r`n" | % {
if($_ -like "*:*") {
$result = $_ -split ":"
$stats.add(($result[0].Trim() -replace "[^A-Za-z0-9]","_").ToLower(),$result[1].Trim())
}
}
Return $stats
}
Function Get-DateFromEpochSeconds {
Param(
[int]$seconds
)
$utcTime = (Get-Date 01.01.1970)+([System.TimeSpan]::fromseconds($seconds))
Return Get-Date $utcTime.ToLocalTime() -Format "yyyy-MM-dd HH:mm:ss"
}
Try {
$nessusExe = Join-Path $env:ProgramFiles -ChildPath "Tenable\Nessus\nessuscli.exe" -ErrorAction Stop
} Catch {
Throw "Cannot find NessusCli.exe"
}
Write-Host "Getting Agent Status..."
$agentStatus = Start-ProcessGetStreams -FilePath $nessusExe -ArgumentList "managed status"
If($agentStatus.stdOut -eq "" -and $agentStatus.StdErr -eq "") {
Throw "No Data Returned from NessusCli"
} elseif($agentStatus.StdOut -eq "" -and $agentStatus.StdErr -ne "") {
Throw "StdErr: $($agentStatus.StdErr)"
} elseif(($agentStatus.stdOut -like "[warn] [scanner] Not linked to a manager")) {
Throw "Not linked to a manager"
} elseif(-not($agentStatus.stdOut -like "*Running: *")) {
Throw "StdOut: $($agentStatus.StdOut)"
} else {
$stats = Get-NessusStatsFromStdOut -stdOut $agentStatus.StdOut
If($stats.last_connection_attempt -as [int]) { $stats.last_connection_attempt = Get-DateFromEpochSeconds $stats.last_connection_attempt }
If($stats.last_connect -as [int]) { $stats.last_connect = Get-DateFromEpochSeconds $stats.last_connect }
If($stats.last_scanned -as [int]) { $stats.last_connect = Get-DateFromEpochSeconds $stats.last_scanned }
}
$stats | Out-Host
Note: Code above is courtesy of here, I've only made a change to the path of Nessus, and I am adding the attempt to capture that it's not connected to a manager.
Modify your code so that it separates standard output from error and so that it handles each line separately.
The following is how to capture standard output (excluding else statements and error handling) of a program (according to your $Proc variable)
if ($proc.Start())
{
while (!$proc.StandardOutput.EndOfStream)
{
$StreamLine = $proc.StandardOutput.ReadLine()
if (![string]::IsNullOrEmpty($StreamLine))
{
# TODO: Duplicate code in this scope as needed or rewrite to use multiline regex
$WantedLine = [regex]::Match($StreamLine, "(?<wanted>.*Not linked to a manager.*)")
$Capture = $WantedLine.Groups["wanted"]
if ($Capture.Success)
{
Write-Output $Capture.Value
}
}
}
}
After that deal with error output separately:
$StandardError = $Proc.StandardError.ReadToEnd()
if (![string]::IsNullOrEmpty($StandardError))
{
# Or use Write-Error
Write-Output $StandardError
}

Function App slot health check failing even when its running fine

I have a script thats been used for a long time with no issues for checking the health status of a deployment slot
This is built into the deployment in dev ops
When I deploy the function via my release pipeline its fine, i.e. the slot starts and stays running with no errors
But the health check fails which in turn stops my deployment
The script is a standard ps template as shown below
param (
[string]$URI,
[string]$resultVarName,
[string]$Method = 'GET',
[string]$SuccessTextContent = 'Healthy',
[string]$Retries = 1,
[string]$SecondsDelay = 2,
[string]$TimeoutSec = 120
)
Write-Host "$Method ""$URI"" Retries: $Retries, SecondsDelay $SecondsDelay, TimeoutSec $TimeoutSec";
Function Req {
Param(
[Parameter(Mandatory=$True)]
[hashtable]$Params,
[int]$Retries = 1,
[int]$SecondsDelay = 2
)
$Params.Add('UserAgent', 'azagent powershell task')
$method = $Params['Method']
$url = $Params['Uri']
$cmd = { Write-Host "$method $url..." -NoNewline; Invoke-WebRequest #Params }
$retrycount = 0
$completed = $false
$response = $null
while (-not $completed) {
try {
$response = Invoke-Command $cmd -ArgumentList $Params
if ($response.StatusCode -ne 200) {
throw "Expecting reponse code 200, was: $($response.StatusCode)"
}
$completed = $true
} catch {
Write-Output "$(Get-Date -Format G): Request to $url failed. $_"
if ($retrycount -ge $Retries) {
$completed = $true
$totalCalls = $retrycount + 1
Write-Warning "Request to $url failed $totalCalls times in total."
} else {
Write-Warning "Request to $url failed. Retrying in $SecondsDelay seconds."
Start-Sleep $SecondsDelay
$retrycount++
}
}
}
Write-Host "Status: ($($response.StatusCode))"
return $response
}
$res = Req -Retries $Retries -SecondsDelay $SecondsDelay -Params #{ 'Method'=$Method;'Uri'=$URI;'TimeoutSec'=$TimeoutSec;'UseBasicParsing'=$true }
if($res.StatusCode -ne 200)
{
echo "##vso[task.setvariable variable=$resultVarName]Unhealthy"
Write-Error "Health check validation failure."
}
else
{
echo "##vso[task.setvariable variable=$resultVarName]Healthy"
Write-Host "Health check validation success."
}
Does anyone know how to fix this?
I get the error powershell-scripts\service-health-check.ps1 : [31;1mHealth check validation failure.

Simple Powershell IIS Site Verification

part of our checkout process after patching is checking webservers. I'd like create a for each loop that runs the following script looking for 200 or 401 and pops terminal message a "site ok message" with the site name. If it gets anything else, I'd like an error message that gives the site name as well.
I know 401 response isn't really ok, but some of the sites I manage I don't have rights to view. (Hence is why I wanted to go this route, I never know what "looks right" on a visual check. Here is what I have so far.
$HTTP_Request = [System.Net.WebRequest]::Create('https://someinternalserver.com')
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-output $http_request | Select-Object RequestUri
Write-Host "SITE OK! 200"
If ($HTTP_Status -eq 401) {
Write-output $http_request | Select-Object RequestUri
Write_Host "SITE OK! 401"}
}
Else {
Write-output $http_request | Select-Object RequestUri
Write-Host "SITE DEAD"}
If ($HTTP_Response -eq $null) { }
Else { $HTTP_Response.Close() }
When I run the command, I am getting error messages that I don't really care about on line 5. How do I supress them? Ideally I am trying to make it look clean as I can so we can just watch info scroll by and note any server that is something other than 200 or 401results
...this was working too sort of but now I seem to have broken it to the point where everything comes back as SITE DEAD.
You could add a try/catch.
$HTTP_Request = [System.Net.WebRequest]::Create('http://localhost:8080')
$HTTP_Response
$HTTP_Status
try {
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
}
catch {
}
If ($HTTP_Status -eq 200) {
Write-output $http_request | Select-Object RequestUri
Write-Host "SITE OK! 200"
If ($HTTP_Status -eq 401) {
Write-output $http_request | Select-Object RequestUri
Write_Host "SITE OK! 401"
}
}
Else {
Write-output $http_request | Select-Object RequestUri
Write-Host "SITE DEAD"
}
If ($HTTP_Response -eq $null) { }
Else { $HTTP_Response.Close() }
If you want to hit some URLs in a loop, you can do something like this:
param(
$urls = #('http://localhost:8080', 'https://google.com')
)
Clear-Host
foreach ($url in $urls) {
$HTTP_Request = [System.Net.WebRequest]::Create($url)
$HTTP_Response
$HTTP_Status
try {
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
}
catch {
}
If ($HTTP_Status -eq 200) {
Write-Host ($http_request | Select-Object RequestUri).RequestUri
Write-Host "SITE OK! 200 `n"
}
ElseIf ($HTTP_Status -eq 401) {
Write-Host ($http_request | Select-Object RequestUri).RequestUri
Write_Host "SITE OK! 401 `n"
}
Else {
Write-Host ($http_request | Select-Object RequestUri).RequestUri
Write-Host "SITE DEAD `n"
}
# $null should be on the left: https://evotec.xyz/the-curious-case-of-null-should-be-on-the-left-side-of-equality-comparisons-psscriptanalyzer/
If ($null -eq $HTTP_Response) { }
Else { $HTTP_Response.Close() }
}

Recheck the URL thrice for web exception cases powershell

$status_wait =1
Do{
$https_request= invoke_webrequest -uri "https:\\"
$https_status = [int]http_request.statuscode
If($($_.categoryinfo.reason) -eq "webexception") {
Start-sleep -secounds 30
$status_wait+=1
}
Elseif($http_status -eq 200) {
Write-host "URL is up"
}
}Untill (status_wait -eq 3)
You are looking for something like this ?
#Remove-Variable * -ErrorAction SilentlyContinue
$url = "www.yourtargetsite.com"
function try-webrequest($url){
try{
return (Invoke-WebRequest -uri $url -ErrorAction Stop)
}catch{
return $_
}
}
$wr = try-webrequest $url
if ($wr.statuscode -ne 200){
If($wr.categoryinfo.reason -eq "webexception"){
$count = 1
while($count -lt 4){
"Retrying...$count"
$count++
if ((try-webrequest $url).statuscode -eq 200){break}
sleep -seconds 30
}
}else{
#In case you want to handle any other exception
"The link is down NOT due to webexception"
}
}else{
"The link's up"
}
PS: I have just started answering on stackoverflow. I'd love to hear your feedback.

Powershell script to get certificate expiry for a website remotely for multiple servers

I am trying to create an script to get the certificate expiry date for an websites remotely for multiple servers. I have an script which is working for single server (Need to login into server and doing execution), I need to run this remotely for multiple servers. How can i modify this script to execute for multiple servers remotely. Please advice.
$servers = get-content D:\Certificate.txt
$DaysToExpiration = 60 #change this once it's working
$expirationDate = (Get-Date).AddDays($DaysToExpiration)
foreach ($server in $servers)
{
$sites = Get-Website | ? { $_.State -eq "Started" } | % { $_.Name }
$certs = Get-ChildItem IIS:SSLBindings | ? {
$sites -contains $_.Sites.Value
} | % { $_.Thumbprint }
Get-ChildItem CERT:LocalMachine/My | ? {
$certs -contains $_.Thumbprint -and $_.NotAfter -lt $expirationDate
}
}
Inspired by https://iamoffthebus.wordpress.com/2014/02/04/powershell-to-get-remote-websites-ssl-certificate-expiration/ I use following script:
$minimumCertAgeDays = 60
$timeoutMilliseconds = 10000
$urls = get-content .\check-urls.txt
#disabling the cert validation check. This is what makes this whole thing work with invalid certs...
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
foreach ($url in $urls)
{
Write-Host Checking $url -f Green
$req = [Net.HttpWebRequest]::Create($url)
$req.Timeout = $timeoutMilliseconds
$req.AllowAutoRedirect = $false
try {$req.GetResponse() |Out-Null} catch {Write-Host Exception while checking URL $url`: $_ -f Red}
$certExpiresOnString = $req.ServicePoint.Certificate.GetExpirationDateString()
#Write-Host "Certificate expires on (string): $certExpiresOnString"
[datetime]$expiration = [System.DateTime]::Parse($req.ServicePoint.Certificate.GetExpirationDateString())
#Write-Host "Certificate expires on (datetime): $expiration"
[int]$certExpiresIn = ($expiration - $(get-date)).Days
$certName = $req.ServicePoint.Certificate.GetName()
$certPublicKeyString = $req.ServicePoint.Certificate.GetPublicKeyString()
$certSerialNumber = $req.ServicePoint.Certificate.GetSerialNumberString()
$certThumbprint = $req.ServicePoint.Certificate.GetCertHashString()
$certEffectiveDate = $req.ServicePoint.Certificate.GetEffectiveDateString()
$certIssuer = $req.ServicePoint.Certificate.GetIssuerName()
if ($certExpiresIn -gt $minimumCertAgeDays)
{
Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green
}
else
{
Write-Host WARNING: Cert for site $url expires in $certExpiresIn days [on $expiration] -f Red
Write-Host Threshold is $minimumCertAgeDays days. Check details:`nCert name: $certName -f Red
Write-Host Cert public key: $certPublicKeyString -f Red
Write-Host Cert serial number: $certSerialNumber`nCert thumbprint: $certThumbprint`nCert effective date: $certEffectiveDate`nCert issuer: $certIssuer -f Red
}
Write-Host
rv req
rv expiration
rv certExpiresIn
}
Alternatively, you might find this advanced script useful:
you can switch between report output as Text, Html or PSObject
use the script with urls (parameter array) or with input file for urls or with pipeline input
improved stability: correctly handle missing certificates on HTTP connections
just put the code into a file like Check-ExpiringSslCerts.ps1
Here the advanced script code:
[CmdletBinding(DefaultParametersetname="URLs in text file")]
Param(
[ValidateSet('Text','Html','PSObject')]
[string]$ReportType = 'Text',
[int]$MinimumCertAgeDays = 60,
[int]$TimeoutMilliseconds = 10000,
[parameter(Mandatory=$false,ParameterSetName = "URLs in text file")]
[string]$UrlsFile = '.\check-urls.txt',
[parameter(Mandatory=$false,ParameterSetName = "List of URLs",
ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$Urls
)
Begin
{
[string[]]$allUrls = #()
$returnData = #()
[bool]$ProcessedInputPipeLineByArrayItem = $false
function CheckUrl ([string]$url, [array]$returnData)
{
[string]$details = $null
if ($ReportType -eq "Html")
{
$stringHtmlEncoded = [System.Web.HttpUtility]::HtmlEncode($url)
Write-Host "<tr><td>$stringHtmlEncoded</td>"
}
if ($ReportType -eq "Text") { Write-Host Checking $url }
$req = [Net.HttpWebRequest]::Create($url)
$req.Timeout = $timeoutMilliseconds
$req.AllowAutoRedirect = $false
try
{
$req.GetResponse() |Out-Null
if ($req.ServicePoint.Certificate -eq $null) {$details = "No certificate in use for connection"}
}
catch
{
$details = "Exception while checking URL $url`: $_ "
}
if ($details -eq $null -or $details -eq "")
{
$certExpiresOnString = $req.ServicePoint.Certificate.GetExpirationDateString()
#Write-Host "Certificate expires on (string): $certExpiresOnString"
[datetime]$expiration = [System.DateTime]::Parse($req.ServicePoint.Certificate.GetExpirationDateString())
#Write-Host "Certificate expires on (datetime): $expiration"
[int]$certExpiresIn = ($expiration - $(get-date)).Days
$certName = $req.ServicePoint.Certificate.GetName()
$certPublicKeyString = $req.ServicePoint.Certificate.GetPublicKeyString()
$certSerialNumber = $req.ServicePoint.Certificate.GetSerialNumberString()
$certThumbprint = $req.ServicePoint.Certificate.GetCertHashString()
$certEffectiveDate = $req.ServicePoint.Certificate.GetEffectiveDateString()
$certIssuer = $req.ServicePoint.Certificate.GetIssuerName()
if ($certExpiresIn -gt $minimumCertAgeDays)
{
if ($ReportType -eq "Html")
{
Write-Host "<td>OKAY</td><td>$certExpiresIn</td><td>$expiration</td><td> </td></tr>"
}
if ($ReportType -eq "Text")
{
Write-Host OKAY: Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green
}
if ($ReportType -eq "PSObject")
{
$returnData += new-object psobject -property #{Url = $url; CheckResult = "OKAY"; CertExpiresInDays = [int]$certExpiresIn; ExpirationOn = [datetime]$expiration; Details = [string]$null}
}
}
else
{
$details = ""
$details += "Cert for site $url expires in $certExpiresIn days [on $expiration]`n"
$details += "Threshold is $minimumCertAgeDays days. Check details:`n"
$details += "Cert name: $certName`n"
$details += "Cert public key: $certPublicKeyString`n"
$details += "Cert serial number: $certSerialNumber`n"
$details += "Cert thumbprint: $certThumbprint`n"
$details += "Cert effective date: $certEffectiveDate`n"
$details += "Cert issuer: $certIssuer"
if ($ReportType -eq "Html")
{
Write-Host "<td>WARNING</td><td>$certExpiresIn</td><td>$expiration</td>"
$stringHtmlEncoded = [System.Web.HttpUtility]::HtmlEncode($details) -replace "`n", "<br />"
Write-Host "<tr><td>$stringHtmlEncoded</td></tr>"
}
if ($ReportType -eq "Text")
{
Write-Host WARNING: $details -f Red
}
if ($ReportType -eq "PSObject")
{
$returnData += new-object psobject -property #{Url = $url; CheckResult = "WARNING"; CertExpiresInDays = [int]$certExpiresIn; ExpirationOn = [datetime]$expiration; Details = $details}
}
rv expiration
rv certExpiresIn
}
}
else
{
if ($ReportType -eq "Html")
{
Write-Host "<td>ERROR</td><td>N/A</td><td>N/A</td>"
$stringHtmlEncoded = [System.Web.HttpUtility]::HtmlEncode($details) -replace "`n", "<br />"
Write-Host "<tr><td>$stringHtmlEncoded</td></tr>"
}
if ($ReportType -eq "Text")
{
Write-Host ERROR: $details -f Red
}
if ($ReportType -eq "PSObject")
{
$returnData += new-object psobject -property #{Url = $url; CheckResult = "ERROR"; CertExpiresInDays = $null; ExpirationOn = $null; Details = $details}
}
}
if ($ReportType -eq "Text") { Write-Host }
rv req
return $returnData
}
#disabling the cert validation check. This is what makes this whole thing work with invalid certs...
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
if ($ReportType -eq "Html")
{
Write-Host "<table><tr><th>URL</th><th>Check result</th><th>Expires in days</th><th>Expires on</th><th>Details</th></tr>"
Add-Type -AssemblyName System.Web
}
}
Process
{
if ($_ -ne $null)
{
CheckUrl $_ $returnData
$ProcessedInputPipeLineByArrayItem = $true
}
}
End
{
if ($ProcessedInputPipeLineByArrayItem -eq $false)
{
if ($Urls -eq $null)
{
$allUrls = get-content $UrlsFile
}
else
{
$allUrls = $Urls
}
foreach ($url in $allUrls)
{
$returnData = CheckUrl $url $returnData
}
}
if ($ReportType -eq "Html") { Write-Host "</table>" }
if ($ReportType -eq "PSObject") { return $returnData }
}
Output might look like e.g.:
"http://www.doma.com", "https://www.domb.com" | .\Check-ExpiringSslCerts.ps1 -ReportType PSObject | ft
Url ExpirationOn CertExpiresInDays CheckResult Details
--- ------------ ----------------- ----------- -------
http://www.doma.com ERROR No certificate in use for connection
https://www.domb.com 18.11.2017 09:33:00 87 OKAY
Put the whole code you've wrote in a script-block, in order to do so, just add at the beginning this code:
$sb = {
and at the bottom of your code add:
}
Once you have this script-block, you can run this script on the servers remotely using these commands:
$cred = Get-Credential
$servers = get-content D:\Certificate.txt
Invoke-Command -Credential $cred -ComputerName $servers -ScriptBlock $SB
Hope it helped!
Your code snippets are helpful but they will throw an error on HTTP errors -- that is the nature of the underlying .NET HttpWebRequest object to panic on everything that's not code 200.
So, if you're testing, say, API endpoints that only accept POST HTTP verb, your script will fail as it will get a 405 error message. Alternatively, if your URL returns HTTP 404, your script will fail as well. Luckily, you can catch layer 7 errors and capture the required info anyway just patch your code in this manner:
try {$req.GetResponse() | Out-Null } catch {
if ($_.Exception.InnerException.Status -eq 'ProtocolError') {
# saving the info anyway since this is a L7 error, e.g.:
$certExpiresOnString = $req.ServicePoint.Certificate.GetExpirationDateString()
[datetime]$expiration [System.DateTime]::Parse($req.ServicePoint.Certificate.GetExpirationDateString())
$certIssuer = $req.ServicePoint.Certificate.GetIssuerName() # ...
} else {
# this is a real error - timeout, DNS failure etc
Write-Host "$url, $_" -ForegroundColor Red
Continue
}
}
Taken mostly from https://gist.github.com/jstangroome/5945820, although with some changes. The following will obtain the certificate. $certificate.NotBefore and $certificate.NotAfter will then need to be checked.
function GetCertificate([string]$domain, [Int16]$port) {
$certificate = $null
$TcpClient = New-Object -TypeName System.Net.Sockets.TcpClient
$TcpClient.ReceiveTimeout = 1000
$TcpClient.SendTimeout = 1000
try {
$TcpClient.Connect($domain, $port)
$TcpStream = $TcpClient.GetStream()
$Callback = { param($sender, $cert, $chain, $errors) return $true }
$SslStream = New-Object -TypeName System.Net.Security.SslStream -ArgumentList #($TcpStream, $true, $Callback)
try {
$SslStream.AuthenticateAsClient($domain)
$certificate = $SslStream.RemoteCertificate
}
finally {
$SslStream.Dispose()
}
}
finally {
$TcpClient.Dispose()
}
if ($certificate) {
if ($certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
$certificate = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList $certificate
}
}
return $certificate
}