I am trying to launch Chrome in my AWS EC2 Windows Instance from my local windows machine using PowerShell.
I have tried the below commands but they haven't worked.
Invoke-Command -Session $session -ScriptBlock {Start-Process -FilePath www.google.com}
Wrote Selenium java code to launch Chrome, exported it a jar file, copied to my remote machine. I tried to execute it from my local machine using:
Invoke-Command -Session $session -ScriptBlock {java -jar launcbrowser.jar}
The jar file is executing and running the process in background, but it is not launching the browser.
function Start-Process-Active{
param (
[System.Management.Automation.Runspaces.PSSession]$Session,
[string]$Executable,
[string]$Argument,
[string]$WorkingDirectory,
[string]$UserID,
[switch]$Verbose = $false
)
if (($Session -eq $null) -or ($Session.Availability -ne [System.Management.Automation.Runspaces.RunspaceAvailability]::Available))
{
$Session.Availability
throw [System.Exception] "Session is not availabile"
}
Invoke-Command -Session $Session -ArgumentList $Executable,$Argument,$WorkingDirectory,$UserID -ScriptBlock {
param($Executable, $Argument, $WorkingDirectory, $UserID)
$action = New-ScheduledTaskAction -Execute $Executable -Argument $Argument -WorkingDirectory $WorkingDirectory
$principal = New-ScheduledTaskPrincipal -userid $UserID
$task = New-ScheduledTask -Action $action -Principal $principal
$taskname = "_StartProcessActiveTask"
try
{
$registeredTask = Get-ScheduledTask $taskname -ErrorAction SilentlyContinue
}
catch
{
$registeredTask = $null
}
if ($registeredTask)
{
Unregister-ScheduledTask -InputObject $registeredTask -Confirm:$false
}
$registeredTask = Register-ScheduledTask $taskname -InputObject $task
Start-ScheduledTask -InputObject $registeredTask
Unregister-ScheduledTask -InputObject $registeredTask -Confirm:$false
}
}
Related
I'm new to java with Talend Open Studio.
I would like to know if it is possible to execute powershell.exe with "Import-Module ActiveDirectory", and then to launch dynamics commands without reloading powershell with "Import-Module ...".
I know this will not work, but my idea could be translated like this :
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");
For this to work, I have to do ...
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");
I don't want to go through a script file because a first update command (Set-ADUser) can have an impact on the next update command.
Thanks.
I found a solution with the jPowerShell library from profesorfalken
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?
}
So i write Windows update'r automat in java. For fetching needed data from windows servers i am using jPowerShell and i have stamble apon weird problem while execute this script
Java calling PowerShell Script
PowerShell ps = PowerShell.openSession();
PowerShellResponse response;
response = ps.executeScript("C:\\Users\\Prezes\\Desktop\\IsUpdateToInstal.ps1");
System.out.println(response.getCommandOutput());
PowerShell Script
$pw = ConvertTo-SecureString 'password' -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentList domein\login, $pw
Enter-PSSession -ComputerName IP -Credential $cred
$UpdateSession = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session"))
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
$Critical = $SearchResult.updates | where { $_.MsrcSeverity -eq "Critical" }
$important = $SearchResult.updates | where { $_.MsrcSeverity -eq "Important" }
$other = $SearchResult.updates | where { $_.MsrcSeverity -eq $nul}
$totalUpdates = $($SearchResult.updates.count)
if($totalUpdates -gt 0)
{
$updatesToInstall = $true
}
else { $updatesToInstall = $false }
$other
$totalUpdates
$updatesToInstall
if i execute this script line by line in PowerShell standard consol everyting is working fine and proper value are returned.
But when i run this script in PowerShell ISE line by line or run by Java i notice some problem with this line
$UpdateSession = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session"))
while i enter this line and press enter i can see in ISE "already running a command, please wait" when i wait a faw minutes communicate is the same and nothing change but when i press enter secound time command pass through immediately. If from them now i run rest of script evertying i working well.
When i try to excecute full script in ISE i am geting this error
Exception form HRESULT: 0x80072EE2
At C:\Users\Prezes\Desktop\IsUpdateToInstal.ps1:6 char:1
+ $SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 a ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMExceptio
Java gives me null saying that i can't run methond on null object reffering to $UpdateSearcher
I am very early beginer with PowerShell and script that i am using is pure form some example finded in google.
So i had not figure out what was the cause of weird behavior but i managed to write someting that started to work for me through PowerShell api in java and get returned value.
$pw = ConvertTo-SecureString 'PASSWORD' -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentList 792\opmanager, $pw
$TotalUpdates = Invoke-Command -ComputerName IP -ScriptBlock{
$UpdateSession = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session"))
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
$Critical = $SearchResult.updates | where { $_.MsrcSeverity -eq "Critical" }
$important = $SearchResult.updates | where { $_.MsrcSeverity -eq "Important" }
$other = $SearchResult.updates | where { $_.MsrcSeverity -eq $nul}
$totalUpdates = $($SearchResult.updates.count)
if($totalUpdates -gt 0)
{
$updatesToInstall = $true
}
else { $updatesToInstall = $false }
Return $totalUpdates
} -Credential $cred
$TotalUpdates
I created a java application(.jar) as a windows service using Procrun. This Service get installed and runs successfully when I use a batch(.bat) file. but I have this requirement of creating the same service using windows powerShell.
When I use PowerShell, service get installed but cannot start the service I checked in the windows event viewer and it displays as "Incorrect Function" Can anyone please tell me what could be the reason for this.
This is the string I used in PowerShell script to install the windows service
$CmdInstall=#'
--Description="$Description"
--DisplayName="$DisplayName"
--Install="$DAEMON"
--Startup=auto
--Type=
--DependsOn=
--Environment=
--User=
--Password=
--ServiceUser=
--ServicePassword=
--LibraryPath=
--JavaHome
--Jvm=auto
--JvmOptions=-Xmx1024M
--Classpath=server.jar
--JvmMs=
--JvmMx=
--JvmSs=
--StartMode=jvm
--StartImage=
--StartPath=
--StartClass=at.mrdevelopment.esl.server.Server
--StartMethod=main
--StartParams=
--StopMode=jvm
--StopImage=
--StopPath=
--StopClass=at.mrdevelopment.esl.server.ServerServiceStarter
--StopMethod=stop
--StopParams=
--StopTimeout=120
--LogPath=$LogPath
--LogPrefix=$InstanceName
--LogLevel=DEBUG
--LogJniMessages=
--StdOutput=auto
--StdError=auto
--PidFile=${InstanceName}.pid
'#
Any help would be appreciated.
This is the PowerShell script I used.
#region Parameters
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[ValidateNotNullOrEmpty()]
[string]$Action="//IS"
,
[ValidateNotNullOrEmpty()]
[string]$ServiceName="//ESL_SERVICE"
,
[ValidateNotNullOrEmpty()]
[string]$DisplayName="ESL_SERVICE"
,
[ValidateNotNullOrEmpty()]
[string]$Description="ESL Service"
,
[ValidateNotNullOrEmpty()]
[string]$InstanceName="server.jar"
,
[ValidateNotNullOrEmpty()]
[string]$LogPath='C:\Apachelogs'
,
[string]$Pause=60
)
#endregion
#region Main
$CmdInstall=#'
--Description="$Description"
--DisplayName="$DisplayName"
--Install="$DAEMON"
--Startup=auto
--Type=
--DependsOn=
--Environment=
--User=
--Password=
--ServiceUser=
--ServicePassword=
--LibraryPath=
--JavaHome
--Jvm=auto
--JvmOptions=-Xmx1024M
--Classpath=server.jar
--JvmMs=
--JvmMx=
--JvmSs=
--StartMode=jvm
--StartImage=
--StartPath=
--StartClass=at.mrdevelopment.esl.server.Server
--StartMethod=main
--StartParams=
--StopMode=jvm
--StopImage=
--StopPath=
--StopClass=at.mrdevelopment.esl.server.ServerServiceStarter
--StopMethod=stop
--StopParams=
--StopTimeout=120
--LogPath=$LogPath
--LogPrefix=$InstanceName
--LogLevel=DEBUG
--LogJniMessages=
--StdOutput=auto
--StdError=auto
--PidFile=${InstanceName}.pid
'#
$DAEMON_HOME = "C:\imagotag\server"
$DAEMON = "$DAEMON_HOME\prunsrv_64.exe"
$ESL_HOME = "C:\imagotag\server"
$CmdArgsDict=#{}
$CmdArgsDict.Add('//IS', "$Action$ServiceName $CmdInstall")
$CmdArgs = $CmdArgsDict[$action]
# Convert backslashes in the paths to java-friendly forward slashes
$CmdArgs = $CmdArgs -replace "\\","/"
# Variable interpolation: expand embedded variables references (need to call this twice)
$CmdArgs = $ExecutionContext.InvokeCommand.ExpandString($CmdArgs)
$CmdArgs = $ExecutionContext.InvokeCommand.ExpandString($CmdArgs)
# Split on newlines to convert to an array of lines
$CmdArgsString = $CmdArgs -split "`n"
# Convert array of lines into a string
$CmdArgsString = "$CmdArgsString"
#--- Execute the command
if ($PSCmdlet.ShouldProcess(
"`n$DAEMON`n$CmdArgs","Manage ESL Service"
))
{
"$DAEMON $CmdArgsString"
$p=Start-Process "$DAEMON" `
-ArgumentList "$CmdArgsString" `
-Wait `
-NoNewWindow `
-PassThru
$rc = $p.ExitCode
"`nExit Code: $rc"
}
#endregion
My PowerShell script is TestPS.ps1 and I execute the script like this
.\TestPS.ps1 //IS
For creating a service , use the following cmdlet in PS:
$username = "Username"
$password = "password"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
new-service -Name [INSERT SERVICE NAME] -DisplayName "[INSERT DISPLAY NAME]" -Description "[INSERT DESCRIPTION]" -BinaryPathName "[INSERT BINARY PATH]" -StartupType Manual -Credential $cred
If you wish to perform it remotely, then use the following function:
function Install-Service(
[string]$serviceName = $(throw "serviceName is required"),
[string]$targetServer = $(throw "targetServer is required"),
[string]$displayName = $(throw "displayName is required"),
[string]$physicalPath = $(throw "physicalPath is required"),
[string]$userName = $(throw "userName is required"),
[string]$password = "",
[string]$startMode = "Automatic",
[string]$description = "",
[bool]$interactWithDesktop = $false
)
{
# can't use installutil; only for installing services locally
#[wmiclass]"Win32_Service" | Get-Member -memberType Method | format-list -property:*
#[wmiclass]"Win32_Service"::Create( ... )
# todo: cleanup this section
$serviceType = 16 # OwnProcess
$serviceErrorControl = 1 # UserNotified
$loadOrderGroup = $null
$loadOrderGroupDepend = $null
$dependencies = $null
# description?
$params = `
$serviceName, `
$displayName, `
$physicalPath, `
$serviceType, `
$serviceErrorControl, `
$startMode, `
$interactWithDesktop, `
$userName, `
$password, `
$loadOrderGroup, `
$loadOrderGroupDepend, `
$dependencies `
$scope = new-object System.Management.ManagementScope("\\$targetServer\root\cimv2", `
(new-object System.Management.ConnectionOptions))
"Connecting to $targetServer"
$scope.Connect()
$mgt = new-object System.Management.ManagementClass($scope, `
(new-object System.Management.ManagementPath("Win32_Service")), `
(new-object System.Management.ObjectGetOptions))
$op = "service $serviceName ($physicalPath) on $targetServer"
"Installing $op"
$result = $mgt.InvokeMethod("Create", $params)
Test-ServiceResult -operation "Install $op" -result $result
"Installed $op"
"Setting $serviceName description to '$description'"
Set-Service -ComputerName $targetServer -Name $serviceName -Description $description
"Service install complete"
}
Here is the Guide to Install Windows Service Remotely
Note: Make sure you are running everything with elevated mode.
Hope it helps.
Your problems came from a misconfigured service. That comes from a problem with the parameters of prunsrv.exe.
The script works well after changing the line
$CmdArgsString = $CmdArgs -split "`n"
to
$CmdArgsString = $CmdArgs -split "`r`n"
I try to start an Java program from a PowerShell script, but I don't want see any window. I have already tried all possible combinations of parameters for ProcessStartInfo and Process, but it still displays a empty shell window for java.exe. This is my current PowerShell code:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "$jre\bin\java.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.CreateNoWindow = $true
$pinfo.WindowStyle = "Hidden"
$pinfo.UseShellExecute = $false
$pinfo.WorkingDirectory = $temp
if ($integrated) {
Write-Output "Connecting using integrated security ..."
# Start with different user context
$securePassword = ConvertTo-SecureString $pw -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $user, $securePassword
$pinfo.UserName = $credential.GetNetworkCredential().UserName
$pinfo.Domain = $credential.GetNetworkCredential().Domain
$pinfo.Password = $credential.Password
$pinfo.Arguments = "-jar `"$jar`" validate -url `"$jdbc`" -i -dbVersion `"$msSqlVersion`""
} else {
Write-Output "Connecting ..."
$pinfo.Arguments = "-jar `"$jar`" validate -url `"$jdbc`" -u `"$user`" -p `"$pw`" -dbVersion `"$dbVersion`""
}
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start()
$p.StandardOutput.ReadToEnd()
$p.StandardError.ReadToEnd()
$p.WaitForExit()
I hope anyone could help me with this issue.
I am trying to run Appium Serve on my Windows 7 machine using a simple command:
D:\Appium\node.exe D:\Appium\node_modules\appium\bin\Appium.js -g C:\Users\vdopia\AppData\Local\Temp\applog_12232015_110310.txt --no-reset
in command prompt, it shows that Appium is started. When I browse the url http://127.0.0.1:4723, I get the message below in my command prompt and because of this I am not able initialize remotedriver also. Surprisingly, the same thing works well in MAC.
Logs:
> info: --> GET / {}
> info: [debug] Responding to client that we did not find a valid resource
> info: <-- GET / 404 0.712 ms - 47
> info: <-- GET /favicon.ico 200 0.535 ms - 1150
I am pasting code here to start appium server, first I am writing command in a sh or bat file then executing the bat file.
public static boolean startAppiumServer()
{
//Kill any Existing Appium Before Starting new session
logger.info("Stopping any running instance of appium. ");
try{SDKCommonUtils.killAppiumServer();}catch(Exception e){}
boolean flag = false;
File logFile = null;
String commandFile = null;
if(System.getProperty("os.name").matches("^Windows.*"))
{
//Getting temp dir
String tempDir = System.getProperty("java.io.tmpdir").toString();
logFile = new File(tempDir+"\\applog"+"_"+MobileTestClass_Methods.DateTimeStamp()+".txt");
commandFile = System.getenv("AUTOMATION_HOME").concat("\\tpt\\appium_commands.bat");
String appiumCmdLocation_Windows = MobileTestClass_Methods.propertyConfigFile.getProperty("appiumCmdLocationForWindows").toString();
String nodeExe = appiumCmdLocation_Windows.concat("\\node.exe");
String appiumJs = appiumCmdLocation_Windows.concat("\\node_modules\\appium\\bin\\Appium.js");
String strText = "start /B " + nodeExe + " " + appiumJs + " -g " + logFile.toString() + " --full-reset --command-timeout 60 ";
FileLib.WriteTextInFile(commandFile, strText);
}
else
{
logFile = new File("/tmp/applog"+"_"+MobileTestClass_Methods.DateTimeStamp()+".txt");
commandFile = System.getenv("AUTOMATION_HOME").concat("/tpt/appium_commands.sh");
String strText = "export PATH=$PATH:/usr/local/bin; /usr/local/bin/appium -g " + logFile.toString() + " --full-reset --command-timeout 60 " ;
FileLib.WriteTextInFile(commandFile, strText);
}
try
{
logger.info("Executing Command File: "+ commandFile +" to start appium service. ");
Runtime.getRuntime().exec(commandFile);
/** wait until appium server is started */
flag = waitForAppiumServer();
}
catch(Exception e)
{
flag = false;
logger.error("There were some issues while executing command to launch appium service. ",e);
}
return flag;
}
If you do not provide server address then it will be used as 0.0.0.0 from command prompt in windows as
info: Appium REST http interface listener started on 0.0.0.0:4723.
Please provide --address 127.0.0.1 --port 4723 parameter from command line and try to use same address and port while initializing driver object in your script.