Подтвердить что ты не робот

Запустите PowerShell- Script из приложения С#

Я пытаюсь выполнить PowerShell script из приложения С#. script должен выполняться в специальном пользовательском контексте.

Я пробовал разные сценарии, некоторые из них работают не так:

1. прямой вызов из PowerShell

Я вызвал script непосредственно из ps-консоли, которая работает под правильными usercredentials.

C:\Scripts\GroupNewGroup.ps1 1

Результат: Успешно выполняется script.

2. из консольного приложения С#

Я вызвал script из консольного приложения С#, которое запускается под правильными usercredentials.

Код:

 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. из приложения консоли С# - код, выдающий себя за

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

Я вызвал script из c_конфигурации С#, которая запускается под правильными usercredentials, а код содержит олицетворение.

код:

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 не распознается как имя командлета, функция, файл script или операционная программа. Проверьте правильность написания имя, или если путь был включен, убедитесь, что путь правильный и повторите попытку.
  • Термин 'C:\Scripts\FunctionsObjects.ps1' не распознается как имя командлета, функция, файл script или операционная программа. Проверьте написание имени, или если путь был включен, убедитесь, что путь правильный и повторите попытку.
  • Никаких оснасток не было зарегистрировано для Windows PowerShell версии 2. Microsoft.Office.Server, Version = 14.0.0.0, Culture = нейтральный, PublicKeyToken = 71e9bce111e9429c
  • System.DirectoryServices.AccountManagement, Version = 4.0.0.0, Культура = нейтральная, PublicKeyToken = b77a5c561934e089
  • Вызов вызова ".ctor" с аргументом "1": "Веб-приложение в http://XXXX/websites/Test4/ не удалось найти. Убедитесь, что вы правильно напечатали URL. Если URL должен обслуживать существующие контента, системному администратору может потребоваться добавить новый URL-адрес запроса сопоставление с предполагаемым приложением ".
  • Вы не можете вызывать метод с нулевым значением. Нельзя индексировать в нулевой массив.

До сих пор нет рабочего ответа

Кто-нибудь знает, почему существуют различия и как решить проблему?

4b9b3361

Ответ 1

Вы пробовали Set-ExecutionPolicy Unrestricted

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

Edit:

Нашел этот маленький камень... 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
    }

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

Ответ 2

Я просто провел день, фиксируя это для себя.

Наконец, я смог заставить его работать, добавив -Scope Process в Set-ExecutionPolicy

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

Ответ 3

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 для вызовите команду "remote" локально, specifying the credential in the -Credential parameter, или вы можете вызвать Start-Job для выполнения работы в качестве фонового задания, passing the credentials you want into the -Credential parameter.

Смотрите здесь, здесь и в msdn для дополнительная информация