Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run PowerShell-Script from C# Application

I'm trying to execute a PowerShell script from a c# application. The script has to be executed under a special usercontext.

I've tried different scenarios some are working some not:

1. direct call from PowerShell

I've called the script directly from a ps-console which is running under the correct usercredentials.

C:\Scripts\GroupNewGroup.ps1 1

Result: Successfully running the script.

2. from a c# console application

I've called the script from a c# consoleapplication which is started under the correct usercredentials.

Code:

 string cmdArg = "C:\\Scripts\\GroupNewGroup.ps1 1"
 Runspace runspace = RunspaceFactory.CreateRunspace();
 runspace.ApartmentState = System.Threading.ApartmentState.STA;
 runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;


     runspace.Open();

 Pipeline pipeline = runspace.CreatePipeline();

 pipeline.Commands.AddScript(cmdArg);
 pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
 Collection<PSObject> results = pipeline.Invoke();
 var error = pipeline.Error.ReadToEnd();
 runspace.Close();

 if (error.Count >= 1)
 {
     string errors = "";
     foreach (var Error in error)
     {
         errors = errors + " " + Error.ToString();
     }
 }

Result: No Success. And a lot of "Null-Array" exceptions.

3. from a c# console application - code side impersonating

(http://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials)

I've called the script from a c# consoleapplication which is started under the correct usercredentials and the code contains impersonation.

Code:

using (new Impersonator("Administrator2", "domain", "testPW"))

                   {
  using (RunspaceInvoke invoker = new RunspaceInvoke()) 
{ 
    invoker.Invoke("Set-ExecutionPolicy Unrestricted"); 
} 

     string cmdArg = "C:\\Scripts\\GroupNewGroup.ps1 1";
     Runspace runspace = RunspaceFactory.CreateRunspace();
     runspace.ApartmentState = System.Threading.ApartmentState.STA;
     runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;


         runspace.Open();

     Pipeline pipeline = runspace.CreatePipeline();

     pipeline.Commands.AddScript(cmdArg);
     pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
     Collection<PSObject> results = pipeline.Invoke();
     var error = pipeline.Error.ReadToEnd();
     runspace.Close();

     if (error.Count >= 1)
     {
         string errors = "";
         foreach (var Error in error)
         {
             errors = errors + " " + Error.ToString();
         }
     }
 }  

Results:

  • The term 'Get-Contact' 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.
  • The term 'C:\Scripts\FunctionsObjects.ps1' 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.
  • No snap-ins have been registered for Windows PowerShell version 2. Microsoft.Office.Server, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c
  • System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
  • Exception calling ".ctor" with "1" argument(s): "The Web application at http://XXXX/websites/Test4/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application."
  • You cannot call a method on a null-valued expression. Cannot index into a null array.

Until now there is no working answer

Does anyone know why there are differences and how to solve the problem?

like image 768
HW90 Avatar asked Jun 20 '12 13:06

HW90


People also ask

How do I run a ps1 script from the command line?

ps1. Then, to execute the PowerShell script from the command line, launch the Windows command line by typing "cmd" into the search box and clicking the result. Type the full path of the PowerShell script, such as "C:\Example\example_script. ps1" and press enter.

Can you run a PowerShell script from CMD?

ps1 files are interpreted by PowerShell, the Command Prompt (CMD) cannot work with PowerShell scripts directly. If you would like to run a PowerShell script in CMD, you'll need to execute it by calling the PowerShell process with the -File parameter, as shown below: PowerShell -File C:\TEMP\MyNotepadScript. ps1.


2 Answers

Have you tried Set-ExecutionPolicy Unrestricted

using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) ) 
{ 
    using (RunspaceInvoke invoker = new RunspaceInvoke()) 
    { 
        invoker.Invoke("Set-ExecutionPolicy Unrestricted"); 
    } 
} 

Edit:

Found this little gem... http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User

namespace Tools
{
    #region Using directives.
    // ----------------------------------------------------------------------

    using System;
    using System.Security.Principal;
    using System.Runtime.InteropServices;
    using System.ComponentModel;

