Install a certificate using PowerShell on a remote server

I want to install a certificate (X.509) created using makecert.exe on a remote server. I cannot use psexec or something like that, but must use PowerShell.

  • Server Operating System: Windows Server 2008 R2
  • PowerShell Version: 4

Question: How to install a certificate using PowerShell on a remote server.

+4
source share
2 answers

To import a PFX file, you can use Import-PfxCertificate, for example

Import-PfxCertificate -FilePath YOUR_PFX_FILE.pfx -Password (ConvertTo-SecureString -String "THE_PFX_PASSWORD" -AsPlainText -Force)

To do this on a remote computer, you can use Invoke-Command -ComputerName(and use the UNC path for the PFX file).

+1
source

: ServerA SSL, ServerB , SSL

  • ( ServerB):

    $afMachineName = "SomeMachineNameOrIp"
    $certSaveLocation = "c:\temp\Cert.CER"
    
  • (ServerA ServerB):

    Function enableRemotePS() {
        Enable-PSRemoting -Force
        Set-Item wsman:\localhost\client\trustedhosts $afMachineName -Force
        Restart-Service WinRM
    }
    
  • ( ServerB):

    Function saveCert([string]$machineName,[string]$certSaveLocation) {
        Invoke-Command -ComputerName $machineName -ArgumentList $certSaveLocation -ScriptBlock {
            param($certSaveLocation)
            $cert = dir Cert:\LocalMachine\Root | where {$_.Subject -eq "CN=YOURCERTNAME" };
            $certBytes = $cert.Export("cert");
            [system.IO.file]::WriteAllBytes($certSaveLocation, $certBytes);
        }
    
        Copy-Item -Path \\$machineName\c$\temp\CertAF.CER -Destination $certSaveLocation
    }
    
  • ( ServerB)

    Function importCert([string]$certSaveLocation) {
        $CertToImport = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certSaveLocation
    
        $CertStoreScope = "LocalMachine"
        $CertStoreName = "Root"
        $CertStore = New-Object System.Security.Cryptography.X509Certificates.X509Store $CertStoreName, $CertStoreScope
    
        # Import The Targeted Certificate Into The Specified Cert Store Name Of The Specified Cert Store Scope
        $CertStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
        $CertStore.Add($CertToImport)
        $CertStore.Close()
    }
    
+2

All Articles