Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To call a powershell script file (example.ps1) from C#

I tried running a script localwindows.ps1 from C# using the following Code :

PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machineName", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
    runspace.Open();
    String file = "C:\\localwindows.ps1";
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(file);
    pipeline.Commands.Add("Out-String");
    Collection<PSObject> results = pipeline.Invoke();
}

                  

But getting exception :'The term 'C:\localwindows.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program.

So I tried the following :

PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machineName", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{

    runspace.Open();
 
    using (PowerShell powershell = PowerShell.Create())
    {
        powershell.Runspace = runspace;           
        
        PSCommand new1 = new PSCommand();
        String machinename = "machinename";
        String file = "C:\\localwindows.ps1";
        new1.AddCommand("Invoke-Command");
        new1.AddParameter("computername", machinename);
        new1.AddParameter("filepath", file);         
        

        powershell.Commands = new1;
        Console.WriteLine(powershell.Commands.ToString());
        Collection<PSObject> results = powershell.Invoke();
       
     }

I am getting the error : "Cannot find path 'C:\localwindows.ps1' because it does not exist."

But using command 'Invoke-Command -ComputerName "machineName" -filepath C:\localwindows.ps1' ,from powershell in local machine created a new account in the remote machine.

How to call the script localwindows.ps1 from C#? How to execute the command 'Invoke-Command -ComputerName "machineName" -filepath C:\localwindows.ps1' through C#?

The script localwindows.ps1 is

$comp = [adsi]“WinNT://machinename,computer”
$user = $comp.Create(“User”, "account3")
$user.SetPassword(“change,password.10")
$user.SetInfo()
like image 860
cmm user Avatar asked Nov 25 '13 14:11

cmm user


1 Answers

Actually your invocation style should work. But in both of your examples, the script c:\localwindows.ps1 must reside on the local computer. In the Invoke-Command case, it will be copied from the local computer to the remote computer.

If, in the Invoke-Command case, the script already exists on the remote computer and you don't need to copy it over, remove the FilePath parameter and add this:

new1.AddParameter("Scriptblock", ScriptBlock.Create(file));
like image 67
Keith Hill Avatar answered Sep 27 '22 19:09

Keith Hill