0

I'm trying to run powershell commands on a remote sharepoint server from a c# console app. This is the code I have so far. It runs without errors but does nothing. What am I doing wrong?

Thanks

server name, username password, and url were taken out

    public static string RunScript()
    {

       Runspace remoteRunspace = null;
       openRunspace("http://server/wsman",
            "http://schemas.microsoft.com/powershell/Microsoft.PowerShell",
            @"domain\user",
            "password",
            ref remoteRunspace);
       try
       {
           StringBuilder stringBuilder = new StringBuilder();
           using (PowerShell powershell = PowerShell.Create())
           {

               powershell.Runspace = remoteRunspace;
               powershell.AddScript("Add-PsSnapin Microsoft.SharePoint.PowerShell");
               powershell.AddScript("enable-SPFeature -identity \"2dfc204b-e9da-4c6c-8b4f-c2f7c593ad4e\" -url sharepointsite -Confirm:$False");
               powershell.Invoke();
               Collection<PSObject> results = powershell.Invoke();
               remoteRunspace.Close();
               foreach (PSObject obj in results)
               {
                   stringBuilder.AppendLine(obj.ToString());
               }
           }

           return stringBuilder.ToString();
       }
       catch (Exception e)
       {

           return "";

       }


     }

    public static void  openRunspace(string uri, string schema, string username, string livePass, ref Runspace remoteRunspace)
    {
        System.Security.SecureString password = new System.Security.SecureString();
        foreach (char c in livePass.ToCharArray())
        {
            password.AppendChar(c);
        }
        PSCredential psc = new PSCredential(username, password);
        WSManConnectionInfo rri = new WSManConnectionInfo(new Uri(uri), schema, psc);
        rri.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
        rri.ProxyAuthentication = AuthenticationMechanism.Negotiate;
        remoteRunspace = RunspaceFactory.CreateRunspace(rri);
        remoteRunspace.Open();
    }
1
  • You have called the Invoke 2 times, why? Commented Aug 25, 2014 at 6:09

1 Answer 1

1

You can try to check if you have access to the SharePoint databases, to add snap-in correctly you need ShellAccess permission on Configuration database as I remember and farm admin rights. Possibly your script can't add snap-in, so cant do anything with SharePoint object model.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.