I have 2 powershell scripts that I run through c# code, the first downloads and installs OpenJDK and sets the appropriate environment variables. The second script just checks for the java version. I have it setup to run the second script (verification script) first and if OpenJDK is not found then to run the first script (download script) followed again by the second script (verification script). This seems to work most of the time but every now and then it seems to get "stuck" where the verification script always returns an error indicating that OpenJDK is not installed on the system. However, manually checking for OpenJDK (checking the installation location, checking the environment variables) tells that installation (through the download script) executed correctly.
The download script:
(New-Object System.Net.WebClient).DownloadFile(OpenJDK Download Link, Download Location);
Add-Type -AssemblyName System.IO.Compression.FileSystem;
[System.IO.Compression.ZipFile]::ExtractToDirectory(Download Location, "C:\Program Files\Java");
[Environment]::SetEnvironmentVariable("JAVA_HOME", "C:\Program Files\Java\jdk-13.0.2", [System.EnvironmentVariableTarget]::Machine);
[System.Environment]::SetEnvironmentVariable('Path', $env:Path + ";C:\Program Files\Java\jdk-13.0.2\bin", "Machine")
The verification script:
(Get-Command java | Select-Object -ExpandProperty Version).tostring()
if working correctly the verification script returns: 13.0.2.0
The c# code I call these scripts through are the following:
public void Execute(string script)
{
using (var ps = PowerShell.Create())
{
var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
ps.Runspace = runspace;
ps.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted");
ps.AddParameter("Scope", "Process");
ps.AddScript(script);
var data = ps.Invoke();
runspace.Close();
}
}
public async Task ExecuteAsync(string script)
{
using (var ps = PowerShell.Create())
{
var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
ps.Runspace = runspace;
ps.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted");
ps.AddParameter("Scope", "Process");
ps.AddScript(script);
await Task.Factory.FromAsync(ps.BeginInvoke(), result => ps.EndInvoke(result));
runspace.Close();
}
}
it seems most easily reproducible if I teamviewer into another machine and run the scripts but I have been able to reproduce this on my local machine.