Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8102113
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T23:09:40+00:00 2026-06-05T23:09:40+00:00

I’m trying to execute a PowerShell script from a c# application. The script has

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T23:09:41+00:00Added an answer on June 5, 2026 at 11:09 pm

    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:uwe.keim@zeta-software.de)
        /// 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
        }
    
        /////////////////////////////////////////////////////////////////////////
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically, what I'm trying to create is a page of div tags, each has
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.