Executing PowerShell scripts on a remote host

I need to execute a PopwerShell script on a remote host (i.e. to add or remove Windows features).
The script uses some Powershell commands to be executed on the remote host (i.e. to add or remove Windows features).
I made part of the job but I am unable to go on...
After enabling PSremoting on the target host I run a script with the following commands:
winrm s winrm/config/client '@{TrustedHosts="remoteserver"}'
$mysession = new-pssession -computername remoteserver -credential remotedomain\remoteuser
If I enter the above lines interactiverly I can go on interactively by entering:
Enter-PSSession $mysession
and execute all the PowerShell commands I need.
My problem is that everything must be part of a script.
I attempted using "Invoke-command" with no success: maybe there is a syntax error or it is not the right command to be used in a script.
Can anybody please provede a sample of a script containing PowerShell commands to be executed on the remore host?
Regards
marius

You're on the right track.  You can use Invoke-Command with the same credentials (or PSSession from New-PSSession, if you prefer) to execute code remotely.  The tricky thing, unfortunately, will be the credentials.  Right now you're being
prompted to enter a username and password, but in an unattended script, you'd need to have these credentials saved somehow.  That can open up a can of worms, depending on your requirements.
The simplest way to do this is to hard-code the password in your script.  No one on the planet recomments actually doing this, because well, you've just exposed an admin password to the world.
The safest way to do this is to log on as the same account that will be used to run the script, on the same computer where the script will be run, and enter the credentials once manually, and export them to an XML file.  With this approach, the credentials
in the XML file will be encrypted with the Windows Data Protection API (DPAPI), and the keys necessary to decrypt that data are only available to the current user, on the current computer.
If you need to be able to securely save the data and have it read by other users, or on other computers, things start to get more complicated.
Here's an example of the DPAPI approach:
# to create the credential file
$cred = Get-Credential
$cred | Export-Clixml -Path c:\myEncryptedCreds.xml
# to use it later (on the same computer, by the same user)
$cred = Import-Clixml -Path c:\myEncryptedCreds.xml
Invoke-Command -ComputerName SomeComputer -Credential $cred -ScriptBlock {
Do-Something

Similar Messages

  • 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.

  • 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

  • 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

  • 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 Shah

    I 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

  • Execute powershell script from ssis?

    Hi,
    I was trying to use the execute process task to kick off a powershell script.  However, nothing happens when I run in debug (the component turns yellow and stays yellow).  Any idea if what I am trying to do is possible and the proper way to configure
    it?
    btw, I am using powershell for the remoting capabilites.  I need to execute a bat file on a remote server which runs a process in a legacy program. 
    Update:  When I name the ps1 script file in the executable window, it opens it in notepad.  This would be like the default if you double clicked the file.
    Mark

    To run a PowerShell Script from SSIS package. Add a "Execute Process Task" in SSIS and use the following command text.
    This works just great, plus the "-ExecutionPolicy ByPass" switch will take care of any server script policies.
    C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe
    -ExecutionPolicy ByPass -command ". 'L:\Powershell_Script\Script1.ps1' 'param1' 'param2'"
    Regards
    Deepak

  • 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

  • Term is not recognized when executing PowerShell Script through SQL Agent using CMDEXEC

    I am trying to simply execute a PowerShell script that is stored in a file on a network drive through SQL Agent as a job. The script is a basic copy from one directory to another.  I have run and successfully executed this from a command prompt outside
    of SQL Agent.  When I execute this through SQL Agent as a Operating System (CmdExec) command I am getting an error that the term is not recognized as the name of a cmdleet, function, script file or operable program. I have executed many different ways
    put found an article to use double quotes in the network path which I have done with no success. 
    I am executing the following command as a job in SQL Agent:
    PowerShell H:\"\PowerShell""\PS_Scripts\"\batchcopyFFLWithProgress.ps1 through SQL Agent job
    I get the following error message:
     04/21/2015 10:01:09,Copy FFL Files,Error,1,NY11266-LTW7E\JPLAPTOPSQL,Copy FFL Files,Copy FFL files,,Executed as user: NT Service\SQLAgent$JPLAPTOPSQL. H:\PowerShell\PS_Scripts\batchcopyFFLWithProgress.ps1 : The term   'H:\PowerShell\PS_Scripts\batchcopyFFLWithProgress.ps1'
    is not recognized as   the name of a cmdlet<c/> function<c/> script file<c/> or operable program. Check the   spelling of the name<c/> or if a path was included<c/> verify that the path is   correct and try again.
     At line:1 char:1  + H:"\PowerShell\PS_Scripts"\batchcopyFFLWithProgress.ps1  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      + CategoryInfo          : ObjectNotFound:
    (H:\PowerShell\P...ithProgress.p      s1:String) []<c/> CommandNotFoundException      + FullyQualifiedErrorId : CommandNotFoundException.  Process Exit Code 1.  The step failed.,00:00:03,0,0,,,,0
    Content of batchcopyFFLWithProgress.ps1 which has the PowerShell script:
    $source=ls H:\SQLTest\Script\TestData\*.*
    $i=1
    $source| %{
        [int]$percent = $i / $source.count * 100
        Write-Progress -Activity "Copying ... ($percent %)" -status $_ -PercentComplete $percent -verbose
        copy $_.fullName -Destination H:\test -Recurse
        $i++
    I have searched the internet and have not found any resolution to my error.  If someone has experienced this error and found the resolution I would greatly appreciate your help.

    I have change the service account for SQL Agent to be my domain account as I have local admin rights to my laptop.  I stopped and started the services for SQL Agent and than started the job to run which is copying locally to minimize any network drive
    issues.  I am still getting the same error message as it is showing that I am executing the job under my domain account?  Any thoughts what it could be?
    ErrorMsg
    04/23/2015 11:21:06,Copy FFL Files,Error,1,ServerName\InstanceName,Copy FFL Files,Copy FFL files,,Executed as user: Domain\DomainAccount. \\ServerName\Test\PS_Script\batchcopyFFLWithProgress.ps1 : The term '\\ServerName\Test\PS_Script\batchcopyFFLWithProgress.ps1'
    is   not recognized as the name of a cmdlet<c/> function<c/> script file<c/> or operable program. Check the spelling of the name<c/> or if a path was   included<c/> verify that the path is correct and try again.  At
    line:1 char:1  + \\ServerName\Test\PS_Script\batchcopyFFLWithProgress.ps1  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      + CategoryInfo          : ObjectNotFound: (\\ServerName...ithProgress.ps1:String)
    []<c/> CommandNotFoundException      + FullyQualifiedErrorId : CommandNotFoundException.  Process Exit Code 1.  The step failed.,00:00:02,0,0,,,,0
    Script
    $source=ls "\\ServerName\Test\TestData\*.*"
    $i=1
    $source| %{
        [int]$percent = $i / $source.count * 100
        Write-Progress -Activity "Copying ... ($percent %)" -status $_ -PercentComplete $percent -verbose
        copy $_.fullName -Destination "\\ServerName\Test\test" -Recurse
        $i++

  • 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.

  • Execute a script on a remote machine - possible?

    I am sorry if this sounds silly - what I would like to know is if its possible for a java program executing on one machine to execute a shell script that resides on another machine.
    That script in turn invokes a java program which does some other stuff.
    I know the way to do it would be to eliminate the script altogether and have the java program on the other box listen on a port and have it accept connections from the host machine. But a client is insistent he doesnt want it that way and I am not even sure if its possible to do as he says. I am aware that I can use the Runtime and Process classes to invoke a script on the same machine that the java application executes on, but is it possible to invoke a script on another machine?
    Thanks,
    Ram.

    If they're running the server on a *NIX box, you might check into inetd or xinetd - this is basically a proxy that listens on a certain port, starts a process running when it gets a request on that port, hands the request to that process, and then the process exits while xinetd waits for the next request.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Execute .sql scripts from a remote login

    Hello,
    1) How do I execute a remote sql script from sqlplus?
    SQL>@remote_server:$HOME/test_sql.sql ...this did not work, which would work?
    2) Another question, in sqlplus I can do...! echo testing123>$HOME/test123.txt.
    How do I do this within a store procedure?
    This does not work, which would work?
    declare
    v_test varchar2(300) := '! echo testing123>$HOME/test123.txt';
    begin
    execute immediate v_test;
    end;
    /

    Re Q2.
    I take it that's an sqlplus feature on unix as it doesn't work on windows:
    SQL> ! echo testing123>$HOME/test123.txt
    SP2-0734: unknown command beginning "! echo tes..." - rest of line ignored.
    SQL>Also the reason this isn't working from within PL/SQL is that the execute immediate statement is used to send SQL statements to the SQL engine. What you are attempting to do is to send sqlplus commands to the SQL engine which obviously knows nothing about sqlplus commands. Those commands are very specific to the sqlplus executable and will only work in that environment.
    ;)

  • Not able to configure BDC (Business Data connectivity )service in SharePoint 2012 Using Powershell Script

    HI
    Now there is an  issue while iam running powershell script for BDC service.
    Below is the script i am using to configure BDC service.
    Param(           
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]           
        [string]$ServiceName = $null,
        [Parameter(Mandatory=$true)]           
        [string]$ServiceProxyName = $null,
        [Parameter(Mandatory=$true)]           
        [string]$AppPoolAccount = $null,
        [Parameter(Mandatory=$true)]           
        [string]$AppPoolName = $null,
        [Parameter(Mandatory=$true)]           
        [string]$DatabaseServer = $null,
        [Parameter(Mandatory=$true)]           
        [string]$DatabaseName = $null
    # check to ensure Microsoft.SharePoint.PowerShell is loaded if not using the SharePoint Management Shell
    $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
    if ($snapin -eq $null) {
        Write-Host "Loading SharePoint Powershell Snapin"
        Add-PSSnapin "Microsoft.SharePoint.Powershell"
    Write-Host "Successfully Sharepoint Powershell snapin Loaded"
    Write-Host "Started executing Powershell script for configuring Business Data Connectivity Service in sharepoint farm ..."
    Write-Host -ForegroundColor Yellow "Checking if Application Pool Accounts exists"
    $AppPoolAccount = Get-SPManagedAccount -Identity $AppPoolAccount -EA 0
    if($AppPoolAccount -eq $null)
    Write-Host "Please supply the password for the Service Account..."
    $AppPoolCred = Get-Credential $AppPoolAccount
    $AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCred -EA 0
    Write-Host -ForegroundColor Yellow "Checking wether the Application Pool exists"
    $AppPool = Get-SPServiceApplicationPool -Identity $AppPoolName -ErrorAction SilentlyContinue
    if (!$AppPool)
    Write-Host -ForegroundColor Green "Creating Application Pool"
    $AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account $AppPoolAccount -Verbose
    Write-Host -ForegroundColor Yellow "Checking if BDC Service Application exists"
    $ServiceApplication = Get-SPServiceApplication -Name $ServiceName -ErrorAction SilentlyContinue
    if (!$ServiceApplication)
    Write-Host -ForegroundColor Green "Creating BDC Service Application"
    $ServiceApplication = New-SPBusinessDataCatalogServiceApplication –ApplicationPool $AppPool –DatabaseName $DatabaseName –DatabaseServer $DatabaseServer –Name $ServiceName
    Write-Host -ForegroundColor Yellow "Starting the BDC Service"
    #$ServiceInstance = Get-SPServiceInstance | Where-Object { $_.TypeName -like "BDC Service*" }
    #Start-SPServiceInstance $ServiceInstance
    Get-SPServiceInstance | where-object {$_.DisplayName -eq $ServiceName} | Start-SPServiceInstance > $null
    Write-Host -ForegroundColor Green "Done - BDC Service is up and running."
    Error i am getting ->
    Started executing Powershell script for configuring Business Data Connectivity S
    ervice in sharepoint farm ...
    Checking if Application Pool Accounts exists
    Checking wether the Application Pool exists
    Creating Application Pool
    VERBOSE: Leaving BeginProcessing Method of New-SPServiceApplicationPool.
    New-SPServiceApplicationPool : The trust relationship between the primary
    domain and the trusted domain failed.
    At C:\SP2013Service\BDC1.ps1:67 char:12
    + $AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account
    $AppPoolAcco ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ~~~
        + CategoryInfo          : InvalidData: (Microsoft.Share...ApplicationPool:
       SPCmdletNewIisWebServiceApplicationPool) [New-SPServiceApplicationPool], S 
      ystemException
        + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewIisWe
       bServiceApplicationPool
    VERBOSE: Leaving ProcessRecord Method of New-SPServiceApplicationPool.
    VERBOSE: Leaving EndProcessing Method of New-SPServiceApplicationPool.
    Checking if BDC Service Application exists
    Creating BDC Service Application
    New-SPBusinessDataCatalogServiceApplication : Cannot bind argument to
    parameter 'ApplicationPool' because it is null.
    At C:\SP2013Service\BDC1.ps1:75 char:84
    + ... pplicationPool $AppPool –DatabaseName $DatabaseName –DatabaseServer
    $DatabaseSer ...
    +                    ~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [New-SPBusinessD...viceApplicat
       ion], ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M
       icrosoft.SharePoint.BusinessData.SharedService.SPNewBusinessDataCatalogSer 
      viceApplication

    hi guys,
    same script i have modified with parametes,in below script i have hard corded values for parameters,and it is executing without errors.
    Below is script executing without error->
    Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    #Settings
    $ServiceName = "BDC Service"
    $ServiceProxyName = "BDC Proxy"
    $AppPoolAccount = "DOMAIN\USERNAME"
    $AppPoolName = "BDC SP Ser App Pool"
    $DatabaseServer = "SPSQL"
    $DatabaseName = "SP2013 BDC"
    Write-Host -ForegroundColor Yellow "Checking if Application Pool Accounts exists"
    $AppPoolAccount = Get-SPManagedAccount -Identity $AppPoolAccount -EA 0
    if($AppPoolAccount -eq $null)
    Write-Host "Please supply the password for the Service Account..."
    $AppPoolCred = Get-Credential $AppPoolAccount
    $AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCred -EA 0
    Write-Host -ForegroundColor Yellow "Checking wether the Application Pool exists"
    $AppPool = Get-SPServiceApplicationPool -Identity $AppPoolName -ErrorAction SilentlyContinue
    if (!$AppPool)
    Write-Host -ForegroundColor Green "Creating Application Pool"
    $AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account $AppPoolAccount -Verbose
    Write-Host -ForegroundColor Yellow "Checking if BDC Service Application exists"
    $ServiceApplication = Get-SPServiceApplication -Name $ServiceName -ErrorAction SilentlyContinue
    if (!$ServiceApplication)
    Write-Host -ForegroundColor Green "Creating BDC Service Application"
    $ServiceApplication = New-SPBusinessDataCatalogServiceApplication –ApplicationPool $AppPool –DatabaseName $DatabaseName –DatabaseServer $DatabaseServer –Name $ServiceName
    Write-Host -ForegroundColor Yellow "Starting the BDC Service"
    #$ServiceInstance = Get-SPServiceInstance | Where-Object { $_.TypeName -like "BDC Service*" }
    #Start-SPServiceInstance $ServiceInstance
    Get-SPServiceInstance | where-object {$_.DisplayName -eq $ServiceName} | Start-SPServiceInstance > $null
    Write-Host -ForegroundColor Green "Done - BDC Service is up and running."
    if any body want need more information please can u respond me to
    Email id:[email protected]

  • How to display a file on remote host?

    Hi, All,
    I want to know how to display a text file on a remote host on APEX.
    In my APEX application, I call a OS command which execute a shell script on a remote host. The shell script will run for 5mins, and send out its running status on the remote host every 10 seconds.
    For APEX application, I want to display the output file on the remote host, and refresh the screen every 10 seconds. So the user can get the running status while the shell script is running.
    Thanks in advance for any advice.
    Sharon.Ni

    I call a OS command which execute a shell script on a remote hostI am assuming that you are using a Java wrapper to execute the OS script.
    <li>If so add another script that 'echo's or displays(cat) the file content in your OS
    <li> Add another java wrapper that runs the script (PLSQL OS COMMAND library can return the unix output of a script to PLSQL and is feature rich)
    <li> Have a PLSQL ondemand process that runs the Java code that returns the file content_(it can even return a clob) to JS ( using htp.p).
    <li> In the page have a timer JS which calls the Ondemadn process and put the content into an HTML div(eg by using html() function) with the Ondemand processes return string.

  • Linux Server to connect Windows 2008 R2 Server to execute powershell commands

    Is it possible to do remotely executing powershell scripts on Windows 2008 R2 from Linux Server. I explored the option of FreeSSHD, but there is no option for password less authentication.
    Any thoughts and hints greatly appreciated.
    Retheesh
    Thanks and Regards, Retheesh Kumar R

    I am going to respectfully disagree with my post mates! Muhahahaha!
    If the target server (your Windows 2008 R2 box) can accept secure shell (ssh) connections, you should be able to ssh into the server then start PowerShell just like any other shell. That said, I suspect you will run into quirks. For example, I bet the
    "out-gridview" commandlet does some whacky stuff. You may get some strange terminal emulation junk too, but by and large you should be okay. I have Cygwin deployed to a Windows machine. That installation includes the OpenSSH package.
    [1] Cygwin http://www.cygwin.com/
    [2] How to run the OpenSSH SSHD server on Windows using Cygwin;
    http://www.noah.org/ssh/cygwin-sshd.html
    This would be like ssh'ing into some Linux machine then firing up ksh. If you're used to Linux, you no doubt know what I'm talking about.
    Now, here is the trick. You'll have to setup key based authentication on the Windows machine once you have your SSH server all setup. If you know how to do this on Linux, its the same process for Cygwin. The following article can help you -- remember the
    process is pretty much the same for Cygwin on Windows as it is for Linux distributions:
    [3] SSH with authentication key instead of password;
    http://www.debian-administration.org/articles/530
    You have your work cut out for you. Give it a try, and tell us how you fare.
    I hope this helps bro!
    Cheers,
    A-

  • Powershell & C# to check if host available

    Hi All,
    I have a c# code segment which process a power-shell script. The following is the code segment.
    Runspace objRunspace = null;
    objRunspace = RunspaceFactory.CreateRunspace();
    objRunspace.Open();
    PowerShell powershell = PowerShell.Create();
    powershell.Runspace = objRunspace;
    powershell.AddScript("my powershell script");
    Collection<PSObject> objPS1 = powershell.Invoke();
    if (objPS1.Count == 0)
    //I Assumes that the PC is down
    In this case, If the login credentials are wrong or if that particular PC is not available; the ObjPS1.count will be zero. If that count is Zero, I assumes that the host is unavailable. But in accuracy point of view, I want to identify both these (wrong
    credentials / host unavailable) situations separate. Is there a better way or different approach to achieve the same.
    Thanks in advance
    Sebastian

    Hi Sebastian,
    In addition, these examples may be helpful for you to handle the error when call powershell script in C#:
    // invoke execution on the pipeline (collecting output)
    Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
    // check the other output streams (for example, the error stream)
    if (PowerShellInstance.Streams.Error.Count > 0)
    // error records were written to the error stream.
    // do something with the items found.
    Reference from:
    Executing PowerShell scripts from C#
    Handling errors when calling PowerShell using C#
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna
    TechNet Community Support

Maybe you are looking for