Search code examples
vbscriptkeytoolwsh

Automation of Java keytool command using VBScript to extract certificate metadata not working


Using the Java keytool utility, I'm attempting to automate the reading of metadata attached to certificates in a JKS file from two possible directories and output the metadata to a flat file (all from a Windows Server 2012 VM). I'm using this command syntax:

E:\Java\jre8\bin\keytool -list -v -keystore E:\foo\foo_trusts.jks > F:\foo_trusts.txt

The caveat: When performing this procedure manually, I need to press the Enter key at the password prompt to complete the keytool execution. The desired output is always produced in the F drive when following the manual approach from the Windows command line.

Here is the VBScript code I am attempting to use (including the code to emulate the Enter key press):

Option Explicit
Dim objFSO
Dim strDirectory, WshShell

strDirectory = "E:\foo"
strDirectory2 = "E:\bar"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")

If objFSO.FolderExists(strDirectory) Then
    WshShell.Run "E:\Java\jre8\bin\keytool -list -v -keystore E:\foo\foo_trusts.jks > F:\foo_trusts.txt"
    WScript.Sleep 5000
    WshShell.SendKeys "{ENTER}"
    WScript.Sleep 30000
ElseIf objFSO.FolderExists(strDirectory2) Then
    WshShell.Run "E:\Java\jre8\bin\keytool -list -v -keystore E:\bar\bar_trusts.jks > F:\bar_trusts.txt"
    WScript.Sleep 5000
    WshShell.SendKeys "{ENTER}"
    WScript.Sleep 30000

End If

WScript.Quit

The method of automation I'm using doesn't support running a VBScript directly, so I'm using a Windows batch file as a wrapper to call the VBScript. The content of the batch file is pretty straightforward:

cscript "E:\certMetaExtract.vbs"

When I run the batch file, I see a keytool.exe window pop up and disappear very quickly...but nothing else happens. When I check the F drive for the output from the VBScript, none is present.

Is there something I'm missing from this VBScript, or something I'm doing incorrectly, that's preventing the expected execution?


Solution

  • I identified the solution. The WshScriptRun object is typically not capable of reading standard output from a task execution. BUT, by adding "cmd /c" to the beginning of my Run strings, I was able to get the desired output in the F drive.

    WshShell.Run "cmd /c E:\Java\jre8\bin\keytool -list -v -keystore E:\foo\foo_trusts.jks > F:\foo_trusts.txt"