# encoding: ascii
# api: powershell
# title: Import-Certificate.ps1
# description: Imports certificate in specified certificate store.
# version: 0.1
# type: function
# author: anti121
# license: CC0
# function: Import-Certificate
# x-poshcode-id: 2643
# x-archived: 2016-11-07T09:21:37
# x-published: 2011-05-02T03:32:00
#
#
function Import-Certificate {
<#
	.SYNOPSIS
		Imports certificate in specified certificate store.

	.DESCRIPTION
		Imports certificate in specified certificate store.

	.PARAMETER  CertFile
		The certificate file to be imported.

	.PARAMETER  StoreNames
		The certificate store(s) in which the certificate should be imported.

	.PARAMETER  LocalMachine
		Using the local machine certificate store to import the certificate

	.PARAMETER  CurrentUser
		Using the current user certificate store to import the certificate

	.PARAMETER  CertPassword
		The password which may be used to protect the certificate file

	.EXAMPLE
		PS C:\> Import-Certificate C:\Temp\myCert.cer my

	.EXAMPLE
		PS C:\> Import-Certificate -CertFile C:\Temp\myCert.cer -StoreNames my

	.EXAMPLE
		PS C:\> Import-Certificate -Cert $certificate -StoreNames my -StoreType LocalMachine

	.EXAMPLE
		PS C:\> Import-Certificate -Cert $certificate -StoreNames my -ST Machine

	.EXAMPLE
		PS C:\> ls cert:\currentUser\TrustedPublisher | Import-Certificate -ST Machine -SN TrustedPublisher
        
        Copies the certificates found in current users TrustedPublishers store to local machines TrustedPublisher using alias  

    .INPUTS
		System.String|System.Security.Cryptography.X509Certificates.X509Certificate2, System.String, System.String

	.OUTPUTS
		NA

	.NOTES
        NAME:      Import-Certificate
        AUTHOR:    Patrick Sczepanksi (Original anti121)
        VERSION:   20110428
        #Requires -Version 2.0
    .LINK
        http://poshcode.org/1937 (Link to original script)

#>

    [CmdletBinding()]
	param
	(
        [Parameter(ValueFromPipeline=$true,Mandatory=$true, Position=0, ParameterSetName="CertFile")]
		[System.IO.FileInfo]
        $CertFile,

        [Parameter(ValueFromPipeline=$true,Mandatory=$true, Position=0, ParameterSetName="Cert")]
		[System.Security.Cryptography.X509Certificates.X509Certificate2]
        $Cert,
        
        [Parameter(Position=1)]
        [Alias("SN")]
		[string[]] $StoreNames = "My",
        
        [Parameter(Position=2)]
        [Alias("Type","ST")]
		[ValidateSet("LocalMachine","Machine","CurrentUser","User")]
        [string]$StoreType = "CurrentUser",

        [Parameter(Position=3)]
        [Alias("Password","PW")]
        [string] $CertPassword
	)
	
	begin
	{
		[void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")
	}
	
	process 
	{
        switch ($pscmdlet.ParameterSetName) {
            "CertFile" {
        		try {
                    $Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $($CertFile.FullName),$CertPassword
                }
                catch {   
        			Write-Error ("Error reading '$CertFile': $_ .") -ErrorAction:Continue
        		}
            }
            "Cert" {
           
            }
            default {
                Write-Error "Missing parameter:`nYou need to specify either a certificate or a certificate file name."
            }
	    }

        switch -regex ($storeType) {
            "Machine$" { $StoreScope = "LocalMachine" }
            "User$"  { $StoreScope = "CurrentUser" }
        } 
        
        if ( $Cert ) {
			$StoreNames | ForEach-Object {
				$StoreName = $_
                Write-Verbose " [Import-Certificate] :: $($Cert.Subject) ($($Cert.Thumbprint))"
                Write-Verbose " [Import-Certificate] :: Import into cert:\$StoreScope\$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)
                        if ( $CertFile ) {
        					Write-Verbose " [Import-Certificate] :: Successfully added '$CertFile' to 'cert:\$StoreScope\$StoreName'."
        				} else {
        					Write-Verbose " [Import-Certificate] :: Successfully added '$($Cert.Subject) ($($Cert.Thumbprint))' to 'cert:\$StoreScope\$StoreName'."
                        }
                    }
					catch
					{
						Write-Error ("Error adding '$($Cert.Subject) ($($Cert.Thumbprint))' to 'cert:\$StoreScope\$StoreName': $_ .") -ErrorAction:Continue
					}
                    if ( $store ) {
                        $store.Close()
                    }
				} 
                else {
					Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."
				}
			}
		} else {
            Write-Warning "No certificates found."
        }
	}
	
	end { 
        Write-Host "Finished importing certificates." 
    }
}

ls "D:\Temp\Source" -filter "*.cet" | Import-Certificate -SN "My"
