我正在为我的公司创建一个有点复杂的编译后脚本环境,它将处理许多移动的部件。使用Powershell脚本提供了更大的灵活性,因此我已经开始学习它。
但是,在安装Java证书时会出现输出重定向问题。
现在,一切都如期而至。证书的检查、删除证书,甚至安装证书都可以正常工作--除了一个小问题:
(这是脚本成功运行的输出)
命令:C:\ Files\Java\jre1.8.0_261\bin\keytool.exe命令: C:\Program证书添加到keystore <--这里是安装在商店中的Java。
我使用"&$Command $args“方法调用所有外部命令,下面是我正在运行的脚本。
# This function is used all over the place to streamline the external command execution of
# KeyTool, Sonar Scanner, and MSBuild
function Invoke([String] $command, [String[]] $arguments)
{
Write-Host " [Commnad: $command]"
Write-Host " [Arguments: $arguments]"
&$command $arguments
}
function ValidateKeyTool()
{ # Our developers may or maynot have the same version of java so this is to find the most recent version on their system
$path = [System.IO.Directory]::GetFiles("C:\Program Files (x86)\Java", "keytool.exe", [System.IO.SearchOption]::AllDirectories);
$path = $path + [System.IO.Directory]::GetFiles("C:\Program Files\Java", "keytool.exe", [System.IO.SearchOption]::AllDirectories);
$path = $path | Sort-Object -Descending;
$script:KeyTool = $path | Select -First 1;
$script:KeyStore = (Join-Path -Path (Split-Path (Split-Path $path)) -ChildPath "lib\security\cacerts");
return ([System.IO.File]::Exists($KeyTool) -and [System.IO.File]::Exists($KeyStore));
}
function CheckCertExists()
{
if (ValidateKeyTool)
{
$args = @("-list", "-storepass", """storepass""", "-keystore", """$KeyStore""", "-alias", """ourcert.crt""");
Invoke $KeyTool $args | Out-Null;
return ($LastExitCode -eq 0)
}
else
{
throw "Unable to determine Java KeyTool or KeyStore";
}
}
function InstallCert()
{
if (!(CheckCertExists))
{
$args = @("-import", "-storepass", """storepass""", "-keystore", """$KeyStore""", "-alias", """ourcert.crt""", "-file", $CertFile, "-noprompt");
Invoke $KeyTool $args | Out-Null; #this DOESN'T Work, the Out-Null doesn't trap the output
if ($LastExitCode -eq 0)
{
Write-Host " Java Cert Installed in Store."
}
else
{
throw "Error occured attempting to Install the Java Cert into the Store."
}
}
else
{
Write-Host " Java Cert already installed."
}
}对于KeyTool的所有执行都会按照预期将输出捕获为-list、-delete,而不是-import。不管我尝试过什么,带有"-import“的keytool总是生成"Certificate”输出消息。我想抑制它,只为成功或失败而退出$LastExitCode。
发布于 2020-10-20 19:30:58
原因很可能是消息被输出到另一个输出流。为了前夫。不是将消息输出到标准成功流(1),而是将消息输出到错误流(2)或警告流(3)或另一个。到| Out-Null的管道将只处理成功流,例如:
PS C:\> Write-Output "hi" | Out-Null
PS C:\>
PS C:\> Write-Warning "hi" | Out-Null
WARNING: hi压制来自所有流的所有消息的钝锤方法是这样对重定向所有的溪流的:
Invoke $KeyTool $args *> $null“更好的”方法是,如果您知道消息被发送到哪个流,(对于ex )。错误流(2),您可以重定向各个流。为此,您可以将错误流(2)重定向到成功流(1),然后将成功流(1)重定向到$null。
Invoke $KeyTool $args 2>&1 > $nullhttps://stackoverflow.com/questions/64450227
复制相似问题