execute Windows powershell command or .ps1 file by java

本文介绍了一种使用Java调用Powershell的方法,并提供了两种可行的实现方式:执行Powershell脚本和执行Powershell命令。文章还包含具体的Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:http://social.technet.microsoft.com/Forums/windowsserver/en-US/d32537bd-0aef-440e-8760-6b3085390c37/executing-powershell-script-via-java?forum=winserverpowershell

最近在尝试用Java调用Powershell, 搜了狠多资料,终于发现下面的可行方案
推荐第一种,因为对于第二种,假如命令为:& "C:\Program Files\Markin\selenium\CloseNousedApp.ps1" 就不会执行,也不报错


1 executePSScript("C:/Program Files/automationscripts/Sample/Markin/src/actions/selenium/CloseNousedApp.ps1","");
2 executePSCommand("Write-Host \"Markin\"");

 public static String executePSCommand(String command) throws Exception 
    {
          //String cmd = "cmd /c c:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell -noprofile -noexit -executionPolicy restricted Set-ExecutionPolicy -Scope Process RemoteSigned " + command;
      	String cmd = "cmd /c c:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive " + command;
          return exec(cmd);
    }
  
  	public static String executePSScript(String scriptFilename, String args) throws Exception {
		if (!new File(scriptFilename).exists())
			throw new Exception("Script file doesn't exist: " + scriptFilename);
		
		String cmd = "cmd /c c:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive -file \"" + scriptFilename + "\"";
		if (args != null && args.length() > 0)
			cmd += " " + args;
		return exec(cmd);
	}
  
  
    private static String exec(String command) throws Exception 
    {        
    	StringBuffer sbInput = new StringBuffer();
        StringBuffer sbError = new StringBuffer();
        
		Runtime runtime = Runtime.getRuntime();
		Process proc = runtime.exec(command);
		proc.getOutputStream().close();
    
       	InputStream inputstream = proc.getInputStream();        
       	InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
        
        String line;
        while ((line = bufferedreader.readLine()) != null) 
        {
        	sbInput.append(line + "\n");
        }
        
        inputstream = proc.getErrorStream();
        inputstreamreader = new InputStreamReader(inputstream);
        bufferedreader = new BufferedReader(inputstreamreader);
        while ((line = bufferedreader.readLine()) != null) 
        {
           		sbError.append(line + "\n");
        }
        if (sbError.length() > 0)
        	throw new Exception("The command [" + command + "] failed to execute!\n\nResult returned:\n" + sbError.toString());

       		return "The command [" + command + "] executed successfully!\n\nResult returned:\n" + sbInput.toString();
	}


$ : 无法将“$”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:4 字符: 1 + $ taskName = "FaceLogin Autostart" + ~ + CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException $ : 无法将“$”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:5 字符: 1 + $ exePath = "C:\FaceLogin\FaceLogin.exe" # 鏇挎崲涓哄疄闄呰矾寰?$ monitorScrip ... + ~ + CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException $ : 无法将“$”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:6 字符: 1 + $ checkInterval = 60 # 妫€鏌ラ棿闅?绉? + ~ + CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException $ : 无法将“$”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:9 字符: 1 + $ monitorScript = @" + ~ + CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Set-Content : 找不到接受实际参数“monitorScriptPath”的位置形式参数。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:56 字符: 1 + Set-Content -Path $ monitorScriptPath -Value $ monitorScript -Force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Set-Content],ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetContentCommand $ : 无法将“$”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:64 字符: 1 + $ action = New-ScheduledTaskAction -Execute "powershell.exe" ` + ~ + CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException $ : 无法将“$”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:68 字符: 1 + $ trigger = New-ScheduledTaskTrigger -AtStartup + ~ + CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -LogonType : 无法将“-LogonType”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请 确保路径正确,然后再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:71 字符: 5 + -LogonType ServiceAccount -RunLevel Highest + ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (-LogonType:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException $ : 无法将“$”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:74 字符: 1 + $ settings = New-ScheduledTaskSettingsSet ` + ~ + CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Register-ScheduledTask : 无法处理对参数“Action”的参数转换。无法将值“$”转换为类型“Microsoft.Management.Infrastructu re.CimInstance[]”。错误:“无法将值“$”转换为类型“Microsoft.Management.Infrastructure.CimInstance”。错误:“指定的参 数已超出有效值的范围。 参数名: className”” 所在位置 C:\FaceLogin\install_facelogin_task.ps1:83 字符: 13 + -Action $ action ` + ~ + CategoryInfo : InvalidData: (:) [Register-ScheduledTask],ParameterBindingArgumentTransformationExceptio n + FullyQualifiedErrorId : ParameterArgumentTransformationError,Register-ScheduledTask $ : 无法将“$”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:90 字符: 1 + $ task.Settings.RestartInterval = "PT5M" # 姣?鍒嗛挓閲嶈瘯 + ~ + CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException $ : 无法将“$”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\FaceLogin\install_facelogin_task.ps1:91 字符: 1 + $ task.Settings.RestartCount = 3 # 鏈€澶氶噸璇?娆?$ task | Set-Sch ... + ~ + CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 上面给出的install_facelogin_task.ps1脚本运行报错
06-24
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值