IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Scripts/Batch Discussion :

appel script PS via C# [PowerShell]


Sujet :

Scripts/Batch

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2008
    Messages
    35
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 35
    Par défaut appel script PS via C#
    Bonjour,

    J'aimerais appeler mes scripts PowerShell via un programme C#

    Je sais que cela est possible car j'ai déjà un programme qui appelle mes scripts PS mais je ne peux y mettre que des scripts avec des cmdlet local du style:
    script.ps1
    Je ne peux pas y mettre des cmdlets qu'on lance sur des sessions distantes..
    ex:
    script1.ps1
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    $cred = D:\import-credential.ps1 D:\pass.txt
    Invoke-Command { Get-Process } -ComputerName wks0010 -Credential $cred
    import-credential.ps1 ( http://janel.spaces.live.com/blog/cn...88C2!358.entry )
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    param ($filename)
     
    $username,$password = type $filename
    $pwd = convertto-securestring $password
    new-object system.management.automation.PSCredential $username,$pwd

    Je ne trouve pas comment faire fonctionner le programme C# avec script1.ps1

    Voic le prgr C#:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    using System.Diagnostics;
    
    namespace PowerShellAndCSharp
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    string scriptFile = ".\\script.ps1";
                    string scriptParameters = "";
                    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
                    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
                    runspace.Open();
                    Console.WriteLine("runspace open");
                    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                    Pipeline pipeline = runspace.CreatePipeline();
    
                    Command scriptCommand = new Command(scriptFile);
                    Console.WriteLine("script ajoute");
                    Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
    
                    foreach (string scriptParameter in scriptParameters.Split(' '))
                    {
                        CommandParameter commandParm = new CommandParameter(null, scriptParameter);
                        commandParameters.Add(commandParm);
                        scriptCommand.Parameters.Add(commandParm);
                    }
                    pipeline.Commands.Add(scriptCommand);
                    Collection<PSObject> psObjects = pipeline.Invoke();
                    runspace.Close();
                    Console.WriteLine("runspace close");
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (PSObject obj in psObjects)
                    {
                        stringBuilder.AppendLine(obj.ToString());
                        Console.WriteLine("reponse: " + obj.ToString());
                    }
    
                    Console.WriteLine(stringBuilder.ToString());
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine("exception: " + ex.Message);
                }
            }
        }
    }
    J'espère que j'ai été clair concernant le problème.
    Vous pouvez toujours essayer de tester le code pour script.ps1, ça fonctionne.
    Quelqu'un aurait-il déjà fait ce genre de choses et saurait-il m'aider?


    Merci d'avance

  2. #2
    Rédacteur


    Profil pro
    Inscrit en
    Janvier 2003
    Messages
    7 171
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2003
    Messages : 7 171
    Billets dans le blog
    1
    Par défaut
    Salut,
    Citation Envoyé par Xpertfly Voir le message
    Quelqu'un aurait-il déjà fait ce genre de choses et saurait-il m'aider?
    Tu as une vingtaine d'exemples progressif dans le SDK Windows 7.
    Citation Envoyé par Xpertfly Voir le message
    Je sais que cela est possible car j'ai déjà un programme qui appelle mes scripts PS mais je ne peux y mettre que des scripts avec des cmdlet local du style
    Peut être est-ce du à ceci constrained runspaces ?

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2008
    Messages
    35
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 35
    Par défaut
    Citation Envoyé par Laurent Dardenne Voir le message
    Salut,

    Tu as une vingtaine d'exemples progressif dans le SDK Windows 7.

    Peut être est-ce du à ceci constrained runspaces ?
    Merci

    Pour ceux que ça intéresse, j'ai réussi via ce scripts:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    SecureString pwd = new SecureString();	 
    	        foreach(char c in "*****".ToCharArray())
    	        {
    	            pwd.AppendChar(c);
    	        }	 
    	        PSCredential cred = new PSCredential("domain\\login", pwd);
    
                // Create a WSManConnectionInfo object using the default constructor to 
                // connect to the "localhost". The WSManConnectionInfo object can also 
                // specify connections to remote computers.
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "exemple-srv.domain.be", 5985, "/wsman", "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", cred);
    
                // Create a remote runspace pool that uses the WSManConnectionInfo object.  
                // The minimum runspaces value of 1 specifies that Windows PowerShell will 
                // keep at least 1 runspace open. The maximum runspaces value of 2 specifies
                // that Windows PowerShell will keep a maximum of 2 runspaces open at the 
                // same time so that two commands can be run concurrently.
                using (RunspacePool remoteRunspacePool =
                       RunspaceFactory.CreateRunspacePool(1, 2, connectionInfo))
                {
                    // Call the Open() method to open a runspace from the pool and establish 
                    // the connection. 
                    remoteRunspacePool.Open();
    
                    // Call the Create() method to create a pipeline, call the AddCommand(string) 
                    // method to add the "get-process" command, and then call the BeginInvoke() 
                    // method to run the command asynchronously using a runspace of the pool.
                    PowerShell gpsCommand = PowerShell.Create().AddCommand("get-process");
                    gpsCommand.RunspacePool = remoteRunspacePool;
                    IAsyncResult gpsCommandAsyncResult = gpsCommand.BeginInvoke();
                    ////<SnippetRemoteRunspacePool01CreatePowerShell01/>
    
                    // The previous call does not block the current thread because it is 
                    // running asynchronously. Because the remote runspace pool can open two 
                    // runspaces, the second command can be run.
                    PowerShell getServiceCommand = PowerShell.Create().AddCommand("get-service");
                    getServiceCommand.RunspacePool = remoteRunspacePool;
                    IAsyncResult getServiceCommandAsyncResult = getServiceCommand.BeginInvoke();
    
                    // When you are ready to handle the output, wait for the command to complete 
                    // before extracting results. A call to the EndInvoke() method will block and return 
                    // the output.
                    PSDataCollection<PSObject> gpsCommandOutput = gpsCommand.EndInvoke(gpsCommandAsyncResult);
    
                    // Process the output as needed.
                    if ((gpsCommandOutput != null) && (gpsCommandOutput.Count > 0))
                    {
                        Console.WriteLine("The first output from running get-process command: ");
                        Console.WriteLine(
                                          "Process Name: {0} Process Id: {1}",
                                          gpsCommandOutput[0].Properties["ProcessName"].Value,
                                          gpsCommandOutput[0].Properties["Id"].Value);
                        Console.WriteLine();
                    }
    
                    // Now process the output from second command. As discussed previously, wait 
                    // for the command to complete before extracting the results.
                    PSDataCollection<PSObject> getServiceCommandOutput = getServiceCommand.EndInvoke(
                                    getServiceCommandAsyncResult);
    
                    // Process the output of the second command as needed.
                    if ((getServiceCommandOutput != null) && (getServiceCommandOutput.Count > 0))
                    {
                        Console.WriteLine("The first output from running get-service command: ");
                        Console.WriteLine(
                                          "Service Name: {0} Description: {1} State: {2}",
                                          getServiceCommandOutput[0].Properties["ServiceName"].Value,
                                          getServiceCommandOutput[0].Properties["DisplayName"].Value,
                                          getServiceCommandOutput[0].Properties["Status"].Value);
                    }
    
                    // Once done with running all the commands, close the remote runspace pool.
                    // The Dispose() (called by using primitive) will call Close(), if it
                    // is not already called.
                    remoteRunspacePool.Close();
    J'obtiens les process distant d'une machine.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Appel procédure stockée via script
    Par christelle_s dans le forum QlikView
    Réponses: 2
    Dernier message: 04/09/2012, 13h40
  2. Appel de fonction/script python via PHP
    Par rastalien dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 2
    Dernier message: 21/02/2008, 18h12
  3. Réponses: 8
    Dernier message: 08/06/2007, 21h39
  4. Réponses: 6
    Dernier message: 06/03/2006, 12h53
  5. Réponses: 4
    Dernier message: 16/07/2004, 09h16

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo