Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

occasional Windows permission error when calling PowerShell from Java - "running scripts disabled"

I have a Java program that does a shell call to invoke PowerShell with a script.

My PS script line looks like this:

execPS:powershell -command "& 'P:/PSScripts/DownloadSslHtml.ps1' -url 'https://somewebsite.com' -outputFile 'P:/DownloadedData/SomeFile.zip' -PFXPath 'P:/Properties/Config/certfile.pfx' -PFXPassword 'cert_password'"

The PS script in question has the following code:

param([string]$url = "https://somewebsite.com",
[string]$outputFile = "P:/DownloadedData/someoutput.html",
[string]$PFXPath = "P:/Properties/Config/certfile.pfx",
[string]$PFXPassword = "cert_password")

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($PFXPath,$PFXPassword,'UserKeySet')
Invoke-WebRequest -Uri $url -Certificate $cert -OutFile $outputFile -Verbose

As you can see, it's pretty simple.

My Java shell call looks like this:

public static String downloadSslWithPshell(String url, String outputFileName, String certName,
                                           String password, boolean waitFor){
    String res = "";
    try {
        ConfigStore configStore = ConfigStore.getInstance();
        String driveLetter = configStore.getDriveFor514();
        String execPS = "powershell -command \"& '" + driveLetter + "PSScripts/DownloadSslHtml.ps1' -url '"
                + url + "' -outputFile '" + outputFileName + "' -PFXPath '"
                + certName + "' -PFXPassword '" + password + "'\"";
        System.out.println("execPS:" + execPS);
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec(execPS);
        if(waitFor) {
            try {
                int resultCode = proc.waitFor();
                if (resultCode == 0) {
                    System.out.println("Script run without errors!");
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(WebManagement.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        //from experience we need to put a pause to let it run
        try {
            TimeUnit.MILLISECONDS.sleep(1600);
        } catch (InterruptedException ex) {
            Logger.getLogger(WebManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
        String line;
        InputStream errStream = proc.getErrorStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(errStream));
        int countError = 0;
        String strError = "";
        while ((line = reader.readLine()) != null) {
            countError++;
            if(countError<=2){
                strError = strError+line;
            }
        }
        proc.getOutputStream().close();
        if(countError== 0){
            res = "200";
        } else {
            res = strError;
        }
    } catch (IOException ex) {
        Logger.getLogger(WebManagement.class.getName()).log(Level.SEVERE, null, ex);
    }
    return res;
}

Here's what happens: 95% of the time the program goes on executing the PowerShell script and it successfully download the file per call. However about 5% of the time, I get this error message:

& : File P:\PSScripts\DownloadSslHtml.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.

This doesn't make much sense to me. I have permissions to run PS scripts on my machine and if I run the script manually from PS GUI, it runs fine. This is an intermittent issue, it seems to only occur occasionally and never consistently.

I'm wondering if this could be an Active Directory issue or a network issue where the system is not able to retrieve the policy? Just a thought, I really have no idea why I'm getting this error. Thoughts? I added " -ExecutionPolicy Bypass" to the PS command arguments so I guess we'll see if that helps.

like image 870
tuj Avatar asked Jan 31 '20 16:01

tuj


People also ask

How do I enable PowerShell scripts execution in Windows 10?

Press “Windows + I” to open settings and click on “Update & Security”. On the left sidebar, click “For developers”, then scroll down to the “PowerShell” subheading. Tick “change execution policy to allow local PowerShell scripts to run without signing.

Why are PowerShell scripts disabled by default?

While running PowerShell script, if you get running scripts is disabled on this system, it is because the PowerShell execution policy is set up by default as Restricted and doesn't allow to run script. PowerShell has built-in security features implemented.


1 Answers

If you use the command:

Get-ExecutionPolicy -List

You will see there are multiple levels of scopes that can each have their own Execution policy, while I am not sure why your results are so inconsistent, I suspect it may have to do with your CurrentUser policy being undefined. Try running the command

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass
like image 149
LogRhythm Avatar answered Oct 13 '22 18:10

LogRhythm