从C#应用程序运行PowerShell脚本

时间:2012-06-20 13:16:40

标签: c# c#-4.0 powershell console-application

我正在尝试从c#应用程序执行PowerShell脚本。该脚本必须在特殊的usercontext下执行。

我尝试了不同的方案,有些人正在努力工作:

1。来自PowerShell的直接电话

我直接从ps-console调用脚本,该控制台在正确的用户凭据下运行。

C:\Scripts\GroupNewGroup.ps1 1

结果:成功运行脚本。

2。来自c#控制台应用程序

我从c#consoleapplication调用了脚本,该脚本是在正确的用户凭据下启动的。

代码:

 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();
     }
 }

结果:没有成功。还有很多“Null-Array”例外。

第3。来自c#控制台应用程序 - 代码端冒充

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

我从c#consoleapplication调用了脚本,该脚本在正确的用户凭据下启动,代码包含模拟。

代码:

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();
         }
     }
 }  

结果:

  • “Get-Contact”一词未被识别为cmdlet的名称, 功能,脚本文件或可操作程序。检查拼写 名称,或者如果包含路径,请验证路径是否正确 再试一次。
  • 术语“C:\ Scripts \ FunctionsObjects.ps1”未被识别为 cmdlet的名称,函数,脚本文件或可运行的程序。校验 名称的拼写,或者如果包含路径,请验证 路径是正确的,然后再试一次。
  • 没有为Windows PowerShell版本2注册管理单元。 Microsoft.Office.Server,Version = 14.0.0.0,Culture = neutral, 公钥= 71e9bce111e9429c
  • System.DirectoryServices.AccountManagement,Version = 4.0.0.0, Culture = neutral,PublicKeyToken = b77a5c561934e089
  • 使用“1”参数调用“.ctor”的异常:“Web应用程序 无法找到http://XXXX/websites/Test4/。验证你 已正确键入URL。如果URL应该是现有的 内容,系统管理员可能需要添加新的请求URL 映射到预期的应用程序。“
  • 您无法在空值表达式上调用方法。无法索引 进入一个空数组。

到目前为止还没有正常工作的答案

有谁知道为什么存在差异以及如何解决问题?

3 个答案:

答案 0 :(得分:8)

您是否尝试过Set-ExecutionPolicy Unrestricted

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

编辑:

找到这个小宝石...... 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
    }

    /////////////////////////////////////////////////////////////////////////
}

答案 1 :(得分:5)

我只是花了一天时间为自己解决这个问题。

我终于能够通过将 -Scope Process 添加到Set-ExecutionPolicy来实现它的工作

invoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process"); 

答案 2 :(得分:0)

Several PowerShell cmddlets take a PSCredential object to run using a particular user account。可以看看这篇文章 - http://letitknow.wordpress.com/2011/06/20/run-powershell-script-using-another-account/

以下是如何创建包含您要使用的用户名和密码的Credential对象:

$username = 'domain\user'
$password = 'something'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))

准备好在凭证对象中使用密码后,您可以执行许多操作,例如调用Start-Process启动PowerShell.exe,在-Credential参数中指定凭据,或调用Invoke-Command在本地调用“远程”命令specifying the credential in the -Credential parameter,或者您可以调用Start-Job来完成后台工作passing the credentials you want into the -Credential parameter

请参阅herehere&amp;在msdnmore information