Skip to content

Instantly share code, notes, and snippets.

@mavaddat
Last active September 7, 2019 01:50
Show Gist options
  • Save mavaddat/c9eaf52a0654462ff582f6d650138a62 to your computer and use it in GitHub Desktop.
Save mavaddat/c9eaf52a0654462ff582f6d650138a62 to your computer and use it in GitHub Desktop.
This creates a parameterized PowerShell function for compiling and running Java applications in .java files.
function Java-CompileRun {
Param(
[Parameter(Mandatory=$true)]
[String]
$javaFile,
[Parameter(Mandatory=$false)]
[String]
$path=$PWD,
[Parameter(Mandatory=$false)]
[String]
$jdkPath=$($(where.exe javac) -replace '\\[^\\]+$','')
)
$path = $path -replace '\\$',''
$jdkPath = $jdkPath -replace '\\$',''
if (-not (Test-Path -Path "$path\$javaFile") -and (Test-Path -Path "$path\$javaFile.java")) {
$javaFile = "$javaFile.java"
}
$quit = $false;
if(-not (Test-Path -Path "$jdkPath\javac.exe")){Write-Error -Message "Cannot find javac.exe at $jdkPath." -Category ObjectNotFound -RecommendedAction "Please ensure you are providing the correct path to the JDK bin directory"; $quit = $true;}
if(-not (Test-Path -Path "$jdkPath\java.exe")){Write-Error -Message "Cannot find java.exe at $jdkPath." -Category ObjectNotFound -RecommendedAction "Please ensure you are providing the correct path to the JDK bin directory"; $quit = $true;}
if(-not (Test-Path -Path "$path\$javaFile")) {Write-Error -Message "Cannot find $javaFile at $path\$javaFile." -Category ObjectNotFound -RecommendedAction "Please ensure you are providing the correct path and the correct filename to the .java file"; $quit = $true; }
if($quit){return}
$_javac = Start-Process -FilePath "$($jdkPath)\javac.exe" -ArgumentList "-Xlint:all $javaFile" -WorkingDirectory $Path -NoNewWindow -PassThru -Wait
if($_javac.ExitCode -eq 0){
$_java = Start-Process -FilePath "$($jdkPath)\java.exe" -ArgumentList "$($javaFile -replace '.java','')" -WorkingDirectory $path -NoNewWindow -PassThru -Wait
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment