Skip to content

Instantly share code, notes, and snippets.

@agross
Created July 2, 2012 18:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save agross/3034643 to your computer and use it in GitHub Desktop.
Save agross/3034643 to your computer and use it in GitHub Desktop.
function Import-Certificate
{
param
(
[IO.FileInfo] $CertFile = $(throw "Parameter -CertFile [System.IO.FileInfo] is required."),
[string[]] $StoreNames = $(throw "Parameter -StoreNames [System.String] is required."),
[switch] $LocalMachine,
[switch] $CurrentUser,
[string] $CertPassword,
[switch] $Verbose
)
begin
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")
}
process
{
if ($Verbose)
{
$VerbosePreference = 'Continue'
}
if (-not $LocalMachine -and -not $CurrentUser)
{
Write-Warning "One or both of the following parameters are required: '-LocalMachine' '-CurrentUser'. Skipping certificate '$CertFile'."
}
try
{
if ($_)
{
$CertFile = $_
}
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertFile, $CertPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet)
}
catch
{
Write-Error "Error importing '$CertFile': $_"
throw
}
if ($cert -and $LocalMachine)
{
$StoreScope = "LocalMachine"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\$StoreScope\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
Write-Verbose "Successfully added '$CertFile' to 'cert:\$StoreScope\$StoreName'"
}
catch
{
Write-Error "Error adding '$CertFile' to 'cert:\$StoreScope\$StoreName': $_"
throw
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping."
}
}
}
if ($cert -and $CurrentUser)
{
$StoreScope = "CurrentUser"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\$StoreScope\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
Write-Verbose "Successfully added '$CertFile' to 'cert:\$StoreScope\$StoreName'"
}
catch
{
Write-Error "Error adding '$CertFile' to 'cert:\$StoreScope\$StoreName': $_"
throw
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping."
}
}
}
if ($cert)
{
return $cert
}
}
end
{ }
}
Export-ModuleMember -Function *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment