PowerShell Trick: Copy Certificates from one Store to another

Windows PowerShell Certificate PS provider won't let you use the Copy-Item cmdlet to copy Certificate from one store say (Machine's Personal Store ) to another store  ( Machine's Trusted Root CA store).

Below is an example :

PS>Copy-Item .\CE9A9FD6ACBE5EA0E25899C314B54DEFCA45FE70 -Destination CERT:\LocalMachine\My   
Copy-Item : Provider operation stopped because the provider does not support this operation. 
At line:1 char:1                                                                             

  • Copy-Item .\CE9A9FD6ACBE5EA0E25899C314B54DEFCA45FE70 -Destination CERT:\LocalMac ...       

    + CategoryInfo          : NotImplemented: (:) [Copy-Item], PSNotSupportedException       
    + FullyQualifiedErrorId : NotSupported,Microsoft.PowerShell.Commands.CopyItemCommand     

No worries we can do this using PowerShell but have to take another approach.
I had to recently copy the Certificate issued to my Cloud Service in one of the Azure VMs Personal Store to the Trusted Root CA store for the Local Machine.

Used the below code to do the needful:

$SourceStoreScope = 'LocalMachine'
$SourceStorename = 'My'
 
$SourceStore = New-Object  -TypeName System.Security.Cryptography.X509Certificates.X509Store  -ArgumentList $SourceStorename, $SourceStoreScope
$SourceStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
 
$cert = $SourceStore.Certificates | Where-Object  -FilterScript {
    $_.subject -like '*Cloudapp.net'
}
 
 
 
$DestStoreScope = 'LocalMachine'
$DestStoreName = 'root'
 
$DestStore = New-Object  -TypeName System.Security.Cryptography.X509Certificates.X509Store  -ArgumentList $DestStoreName, $DestStoreScope
$DestStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$DestStore.Add($cert)
 
 
$SourceStore.Close()
$DestStore.Close()

Cheers !