gpt4 book ai didi

Java - 在同一 shell 中逐行执行命令

转载 作者:行者123 更新时间:2023-12-01 16:15:21 25 4
gpt4 key购买 nike

我是 Talend Open Studio 的 Java 新手。我想知道是否可以使用“Import-Module ActiveDirectory”执行 powershell.exe,然后启动动态命令,而无需使用“Import-Module ...”重新加载 powershell。

我知道这行不通,但我的想法可以这样翻译:

Runtime.getRuntime().Exec("powershell.exe");
Runtime.getRuntime().Exec("Import-Module ActiveDirectory");
Runtime.getRuntime().Exec("Get-ADUser TestLogin1");
Runtime.getRuntime().Exec("Set-ADUser -Identity TestLogin1 -Company MyCompany1");
Runtime.getRuntime().Exec("Get-ADUser TestLogin2");
Runtime.getRuntime().Exec("Set-ADUser -Identity TestLogin2 -Company MyCompany2");

为了让它发挥作用,我必须做......

Runtime.getRuntime().Exec("powershell.exe /c Import-Module ActiveDirectory ; Get-ADUser TestLogin");
Runtime.getRuntime().Exec("powershell.exe /c Import-Module ActiveDirectory ; Set-ADUser -Identity TestLogin1 -Company MyCompany1");
Runtime.getRuntime().Exec("powershell.exe /c Import-Module ActiveDirectory ; Get-ADUser TestLogin_2");
Runtime.getRuntime().Exec("powershell.exe /c Import-Module ActiveDirectory ; Set-ADUser -Identity TestLogin2 -Company MyCompany2");

我不想检查脚本文件,因为第一个更新命令 (Set-ADUser) 可能会对下一个更新命令产生影响。

谢谢。

最佳答案

我找到了一个使用 profesorfalken 的 jPowerShell 库的解决方案

https://github.com/profesorfalken/jPowerShell

//Creates PowerShell session (we can execute several commands in the same session)
try (PowerShell powerShell = PowerShell.openSession()) {
//Execute a command in PowerShell session
PowerShellResponse response = powerShell.executeCommand("Import-Module ActiveDirectory");

//Get an ADUser
PowerShellResponse response = powerShell.executeCommand("Get-ADUser TestLogin1");
//Print results ADUser
System.out.println("PS : " + response.getCommandOutput());
//Set an ADUser
PowerShellResponse response = powerShell.executeCommand("Set-ADUser -Identity TestLogin1 -Company MyCompany1");

//Get an ADUser
PowerShellResponse response = powerShell.executeCommand("Get-ADUser TestLogin2");
//Print results ADUser
System.out.println("PS : " + response.getCommandOutput());
//Set an ADUser
PowerShellResponse response = powerShell.executeCommand("Set-ADUser -Identity TestLogin2 -Company MyCompany2");

} catch(PowerShellNotAvailableException ex) {
//Handle error when PowerShell is not available in the system
//Maybe try in another way?
}

关于Java - 在同一 shell 中逐行执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62410801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com