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
为什么我写什么 小蓝窗都没反应“PS C:\Users\Administrator> # 1. 修复错误的快捷方式 >> $desktopPath = [Environment]::GetFolderPath("Desktop") >> $badShortcut = Join-Path $desktopPath "PS7_Direct.lnk" >> >> if (Test-Path $badShortcut) { >> try { >> # 检查快捷方式目标 >> $shell = New-Object -ComObject WScript.Shell >> $shortcut = $shell.CreateShortcut($badShortcut) >> >> if ($shortcut.TargetPath -notlike "*pwsh.exe") { >> # 创建正确的快捷方式 >> $correctShortcut = Join-Path $desktopPath "PS7_Correct.lnk" >> $pwshPath = (Get-Command pwsh).Source >> >> $newShortcut = $shell.CreateShortcut($correctShortcut) >> $newShortcut.TargetPath = $pwshPath >> $newShortcut.Arguments = "-NoExit" >> $newShortcut.IconLocation = "$pwshPath,0" >> $newShortcut.WorkingDirectory = $desktopPath >> $newShortcut.Save() >> >> # 替换错误快捷方式 >> Remove-Item $badShortcut -Force >> Rename-Item $correctShortcut "PS7.lnk" >> >> Write-Host "已修复快捷方式: PS7.lnk" -ForegroundColor Green >> } >> } >> catch { >> Write-Host "快捷方式修复失败: $($_.Exception.Message)" -ForegroundColor Red >> } >> } >> >> # 2. 修复配置文件路径问题 >> $ps7ProfileDir = Join-Path ([Environment]::GetFolderPath('MyDocuments')) "PowerShell" >> $ps7ProfilePath = Join-Path $ps7ProfileDir "Microsoft.PowerShell_profile.ps1" >> >> $winPSProfileDir = Join-Path ([Environment]::GetFolderPath('MyDocuments')) "WindowsPowerShell" >> $winPSProfilePath = Join-Path $winPSProfileDir "Microsoft.PowerShell_profile.ps1" >> >> # 确保正确的配置文件存在 >> if (-not (Test-Path $ps7ProfilePath)) { >> # 从Windows PowerShell位置复制配置文件 >> if (Test-Path $winPSProfilePath) { >> $null = New-Item -ItemType Directory -Path $ps7ProfileDir -Force >> Copy-Item $winPSProfilePath $ps7ProfilePath -Force >> Write-Host "已复制配置文件到PowerShell 7位置" -ForegroundColor Cyan >> } >> else { >> # 重新创建配置文件 >> $profileContent = @' >> # PowerShell 7 基础配置 >> Write-Host "✅ PowerShell $($PSVersionTable.PSVersion) 已加载" -ForegroundColor Green >> Set-Alias ll Get-ChildItem >> '@ >> $profileContent | Out-File $ps7ProfilePath -Encoding UTF8 >> Write-Host "已创建基础配置文件" -ForegroundColor Cyan >> } >> } >> >> # 3. 添加版本检测和自动修复 >> $autoFixScript = @' >> # 自动环境修复脚本 >> function Repair-PS7Environment { >> # 检查PowerShell版本 >> if ($PSVersionTable.PSVersion.Major -lt 7) { >> Write-Host "⚠️ 当前运行的是PowerShell $($PSVersionTable.PSVersion)" -ForegroundColor Red >> Write-Host "正在尝试启动PowerShell 7..." -ForegroundColor Yellow >> >> try { >> # 尝试通过快捷方式启动 >> $desktop = [Environment]::GetFolderPath("Desktop") >> $shortcut = Join-Path $desktop "PS7.lnk" >> >> if (Test-Path $shortcut) { >> $shell = New-Object -ComObject WScript.Shell >> $shell.Run($shortcut) >> } >> else { >> # 直接启动pwsh >> Start-Process pwsh -ArgumentList "-NoExit" >> } >> >> # 退出当前会话 >> exit >> } >> catch { >> Write-Host "启动失败: $($_.Exception.Message)" -ForegroundColor Red >> } >> } >> >> # 检查配置文件加载 >> if (-not (Test-Path $PROFILE)) { >> Write-Host "⚠️ 配置文件未找到" -ForegroundColor Yellow >> Write-Host "正在创建基础配置文件..." -ForegroundColor Cyan >> >> @' >> # PowerShell 7 基础配置 >> Write-Host "✅ PowerShell $($PSVersionTable.PSVersion) 已加载" -ForegroundColor Green >> Set-Alias ll Get-ChildItem >> '@ | Out-File $PROFILE -Encoding UTF8 >> } >> } >> >> # 启动时自动运行修复 >> Repair-PS7Environment >> '@ >> >> # 将修复脚本添加到配置文件 >> $currentProfile = if (Test-Path $ps7ProfilePath) { >> Get-Content $ps7ProfilePath -Raw >> } else { "" } >> >> if (-not $currentProfile.Contains("Repair-PS7Environment")) { >> $autoFixScript + "`n`n" + $currentProfile | Out-File $ps7ProfilePath -Encoding UTF8 >> Write-Host "已添加自动修复功能到配置文件" -ForegroundColor Green >> } >> >> # 4. 创建验证脚本 >> $verificationScript = @' >> # 环境验证脚本 >> Write-Host "`n=== PowerShell 7 环境验证 ===" -ForegroundColor Cyan >> >> # 1. 版本验证 >> Write-Host "PowerShell 版本: $($PSVersionTable.PSVersion)" >> if ($PSVersionTable.PSVersion.Major -ge 7) { >> Write-Host "✅ 版本验证通过" -ForegroundColor Green >> } else { >> Write-Host "❌ 需要PowerShell 7或更高版本" -ForegroundColor Red >> } >> >> # 2. 配置文件验证 >> Write-Host "`n配置文件状态: " -NoNewline >> if (Test-Path $PROFILE) { >> Write-Host "已加载" -ForegroundColor Green >> Write-Host "配置文件路径: $PROFILE" >> } else { >> Write-Host "未找到" -ForegroundColor Red >> } >> >> # 3. 快捷方式验证 >> Write-Host "`n桌面快捷方式验证:" >> $desktop = [Environment]::GetFolderPath("Desktop") >> $shortcuts = Get-ChildItem $desktop -Filter "PS7*.lnk" >> >> if ($shortcuts) { >> foreach ($shortcut in $shortcuts) { >> $shell = New-Object -ComObject WScript.Shell >> $sc = $shell.CreateShortcut($shortcut.FullName) >> >> $status = if ($sc.TargetPath -like "*pwsh.exe") { >> "✅ 有效" >> } else { >> "❌ 无效" >> } >> >> Write-Host " - $($shortcut.Name): $status" -ForegroundColor $( >> if ($status -eq "✅ 有效") { "Green" } else { "Red" } >> ) >> Write-Host " 目标: $($sc.TargetPath)" >> Write-Host " 参数: $($sc.Arguments)" >> } >> } else { >> Write-Host " - 未找到PS7快捷方式" -ForegroundColor Yellow >> } >> >> # 4. 基本功能测试 >> Write-Host "`n基本功能测试:" >> try { >> $result = Invoke-RestMethod -Uri "https://httpbin.org/get" -TimeoutSec 5 >> Write-Host " - HTTP测试: 成功" -ForegroundColor Green >> } catch { >> Write-Host " - HTTP测试: 失败 - $($_.Exception.Message)" -ForegroundColor Red >> } >> >> try { >> $json = '{"test": true}' | ConvertFrom-Json >> Write-Host " - JSON测试: 成功" -ForegroundColor Green >> } catch { >> Write-Host " - JSON测试: 失败" -ForegroundColor Red >> } >> >> Write-Host "`n验证完成!" -ForegroundColor Cyan >> '@ >> >> # 保存验证脚本 >> $verifyPath = Join-Path $env:TEMP "Verify-PS7Environment.ps1" >> $verificationScript | Out-File $verifyPath -Encoding UTF8 >> >> # 5. 启动验证 >> Write-Host "`n正在启动环境验证..." -ForegroundColor Cyan >> Start-Process pwsh -ArgumentList "-NoExit", "-File `"$verifyPath`"" >> >> # 检查PowerShell版本 >> $PSVersionTable.PSVersion >> >> # 检查配置文件 >> Test-Path $PROFILE >> >> # 检查快捷方式目标 >> $shell = New-Object -ComObject WScript.Shell >> $shortcut = $shell.CreateShortcut("C:\Users\Administrator\Desktop\PS7.lnk") >> $shortcut.TargetPath >> >> # 直接运行验证脚本 >> & "$env:TEMP\Verify-PS7Environment.ps1" >> >> # 创建一键修复快捷方式 >> $desktop = [Environment]::GetFolderPath("Desktop") >> $shortcutPath = Join-Path $desktop "Fix_PS7.lnk" >> $shell = New-Object -ComObject WScript.Shell >> $shortcut = $shell.CreateShortcut($shortcutPath) >> $shortcut.TargetPath = "pwsh.exe" >> $shortcut.Arguments = "-Command `"& {Start-Process pwsh -ArgumentList '-NoExit','-File',`"$verifyPath`"}`"" >> $shortcut.IconLocation = "C:\Windows\System32\shell32.dll,2" >> $shortcut.Save() >> >> # 每月自动验证环境 >> $trigger = New-JobTrigger -Daily -At "9:00 AM" -DaysInterval 30 >> $action = { >> & "$env:TEMP\Verify-PS7Environment.ps1" | Out-File "$env:TEMP\PS7_HealthCheck.log" >> } >> Register-ScheduledJob -Name "PS7_Maintenance" -ScriptBlock $action -Trigger $trigger >>”
最新发布
08-17
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值