Executing PowerShell script via JAVA
Hi,
I have simple powershell script as below :
# Filename: Hello.ps1
Write-Host
Write-Host 'Hello World!'
Write-Host "Good-bye World! `n"
# end of script
I wish to run this script via JAVA by the below JAVA code -
import java.io.*;
public class PsJava {
public static void main(String[] args)
throws IOException{
Runtime runtime = Runtime.getRuntime();
String cmds = (String)
"cmd /C powershell C:/Documents and Settings/vvenkata/My Documents/Hello.ps1";
Process proc = runtime.exec(cmds);
proc.getOutputStream().close();
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader =
new InputStreamReader(inputstream);
BufferedReader bufferedreader =
new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
Thanks
Now, why is that I am not able to see any print statements from Hello.ps1 ? Can anyone help me on this?
Hi,
I have place my powershell script in the 'C' directory. and i have changed my JAVA code as below, but it still doesn't give any output in my Eclipse Console.
import java.io.*;
public class PsJava {
public static void main(String[] args)
throws IOException{
Runtime runtime = Runtime.getRuntime();
String cmds = (String)
"cmd /c powershell c:/Hello.ps1";
Process proc = runtime.exec(cmds);
proc.getOutputStream().close();
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader =
new InputStreamReader(inputstream);
BufferedReader bufferedreader =
new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
Please advice me on this. If I have to create a batch file, then can you let me know how do I do that?
Thanks
Similar Messages
-
Executing powershell script via task scheduler
Hello,
I am trying to execute powershell script via windows task scheduler which will forcefully delete all email in a mailbox, but I am getting the below errors
Operational Code - 2
Task Category - Action Completed --- Task Scheduler successfully completed task "\IL98" , instance "{2b193375-cbd2-4986-918d-3cfd4027d6b6}" , action "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" with return code 0.
Last Run Result - 0X0
When I am adding additional cmdlets in the script "Set-ExecutionPolicy Unrestricted", I am getting Last Run Result 0X5 rest of the error remains the same.
Powershell version - 3.0
Task Scheduler version - 1.0
If I try to run the script manually via Exchange Powershell the script executes without any errors
Thanks in Advance,
Ankush ShahI figured out the problem, there wasn't any problem with the script but I had to correct inputs in windows task scheuler
Below is the resolution:
Under Actions:
Program/Script --> ws\System32\WindowsPowerShell\v1.0\powershell.exe
Add Argument --> -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto
; <filepath>"
Eariler I was writing the filepath after double quote "
Also I have selected the option "Run with Highest Privilages" to avoid
0x5 error -
Executing powershell scripts via Task Scheduler
Hi,
I have a powershell script that I wrote that when executed from the shell works fine but when executed from task scheduler does not work.
In my script, an email is sent out based on the results of the execution. When I run this from the shell, email goes out, when scheduled, no email and there is no indication of errors having occurred anywhere in the system.
Has anyone run into a similar issue?
I did change my powershell execution policy to be unrestricted (both in the x86 and x64 consoles). I am running Windows 2008 R2.
Thanks - Greg.Hi,
In addition the above suggestions, please also refer to the below threads:
Using Task Scheduler for a powershell script on server 2008
http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/e298d613-47b8-4492-92d1-0b55cc8497c1
Using Windows Task Scheduler to execute Powershell Script frequently
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/5901a6ad-ba18-4817-82a9-f75d2d6b439f
Hope this helps.
Best Regards,
Yan Li
Yan Li
TechNet Community Support -
Execute PowerShell Scripts via SAP NetWeaver Identity Management
Hello,
Has anyone implemented the execution of a PowerShell script from SAP NetWeaver Identity Management (7.1, 7.2, 8.0?). Currently implementing 8.0, and our client is looking to kick off PowerShell scripts that would generate Active Directory accounts, Exchange accounts etc.
Thanks!Hey Brendan,
We've done this out of a 7.2 implementation for exchange 2010 admin processes. We started with running powershell via a command line pass. It worked pretty well but it wasn't plain sailing. We used positional parameters to pass data to the scripts in question, we also had to come up with a return process that deals with any errors that might come of the powershell session. We had some issues with the shell sessions closing after the script completed.
We've since redesigned and now drop flat files to a constantly running powershell script that acts a bit like an IDM dispatcher (but obviously not integrated with IDM). It kicks off other powershell sessions and monitors their progress allowing it to process time outs, stack work up, etc.
We also found timing the processes to be an issue. If you create an AD account in IDM and then try to immediately move onto mailbox enable (for example) the account we created wasn't yet replicated to exchange so we had to build wait time into various parts of the process.
Thanks,
Pete. -
How to change maintenance powershell script via GPO?
Per suggestion reposted from here: http://social.technet.microsoft.com/Forums/windowsserver/en-US/6eece9d6-a524-48aa-8e64-7554f0ec9b31/how-to-change-maintenance-powershell-script-via-gpo?forum=winserverGP
Posted at http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/desktop-shortcuts-to-items-on-network-drives/94eddb27-342b-40fc-9ad4-677ff4ee8ebe?page=9&tm=1403700614489 originally.
There is a very annoying "feature" in Windows 7 called BrokenShortcuts.ps1 which is being called out weekly via maintenance task and if it finds more than 4 "broken" network shortcuts it removes them all. So it means if a user at this
moment is disconnected from the network he will lose all links to shares, network applications sitting on his desktop. Funny that there was no such script on Vista and i don't see this on Win8. On the post i have attached one user suggested to edit this script
and change 4 to 500 or whatever high number. That's fine for one time fix. But i need to do this for 200+ users. This file cannot be simply replaced by a script, so i'm wondering is there any way to do it via GPO?
I have already tried various startup scripts, but i'm not sure which user to put into commands.
I need to run this on startup:
takeown /F C:\Windows\diagnostics\scheduled\Maintenance\TS_BrokenShortcuts.ps1
icacls c:\windows\diagnostics\scheduled\maintenance\TS_BrokenShortcuts.ps1 /grant "some user":F
copy \\share\folder$\TS_BrokenShortcuts.ps1 C:\Windows\diagnostics\scheduled\Maintenance\ /YYou need to take time to study how Windows does these things. You can control them with GP which is what you asked. The article shows you how to disable elements of the tasks. Each task controls a script. If you disable the task the
script that deletes shortcuts will be stopped. Other maintenance tasks will continue to run.
Most of your problem is that you seem to want someone to provide a magical solution. In technology it is necessary to fully research your issues until you understand all aspects. After fully studying the issue you should understand the possible
solutions if they exist.
You claim to have deployed the patch that Microsoft released to fix the issue. You claim it didn't work. If that is the case then you need to call MS and \p[en a support incident. If Microsoft determines that you are right about the
patch not working you will not be charged for the call.
I know that learning how to support technology is hard and frustrating for newcomers. In time, by using these incidents to learn, you will become a seasoned technician and all of this will seem trivial. Until then we can only suggest that you
do things that most of us are familiar with. We cannot fix your network for you.
I think you haven't really posted in the GP forum but posted a question about GP in the server forum. Try posting in the GP forum.
http://social.technet.microsoft.com/Forums/windowsserver/en-US/home?forum=winserverGP
Here is one answer from the GP forum:
http://social.technet.microsoft.com/Forums/windowsserver/en-US/home?forum=winserverGP
http://social.technet.microsoft.com/Forums/windowsserver/en-US/600ca14f-8b1b-400c-b27f-a7f5733407ac/windows-scheduled-maintenance-task?forum=winserverGP
¯\_(ツ)_/¯ -
How execute Unix script from java?
Can I execute Unix script from java?
Yes. Using ProcessBuilder. And read [When Runtime.exec() wont|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. It's old, but pretty much all of it is still true.
-
Is it possible to execute SAPGUI scripts from java program?
Hi everyone..
I need to develop an java applications that executes the SAPGUI script or any technique that execute set of transaction as client.
Is it possible to execute SAPGUI scripts from java program? if so, how it can be achieved? is there any other technique to achieve above mention scenario?.
it will be more helpful, if docs related to that are shared..
Thanks in advanceOh, bummer. Would be much more convenient if I could just use iTunes for everything. Can't stand WMP. I wonder if WinAmp might be a good compromise?
Thanks for this answer . . .
Sharon -
Execute powershell script in OIM task
Hi everyone,
I have a powershell script.
I want to execute this script on exchange machine.
How can I do this?
Can you send a code blok that executes powershell script if you have?
Thanks.
Best regards.Hi FXE,
first of all, to protocol execution you can use the cmdlets Start-Transcript
and Stop-Transcript.
If it doesn't create a transcript at all, your error is with launching the console from task.
If it does create a transcript, you can (hopefully) see what the script wrote.
On general principle I'd recommend trying these things:
Try specifying the full path to powershell.exe
Make sure the user running the task has the necessary permissions
Make sure it's running as local admin (with maximum privileges)
Cheers,
Fred
There's no place like 127.0.0.1 -
Execute photoshop script via illustrator cs5
Hi
Is it possible to execute Photoshop script via illustrator
I have 2 different script
script 1 work in illustrator with eps file and export as jpeg
script 2 where i want to trim the exported jpeg for illustrator in photoshop and save it back
I have 2 differnt script with me
can anyone help me to club both and run at same time..
Thank you
Appuuse BridgeTalk to have Illustrator talk to Photoshop, here's a sample by Mark
Illustrator script to open file in Photoshop
or use inter app communication
open PS, open a document
// start your illustrator script
var Aidoc = app.activeDocument;
continue with your script
// when ready, call your photoshop script
// this sample alerts the active document name and closes it
photoshop.executeScript("alert('document name: ' + app.activeDocument.name); app.activeDocument.close()"); -
Problem in executing vb script in java pgm
hi
i need to execute vb script in java pgm
i code is given below
there are no errors but the script is not executed,instead if i replace "command.exe \C G:/vb.vbs" with notepad,notepad is being executed
import java.lang.*;
import java.io.*;
public class run
public static void main(String args[])
Process p1;
Runtime r = Runtime.getRuntime();
try
p1 = r.exec("command.exe \C G:/vb.vbs");
catch(NullPointerException eo){}
catch(IOException e) { }
}Isn't it supposed to be "/C" and not "\C"?
-
Executing powershell script from remote computer using RSAT
Hi.
I want to execute powershell script on AD server from remote computer (in the same domain). I installed and tested RSAT - it is working fine. But i cant execute PS from c# code.
ps.Commands.AddCommand("Import-Module").AddArgument("ActiveDirectory");
ps.Invoke();
ps.Commands.AddCommand("Get-ADOrganizationalUnit -Filter 'Name -like \"*\"'");
var res = ps.Invoke();
And i get exception:
An unhandled exception of type 'System.Management.Automation.CommandNotFoundException' occurred in System.Management.Automation.dll
Additional information: The term 'Get-SBNamespace' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.Hi
CapitanPlanet
For the
CommandNotFoundException, it means the command cannot be found.
On the other hand, your issue is about the PowerShell, if you still have the issue, I suggest that you should post it in the
PowerShell forum for efficient response.
Here are some useful information, please check
Powershell
commands from C# not working (System.Management.Automation.CommandNotFoundException)
Powershell, Service Bus For Windows Server Programmatically: Command found, module could not be loaded
https://msdn.microsoft.com/en-us/library/dn282152.aspx
Best regards,
Kristin
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Executing SCVMM PowerShell scripts via C# conditionally works depending on application type
I suspect that this is the wrong forum but I could not find one that was appropriate.
The environment is SCVMM 2012 R2. I have a series of PowerShell scripts that are executed via C# code from a variety of applications -- MVC, WCF, console, unit tests. It seems that successful connection to the VMM server is dependent on the type of application
being used. For example, console apps and WCF apps can connect successfully but the
same code running in a unit test or standard MVC app throw the following exception:
{You cannot access VMM management server SC-01. (Error ID: 1604)
Contact the Virtual Machine Manager administrator to verify that your account is a member of a valid user role and then try the operation again.}
CategoryInfo: {ReadError: (:) [Get-SCVirtualMachine], CarmineException}
ErrorDetails: {You cannot access VMM management server SC-01. (Error ID: 1604)
Contact the Virtual Machine Manager administrator to verify that your account is a member of a valid user role and then try the operation again.}
Exception: {"You cannot access VMM management server SC-01.\r\nContact the Virtual Machine Manager administrator to verify that your account is a member of a valid user role and then try the operation again."}
FullyQualifiedErrorId: "1604,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetVMCmdlet"
InvocationInfo: Command = {Get-SCVirtualMachine}
PipelineIterationInfo: Count = 0
ScriptStackTrace: "at <ScriptBlock>, <No file>: line 1"
TargetObject: null
I suspect that somehow, each app is running under different credentials but I cannot see how that is possible. Each app exhibits the stated behavior whether running within Visual Studio (w/ IIS Express) [running under my own account] or published to the
server running under a specific specified account that definitely has permissions to the VMM environment.
This behavior is easily reproducible with the following code
-- PS Script as embedded resource
Get-SCVirtualMachine -VMMServer "SC-01"
-- C# code to load and execute script
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
namespace LabManagement {
public class HyperVVirtualMachineManager {
public IEnumerable<Models.VirtualMachine> GetVirtualMachines() {
var vms = new List<Models.VirtualMachine>();
try {
using (var rs = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()) {
rs.Open();
using (var ps = PowerShell.Create()) {
ps.Runspace = rs;
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var scriptName = "LabManagement.Scripts.GetAllVirtualMachines.ps1";
using (var s = assembly.GetManifestResourceStream(scriptName)) {
using (var reader = new System.IO.StreamReader(s)) {
var script = reader.ReadToEnd();
ps.AddScript(script);
var output = ps.Invoke();
if (ps.Streams.Error.Count > 0) {
foreach (var item in ps.Streams.Error) {
// do something
if (output.Count > 0) {
foreach (var o in output) {
// do something
rs.Close();
catch (RuntimeException ex) {
// do something
return vms;
-- Console app (Success)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VirtualLabManagement.ConsoleTests {
class Program {
static void Main(string[] args) {
// Arrange
var svc = new LabManagement.HyperVVirtualMachineManager();
// Act
var hosts = svc.GetVirtualMachines();
// Assert
-- Unit Test (Fails)
[TestMethod]
public void TestMethod1() {
// Arrange
var svc = new LabManagement.HyperVVirtualMachineManager();
// Act
var hosts = svc.GetVirtualMachines();
// Assert
Assert.IsNull(hosts);
As you can see, the code is exactly the same between the different executions but the ability to connect differs.Hi Sir,
I would like to check the following items:
1. "a variety of applications -- MVC, WCF, console, unit tests." they are all installed on same computer?
2. VMM server still installed on same computer as these app resides in ?
(if it is possible please detail the topology of the environment )
If they are running at same account on same computer , I would suggest you to post this issue into Code UI forum for further assistance :
https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vstest
Best Regards,
Elton JI
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected] . -
How to call business rules scripts via Java API
Hi
I have a problem. I have some scripts (business rules in essbase) that can be seen thru Administration Services Console under Business Rules folder. How can I execute these script using Provider Services (via Java API to EssBase interface)?hi
i look too java api sample for "HBR Lounch"
you can try found example in EAS folder
C:\Hyperion\AdminServices\AppServer\InstalledApps\Tomcat\5.0.28\eas\webapps\hbrlauncher\MC_LaunchWindow.jsp
please back, if you will have resolution :) -
How can i execute vb scripts in java program
hi
how can i execute any batch files or any other exe files (vb scripts) from java programs
thanksHi,
You use Runtime.exec to execute commands / exe-files. See the documentation (and remember that it will only work on windows):
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html
/Kaj -
Execute UNIX script from java not working
Hi
I am having difficulty running my java program to execute UNIX script on a Windows box. Here is my code.
public boolean executeScript() {
try {
String testScript= "WEB-INF/scripts/test.sh";
File file = new File(copyToQaScript);
System.out.println(file.getAbsolutePath());
Process proc = Runtime.getRuntime().exec(file.getAbsolutePath());
} catch (IOException ioe) {
ioe.printStackTrace();
logger.error(ioe);
} catch (RuntimeException re) {
re.printStackTrace();
logger.error(re);
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
return true;
}When I execute this method, I am getting IOException as below.
java.io.IOException: CreateProcess: C:\tomcat-5.0.28\webapps\myProject\WEB-INF\scripts\test.sh error=193
Can anyone help me? Thanks.kminkeller wrote:
Yes I have Cygwin installed. I am quite aware of that thanks Sabre.Then you need something like
String[] command = {"bash","/home/sabre/bin/fred.sh"};
Process p = Runtime.getRuntime().exec(command);
if the executabe directory (/home/sabre/bin in my case) is not on the PATH or
String[] command = {"bash","fred.sh"};
Process p = Runtime.getRuntime().exec(command);
if it is.
Maybe you are looking for
-
Event 55, Ntfs. Causing System to lock up every hour.
I checked the event log because my computer began locking up frequently last night. About a month ago I started regularly getting event 55 occurrences (after struggling to remove a browser hijacker virus) and now it looks like the last two event 55 o
-
Primary Key problem in 11g - Known issue 6894412
Hi Everyone: We are on JDeveloper 11.1.1.4, and JHeadstart 11.1.1.2.46. This thread originally started on the JHeadstart forum and can be seen at: Problem with LOV's in 11g We are converting our 10g application to 11g. We have an established Oracle d
-
I would like to run both client and server mode on my Desktop. Currently i have J2SE 1.5 jdk and can not run server mode. Can i run both modes with J2EE edition. Also there are at least two popular versions. J2EE 1.4 SDK or JAVA EE5. - not sure which
-
Hi All, As I am new to SRM and I have a requirement that while executing transaction SWI5 (Run RSWILOAD) i am getting data for fields Agent, Task, Date, Work Item Text and Processing time. Data for these fields is getting from DB Table SWWWIHEAD. B
-
hi everyone, my problem is that my computer technician installed iwork on my imac and i do not know if its pirate or original and when i type this (sudo find / -iname "iworkserv*" -print) in the terminal to see if i have a trojan or not, find: /dev/f