<# .SYNOPSIS Creates, installs, and exports a self-signed certificate for use as authorization method for automated PowerShell scripts using App Registrations / Service Principals Note that the certificate will not be exportable as know .pfx file will be generated, as the cert is intended for local installs on workstations and servers, that call PowerShell scripts as Scheduled Tasks to access Azure resources, particularly Storage Accounts .EXAMPLE Create-CertificateForAppRegistration -nameOfCertificate "testCert3" -validityLengthInMonths "24" -folderPath "C:\Scripts" .INPUTS [String]$nameOfCertificate - The name of the certificate (aka Subject) [Int]$validityLengthInMonths - How long will the certficate be valid in months [String]$folderPath - The path where certificate will be exported to as a .cer file .OUTPUTS None #> Function Create-CertificateForAppRegistration { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [String]$nameOfCertificate, [Parameter(Mandatory = $true)] [Int]$validityLengthInMonths, [Parameter(Mandatory = $true)] [String]$folderPath ) New-SelfSignedCertificate -KeyExportPolicy NonExportable -Subject "CN=$("$nameOfCertificate")" ` -CertStoreLocation "Cert:\$("CurrentUser")\My" ` -NotAfter (Get-Date).AddMonths($($validityLengthInMonths)) -KeySpec "Signature" $Subject = "CN="+$nameOfCertificate $certificate = Get-ChildItem -Path "Cert:\CurrentUser\My" | Where-Object {$_.Subject -eq $Subject} $filePath = $folderPath+"\"+$nameOfCertificate+".cer" Export-Certificate -Cert $certificate -FilePath $filePath # Add the self-signed certificate to the CurentUser's root certificate store. $rootStore = [System.Security.Cryptography.X509Certificates.X509Store]::new("My","CurrentUser") $rootStore.Open("ReadWrite") $rootStore.Add($certificate) $rootStore.Close() } Create-CertificateForAppRegistration -nameOfCertificate "testCert3" -validityLengthInMonths 24 -folderPath "C:\Scripts"