简体   繁体   中英

Run command prompt commands in powershell

The following are two commands that run in command prompt and create the required certificate files:

makecert –sv <cnName>.pvk -n "cn=<cnName>" <cnName>.cer -r -eku 1.3.6.1.5.5.7.3.1
pvk2pfx -pvk <cnName>.pvk -spc <cnName>.cer -pfx <cnName>.pfx -po <password>

I am trying to run the same commands in powershell using the following code:

$cnName = <sampleCnName> + ".com"
$pvkName = $cnName + ".pvk"
$cerName = $cnName + ".cer"
$pfxName = $cnName + ".pfx"
$certificatePassword = <password>

& "Makecert\makecert –sv $pvkName -n "cn=$cnName" $cerName -r -eku 1.3.6.1.5.5.7.3.1"
& "Makecert\pvk2pfx -pvk $pvkName -spc $cerName -pfx $pfxName -po $certificatePassword"

The current error is

& : The module 'Makecert' could not be loaded. For more information, run 'Import-Module Makecert'.

One issue is, while I run makecert and pvk2pfx command from the Makecert folder in the command prompt, I want to write the powershell script in the parent folder Makecert level. Wondering what is the correct way to do this.

Update: The following command worked in powershell:

$currentDirectory = Split-Path $Script:MyInvocation.MyCommand.Path
& "$currentDirectory\Makecert\makecert.exe" –sv actualCnName.pvk -n "cn=actualCnName" actualCnName.cer -r -eku 1.3.6.1.5.5.7.3.1 

You have 2 issues right now -

  1. If you want to invoke a tool from a relative path based in the current directory, Powershell requires .\\ qualification. ie makecert\\makecert.exe won't work, you need .\\makecert\\makecert.exe .

  2. If you are using & , the subsequent string should contain only the path and tool name, not any arguments. ie & "sometool.exe -a foo -b bar" is wrong, & "sometool.exe" -a foo -b bar is right.

Also note that & is not needed unless the path and/or tool name contain spaces or other special characters, or the path has been stored in a string for other reasons. Given your sample code, it's not strictly needed here.

So I would recommend:

$cnName = <sampleCnName> + ".com"
$pvkName = $cnName + ".pvk"
$cerName = $cnName + ".cer"
$pfxName = $cnName + ".pfx"
$certificatePassword = <password>

.\makecert\makecert.exe –sv $pvkName -n "cn=$cnName" $cerName -r -eku 1.3.6.1.5.5.7.3.1
.\makecert\pvk2pfx.exe -pvk $pvkName -spc $cerName -pfx $pfxName -po $certificatePassword

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM