将具有绝对路径的变量传递给命令

Passing variable with absolute path to command

我正在尝试在 PowerShell 中使用 certutil.exe 导入证书和 CA 进行存储。 这是我的脚本:

$appDir="C:\Program Files\My App"
$certFilespec = $appDir + "\mycert.pfx"
certutil -p '""' -importPFX $certFilespec
$certFilespec = $appDir + "\myca.crt"
certutil -f -addStore Root $certFilespec

除了第三行之外的所有内容都成功执行。错误是:

PS C:\> certutil -p '""' -importPFX $certFilespec
CertUtil: -importPFX command FAILED: 0x80070002 (WIN32: 2)
CertUtil: The system cannot find the file specified.
PS C:\>

当我使用字符串而不是 $certFilespec

certutil -p '""' -importPFX "C:\Program Files\My App\mycert.pfx"
certutil -f -addStore Root "C:\Program Files\My App\myca.crt"

一切执行成功。我还发现,当我使用相对路径时,它工作正常

PS C:\> cd '.\Program Files\My App'
$certFilespec=".\mycert.pfx"
certutil -p '""' -importPFX $certFilespec
CertUtil: -importPFX command completed successfully
PS C:\Program Files\My App>

一切正常。所以我猜想在使用绝对路径时引用存在一些问题。我不明白的是为什么同一个命令只是不同的选项 (-addStore/-importPFX).

我导入的文件是PKCS12证书+私钥(.pfx文件)。和 CA 证书(.crt 文件)。但这应该没有任何作用。

最好的猜测。 当它生成 $certFilespec 时,它生成的字符串没有注释,因此该命令将看到 C:\Program 并踢出一个错误。

$appDir="C:\Program Files\My App"
$certFilespec = $appDir + "\mycert.pfx"
$certFilespec

C:\Program Files\My App\mycert.pfx

你可以试试

$appDir='"C:\Program Files\My App\'
$certFilespec = $appDir + 'mycert.pfx"'

当运行产生

$certFilespec

"C:\Program Files\My App\mycert.pfx"

尝试修改这一行:

certutil -p '""' -importPFX $certFilespec

certutil -p '""' -importPFX "$certFilespec"

由于您的路径中有一个 space,它将单个路径参数分解为多个参数。