    // ----------------------------------------------------------------------
    #endregion

    /////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// Impersonation of a user. Allows to execute code under another
    /// user context.
    /// Please note that the account that instantiates the Impersonator class
    /// needs to have the 'Act as part of operating system' privilege set.
    /// </summary>
    /// <remarks>   
    /// This class is based on the information in the Microsoft knowledge base
    /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158
    /// 
    /// Encapsulate an instance into a using-directive like e.g.:
    /// 
    ///     ...
    ///     using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
    ///     {
    ///         ...
    ///         [code that executes under the new context]
    ///         ...
    ///     }
    ///     ...
    /// 
    /// Please contact the author Uwe Keim (mailto:[email protected])
    /// for questions regarding this class.
    /// </remarks>
    public class Impersonator :
        IDisposable
    {
        #region Public methods.
        // ------------------------------------------------------------------

        /// <summary>
        /// Constructor. Starts the impersonation with the given credentials.
        /// Please note that the account that instantiates the Impersonator class
        /// needs to have the 'Act as part of operating system' privilege set.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        public Impersonator(
            string userName,
            string domainName,
            string password )
        {
            ImpersonateValidUser( userName, domainName, password );
        }

        // ------------------------------------------------------------------
        #endregion

        #region IDisposable member.
        // ------------------------------------------------------------------

        public void Dispose()
        {
            UndoImpersonation();
        }

        // ------------------------------------------------------------------
        #endregion

        #region P/Invoke.
        // ------------------------------------------------------------------

        [DllImport("advapi32.dll", SetLastError=true)]
        private static extern int LogonUser(
            string lpszUserName,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        private static extern int DuplicateToken(
            IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        private static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
        private static extern  bool CloseHandle(
            IntPtr handle);

        private const int LOGON32_LOGON_INTERACTIVE = 2;
        private const int LOGON32_PROVIDER_DEFAULT = 0;

        // ------------------------------------------------------------------
        #endregion

        #region Private member.
        // ------------------------------------------------------------------

        /// <summary>
        /// Does the actual impersonation.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        private void ImpersonateValidUser(
            string userName, 
            string domain, 
            string password )
        {
            WindowsIdentity tempWindowsIdentity = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if ( RevertToSelf() )
                {
                    if ( LogonUser(
                        userName, 
                        domain, 
                        password, 
                        LOGON32_LOGON_INTERACTIVE,
                        LOGON32_PROVIDER_DEFAULT, 
                        ref token ) != 0 )
                    {
                        if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 )
                        {
                            tempWindowsIdentity = new WindowsIdentity( tokenDuplicate );
                            impersonationContext = tempWindowsIdentity.Impersonate();
                        }
                        else
                        {
                            throw new Win32Exception( Marshal.GetLastWin32Error() );
                        }
                    }
                    else
                    {
                        throw new Win32Exception( Marshal.GetLastWin32Error() );
                    }
                }
                else
                {
                    throw new Win32Exception( Marshal.GetLastWin32Error() );
                }
            }
            finally
            {
                if ( token!= IntPtr.Zero )
                {
                    CloseHandle( token );
                }
                if ( tokenDuplicate!=IntPtr.Zero )
                {
                    CloseHandle( tokenDuplicate );
                }
            }
        }

        /// <summary>
        /// Reverts the impersonation.
        /// </summary>
        private void UndoImpersonation()
        {
            if ( impersonationContext!=null )
            {
                impersonationContext.Undo();
            }   
        }

        private WindowsImpersonationContext impersonationContext = null;

        // ------------------------------------------------------------------
        #endregion
    }

    /////////////////////////////////////////////////////////////////////////
}
like image 69
Chris Gessler Avatar answered Oct 11 '22 14:10

Chris Gessler


I just spent the day fixing this for myself.

I finally was able to make it work by adding -Scope Process to Set-ExecutionPolicy

invoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process"); 
like image 31
Gunnar Steinn Avatar answered Oct 11 '22 15:10

Gunnar Steinn