powershell,x509certificate,pki , Remotely renewing a certificate using CertEnroll

Remotely renewing a certificate using CertEnroll


Tag: powershell,x509certificate,pki

I am trying to renew a certificate using CertEnroll and CertLib COM libraries in PowerShell. Here is my code:

[parameter (mandatory=$true)]

$credential = Get-Credential

Invoke-Command -ComputerName $ServerName -Credential $credential -ScriptBlock{

$store =New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $location
$cert = $store.Certificates.Find([System.Security.Cryptography.X509Certificates.X509FindType]::FindByIssuerName,"<CA-Name>",$false)[0]
#Write-Output $cert.IssuerName
$request = New-Object -ComObject X509Enrollment.CX509CertificateRequestPkcs7 
$request.InitializeFromCertificate(0x2,$true,[System.Convert]::ToBase64String($cert.RawData),0x1,3 -band 1024)

$enroll = New-Object -ComObject X509Enrollment.CX509Enrollment

$message = $enroll.CreateRequest(1)

$certReq = New-Object -ComObject CertificateAuthority.Request
$val=$certReq.Submit(0x1 -bor 0,$message,[string]::Empty,"<CA-Server>\"+ $cert.Issuer.Split('=')[1])

if($val -eq 3)
    Write-Host "Certificate request accepted"
$objcertRequest = New-Object -ComObject CertificateAuthority.Request
$pending = $objcertRequest.RetrievePending($reqid,"<CA-Server>"+$cert.Issuer.Split('=')[1])
if($pending -eq 3)
        $certificate = $objcertRequest.GetCertificate(0x1 -bor 0x100);
        $objEnroll = New-Object -ComObject  X509Enrollment.CX509Enrollment
       Write-Host "Installed Successfully"
   Write-Error 'error'
Write-Output $_.Exception.Message
Write-Output $_.Exception.ItemName

I've given correct values for the CA server and the CA Name. I am able to renew the certificates on my local machine but I'm getting error when I try to do it for a certificate on another computer. This is the error I'm getting:

 Exception calling "InitializeFromCertificate" with "5" argument  (s): "CertEnroll::CX509CertificateRequestPkcs7::InitializeFromCertificate: The operation being requested was not performed because the user has not been authenticated. 0x800704dc (WIN32: 1244)"

Can anyone tell me why I'm getting an authentication error. I'm providing the correct credentials.


You provided credentials to authenticate on a remote host, however these credentials are not used to authenticate on CA server. You have either to:

  1. make remote computer as trusted for delegation (not recommended)
  2. use CredSSP to allow these credentials to use to authenticate on CA server. More details: Enable PowerShell "Second-Hop" Functionality with CredSSP


Programmatically accessing TFS history [closed]

I have a solution under TFS source control and had written some sample code using an external library that was deleted a few months ago. I am certain that the code was checked in before that class file was deleted. I am able to manually browse to previous versions of...

Color a cell on the basis of another cell value

I have a file output.txt having below content: SERVER_NAME MOUNT_POINT TOTAL_SPACE USED_SPACE USED_PERCENTAGE AVAILABLE_SPACE Server_1 /dev 1200G 537G 54% 464G Server_2 /dev 600G 490G 85% 94G Server_3 /dev 600G 402G 69% 181G Backup_server /storage 800G 682G 72% 278G Using following script, I formatted my output.txt file to get a notification...

Create powershell parameter default value is current directory

I'm hoping to create a parameter who's default value is the 'current directory' (.). For example, the Path parameter of Get-ChildItem: PS> Get-Help Get-ChildItem -Full -Path Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). Required? false Position? 1 Default...

Enhancing the pipeline's content?

Let's assume that you have a command that compresses files using 7-zip that accepts values from the pipeline: Function New-Archive { [CmdletBinding()] param ( [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)][Alias('FullName')] [string[]]$Files, [string]$Archive='Archive.zip' ) BEGIN {} PROCESS { Foreach ($File in $Files) { & 7z a -tZIP $Archive $File } } END {} } Assuming the...

What is the `.` shorthand for in a PowerShell pipeline?

I'm looking over a block of code I've used (sourced from another question) and I haven't been able to figure out what the . in .{process represents in this snippet (comments removed): Get-ItemProperty $path | .{process{ if ($_.DisplayName -and $_.UninstallString) { $_ } }} | Select-Object DisplayName, Publisher, InstallDate, DisplayVersion,...

Search for certain UPN suffix

How do I search AD users by UPN suffix in AD? The users are under Uofguelph/SEC213/users OU. Some users have @sec213.com suffix and some have @home.sec213.com suffix. I need to search for users who only have @sec213.com suffix. I have the following two code snippets. Code 1 gets all accounts...

Disconnect Session via Powershell [closed]

Is there a command to disconnect a user from a session on a server via PowerShell? To logoff i use: Logoff /server:<Server> <SessionID> ...

How do I write a loop to read text file and insert it to the database

I'm writing a powershell script to load text files from a specific folder into SQL server database, I have manage to do so but only one file by one file. I want the program to do this automatically once the user inputs the path and the file extension. For example:...

PowerShell logic to remove objects from Array

I'm trying to remove objects from an array that contain duplicates and only keep the ones with the highest number in TasteCode. The example below is highly simplified, but it shows the problem. Example: $Fruits Name | Color | TasteCode ----- ------ --------- Apple | Red | 2 Apple |...

Using --check on a md5sum command generated checksum file is failing

I'm encountering an error when I try and run md5sum -c on a checksum file I generated. I should mention that I'm running this from PowerShell (as a script will be running this eventually) and this is the cygwin version of md5sum. I have a test file, jira_defect.txt and I've...

CPU usage missing from log for some processes

I'm trying to get information on all processes and services and save it into a .log. Here my Problem: Some processes have noting inside the CPU table, there I want to add something like "Nothing". How can I achieve that? That is my code so far: $ProcessTable = @{Expression={$_.ProcessName};Label="ProcessName";Width=40}, @{Expression={$_.CPU};Label="CPU";Width=20}...

Format a command in powershell including a comma, can't find the right way to escape

I have a command that I need to run in a Powershell script, the command is : ".\pacli DELETEUSER DESTUSER='"[email protected]`,com"' sessionid=333" | invoke-expression The comma (,) in here :[email protected],com is not a mistake, and that's what is giving me the hard time. I tried to escape the comma with `...

Send email with body consisting of objects

I am trying to write a script to search through AD and look for any stale computers and then sends an email to me. However, there are 3 requirements: get the lastlogondate for any pc that is older than 90 days once I get that list, I do a ping...

View All Certificates On Smart Card

I am trying to create a script to remove all but the newest certificate from any given smart card (in the SC Reader at the time). This is something that I intend to be able to distribute to end users, so it should be self sufficient. My first issue is...

Remove all folders .old

I'm trying to delete all folders in \\kiewitplaza\vdi\Appsense_profiles that end with .old. The piece I have that says Write-Host $name is just me trying to test before I delete anything. $name = Get-ChildItem "\\kiewitplaza\vdi\Appsense_profiles" if ($name.name.EndsWith(".old")) { Write-Host $name #Remove-Item "\\kiewitplaza\vdi\Appsense_profiles\$name.old" } ...

How to pass a switch variable?

& "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" ` -Verbose -ProjectFilePath $project -PO "$packOptions" -NPFPPTNG So if I provide the command line above in PowerShell the call works correctly. If I try something like this: if ($NoPromptForPushPackageToNuGetGallery) { $xtraOptions += " -NPFPPTNG " } & "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" ` -Verbose -ProjectFilePath $project -PO "$packOptions"...

win32_physicalMemory.Capacity returns null in powershell

This is a really weird issue that only occurs on one computer that I've tested on. I have the following line of code: (get-WmiObject win32_physicalMemory -Impersonation 3 -ComputerName "localhost").Capacity which returns null for some reason. However, on the same computer, if I run the command: get-WmiObject win32_physicalMemory -Impersonation 3 -ComputerName...

Why doesn't “go get gopkg.in/…” work while “go get github.com/…” OK?

I try to use go get gopkg.in/fatih/pool.v2 to install pool according to Readme.md, but can't success: C:\Users\xiaona\Documents\GitHub> go get -v gopkg.in/fatih/pool.v2 Fetching https://gopkg.in/fatih/pool.v2?go-get=1 https fetch failed. Fetching http://gopkg.in/fatih/pool.v2?go-get=1 import "gopkg.in/fatih/pool.v2": http/https fetch: Get http://gopkg.in/fatih/poo l.v2?go-get=1: dial tcp ConnectEx tcp: A connection attempt failed because the connected party did not...

Powershell workflow - Get-Service not filtering

I am trying to restart Windows services in parallel via Powershell workflow. When I use Get-Service -DisplayName "S*" outside of workflow I get expected results. However, when I use the same in workflow, I get ALL services instead. It seems that -Displayname parameter is ignored in workflow. How do I...

Powershell comparison of text file

I'm just wondering if it's possible to compare two text file and check if there's a difference between them? What I mean is like this, For example I have text1.txt : 123 456 789 000 and I have text2.txt : 123,test,input,bake 789,input,cake,bun Expected output : 456 does not exist in...

PS pipe WorkingSet as variable

I have this which gives me the WorkingSet memory usage I'm after: $mem=Get-Process spiceworks | Select-Object Name,@{Name='WorkingSet';Expression={($_.WorkingSet/1KB)}} But I'm looking to only have the actual amount as the variable so I can then work with that to monitor it. I want to set it so it alerts me if it...

Powershell Reading text file

I'm just wondering if it's possible to read the content of text file with specific index? What I mean is like this, for example: I have text file like this, 'test1.txt' 12345678900 ## ## readthistext 54321123440 ## ## hellothistext I just want to read the content of text file after...

Difference between EV sign certificate and regular ones

My company is deciding which type of certificate to choose: the EV certificate or the regular one. I would like to know the difference between them. I know that the EV ones put some kind of reputation to the application you sign, but I'm not sure about the difference. Two...

PowerShell - Convert CSV to XLSX

I found this script on here, please help me understand this better. What is the whole "gps" part of the script for? What part of this script is overwriting my original CSV and copying in the PC's taskmanager list? Processes. What does this do, why 51? ($xlOut,51) I went searching...

Filter and delete Registry values with Where-Object

I'm not sure why I'm finding this so difficult. From under a particular registry key, I'd like to query certain registry-values based on their data (not name), and delete the resulting registry-values. For example: How would I delete any values in this key that contain, let's say, "foo". I can...

Increment Serial Number using EXIF

I am using ExifTool to change the camera body serial number to be a unique serial number for each image in a group of images numbering several hundred. The camera body serial number is being used as a second place, in addition to where the serial number for the image...

Turn environment variable into an array

I need to pass an array to a PowerShell subprocess and was wondering how I can turn an environment variable (string) into a PowerShell array. Is there a convention I need to follow so PowerShell will do it for me automatically or I just need to parse it myself? I'm...

Get IP address of the Network Adapter of a computer having No gateway

I've a project to add persistent routes on a list of servers which I need to do through Powershell. Our environment has 2 NIC's for every server , one production one backup. For this I need to fetch the Backup IP address of the computer , replace the last octet...

Define an array with prefixes using the range operator

From this I can see I can do this with range operator: $myArray = @(4..9) But how can I do something like this: $myArray = @(usr4..9) I have tried various deviations of this with nonsense errors: $myArray = 4..9 | %\{ "usr$_"\} ...

Get actual path from path with wildcard

When using Test-Path in an if statement, I am looking to get the path that the if statement succeeds with. For example, these files exist in C: C:\Test6_1_15.txt C:\Test6_2_15.txt C:\Test6_3_15.txt C:\Test6_4_15.txt what do I do in the "then" branch? $Path = "C:\Test6_*_15.txt" if (Test-Path $Path) { # if test passes...

Extract e-mail from grouped objects

I have some code that pull user accounts from an OU in AD. I am sorting it using Group-Object so I know how many users are using the same email address. Code below, the $OuUser uses Get-ADUser with Properties and Filter set to *. $Duplicates = $OUUser | Select samaccountname,...

How do I select a string from a string and replace it in powershell?

I'm trying to write a powershell instance that finds and replaces each instance of text and replaces it. UserRights "rights_wo_view" I need to place parenthesis around the quotes. I've been trying all kinds of things, but I'm running flat. $files = get-item C:\Users\programmer\Documents\Project\tsbrick\*.asp foreach ($file in $files) {(Get-Content $file) select-string...

Issue filtering out certain event logs from output

So I've coded a little script that sends me the last 24 hours event logs for my Servers in a nice HTML Email to save me having to log on to each Server, etc. It works well except some of our applications produce loads of events that I want to...

PowerShell XML formatting issue

I'm having trouble getting a properly formatted XML file using the following code: # Get Computer System info $CompInfo = Get-WmiObject Win32_ComputerSystem $CompName = $CompInfo.Name # Get IP Address $IPAddressTemp = Test-Connection $CompName -count 1 | select Address,Ipv4Address $IPAddress = $IPAddressTemp.IPV4Address # Begin Writing values to XML Document $filePath =...

Why does piping Get-PSSession to Exit-PSSession not work?

I'm creating a new Powershell session like so: New-PSSession -ConnectionUri https://myserver:12345 -Credential myserver\username -Authentication default This is working fine, I can do Get-PSSession and it provides me with that one session. However, when trying to pipe the result to Exit-PSSession things go haywire. So this: Get-PSSession | Exit-PSSession Or this:...

How to get current working directory inside a Cmdlet

I am writing a Cmdlet for PowerShell in C#. I am subclassing a Cmdlet and NOT a PSCmdlet. Is there a way to get the current directory from PowerShell? I could do so with the PSCmdlet using GetVariableValue("pwd"). But in the Cmd class I do not have that available. Environment.CurrentDiretory...

Logging actual error when script fails

I have a script here that reads a list of computers and changes the administrator password. When the script is ran, it'll have a log file that says whether the task succeeded or fail. But I also want to log the actual error to the log when it fails. How...

Sample X509 Certificates with Wrong ASN.1 Encode

For testing purpose, I am looking for sample X509 Certificates with wrong ASN.1 encoding, like Null with length more then Zero, etc. Any pointers??

setting up azure ad certificate auth using powershell

I am attempting to setup an Azure AD application to authenticate using a certificate. I have been using this guide to successfully set this up after failing following this guide. I wish to now automate the process so it can be added to our general build scripts, looking at the...

How to create a powershell script that triggers a NuGet Update-Package –reinstall?

I have a nuget spec that installs both library file (dll) and two zip packages on a specific folder. Updating the packages is no issue when doing it from Visual Studio 2013 manually. However, when it is being triggered from either our CI servers TeamCity and CCNet, it is only...

Get list of files whose creation date is greater than some date time

I have a date 2015/05/28 I want to list all files using order by creation date whose creation date is greater than that using PowerShell. How could I do that? I googled for it and found Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" but no idea how to compare it with creation date...

Loop Issue - Remote Server

I wrote a small script to get some basic information off a few remote servers. But my output it is a bit odd. I believe my issue is with my $DRIVE function. Code: $serversList = 'svr01.xxx.com', 'svr03.xxx.com', 'svr05.xxx.com', 'svr06.xxx.com', 'svr08.xxx.com' #End of Server List Write-Output "Start of Hal0 `n"; ForEach...

Error with Get-ADUser: Invalid enumeration context

I posted this question the other day Extract e-mail from grouped objects $OuUser = @{} $OuUser = Get-AdUser -Properties * -Filter * -SearchBase "domain" $Duplicates = $OuUser | Select samaccountname, mail,UserPrincipalName | Group-Object Mail | Where{$_.Count -gt 1} $Duplicates | Select Name,Count,@{l='Accounts';e={($_.Group|Select -Expand samaccountname) -join ';'}} | Export-CSV E:\Damo\Duplicates.csv -NoTypeInfo...

Where is git command after installing “GitHub for Windows”? [closed]

After installing GitHub for Windows, I can use git command in Powershell directly: C:\Users\xiaona\Documents\GitHub> git usage: git [--version] [--help] [-C <path>] [-c name=value] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] [-p|--paginate|--no-pager] [--no-replace-objects] [--bare] [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] <command> [<args>] The most commonly used git commands are: add Add file contents to the index bisect...

Post messages from async threads to main thread in F#

There is a subscription to an observable that sends out log messages. Some of the log messages come from other threads because they are are in F# async blocks. I need to be able to write out the messages from the main thread. Here is the code that currently filters...

PowerShell Where-Object $_.name -like -in $list

New to PowerShell and ran into a bit of a road block. I am trying to pull program name and version information from multiple servers. I have a list of the program names in a $list variable but the program names also contain the version numbers in them. I am...

Join SQL query Results and Get-ChildItem Results

Background: I have a directory with a number of files that are imported to SQL server. Task: Creating a PowerShell script which will pick up files within this directory and use the filenames as in the SQL query. Ultimate objective: To display SQL results besides the filenames but the resultset...

How to retrieve the name and path of VM's through powercli

am using the below script to retrieve the NAME and PATH of the VM's and in the PATH am getting the full length path which i dont want it, i just need the path which is displaying after the Resources in the output here is my code: function Get-Path{ param($Object)...

Powershell Invoke-Command with PSCredential Cannot process argument transformation on parameter 'Credential'

I'm trying to run a powershell invoke-command call with a PSCredential as parameter. But the call fails with the error: Invoke-Command : Cannot process argument transformation on parameter 'Credential'. userName" Here is the detailed output I get : error 17-Jun-2015 14:33:53 Invoke-Command : Cannot process argument transformation on parameter 'Credential'....