Пример #1
0
 internal static CommandParameterInternal ToCommandParameterInternal(CommandParameter publicParameter, bool forNativeCommand)
 {
     string str2;
     if (publicParameter == null)
     {
         throw PSTraceSource.NewArgumentNullException("publicParameter");
     }
     string name = publicParameter.Name;
     object obj2 = publicParameter.Value;
     if (name == null)
     {
         return CommandParameterInternal.CreateArgument(PositionUtilities.EmptyExtent, obj2, false);
     }
     if (!name[0].IsDash())
     {
         str2 = forNativeCommand ? name : ("-" + name);
         return CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, name, str2, PositionUtilities.EmptyExtent, obj2, true);
     }
     bool spaceAfterParameter = false;
     int length = name.Length;
     while ((length > 0) && char.IsWhiteSpace(name[length - 1]))
     {
         spaceAfterParameter = true;
         length--;
     }
     str2 = name.Substring(0, length);
     bool flag2 = name[length - 1] == ':';
     string parameterName = str2.Substring(1, str2.Length - (flag2 ? 2 : 1));
     if (!flag2 && (obj2 == null))
     {
         return CommandParameterInternal.CreateParameter(PositionUtilities.EmptyExtent, parameterName, str2);
     }
     return CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, parameterName, str2, PositionUtilities.EmptyExtent, obj2, spaceAfterParameter);
 }
Пример #2
0
        private Hashtable GetConfigRaw(string env, string scriptFilePath, string xmlDefn = null)
        {
            using (var runspace = RunspaceFactory.CreateRunspace())
            {
                using (var pipeline = runspace.CreatePipeline())
                {
                    var getConfigCmd = new Command(scriptFilePath);
                    var envParam = new CommandParameter("Env", env);
                    getConfigCmd.Parameters.Add(envParam);

                    if (xmlDefn != null)
                    {
                        var envFileContentParam = new CommandParameter("EnvFileContent", xmlDefn);
                        getConfigCmd.Parameters.Add(envFileContentParam);
                    }

                    pipeline.Commands.Add(getConfigCmd);
                    runspace.Open();

                    Collection<PSObject> results = pipeline.Invoke();
                    var res = results[0].BaseObject as Hashtable;
                    if (res == null)
                    {
                        throw new Exception("Missing Config");
                    }

                    return res;
                }
            }
        }
Пример #3
0
        public static string ExecuteShellScript(List<string> getshellstrlist, List<ShellParameter> getshellparalist)
        {
            string getresutl = null;
            try
            {
                //Create Runspace
                Runspace newspace = RunspaceFactory.CreateRunspace();
                Pipeline newline = newspace.CreatePipeline();

                //open runspace
                newspace.Open();

                if (getshellstrlist.Count > 0)
                {
                    foreach (string getshellstr in getshellstrlist)
                    {
                        //Add Command ShellString
                        newline.Commands.AddScript(getshellstr);
                    }
                }

                //Check Parameter
                if (getshellparalist != null && getshellparalist.Count > 0)
                {
                    int count = 0;
                    foreach (ShellParameter getshellpar in getshellparalist)
                    {
                        //Set parameter
                        //注入脚本一个.NEt对象 这样在powershell脚本中就可以直接通过$key访问和操作这个对象
                        //newspace.SessionStateProxy.SetVariable(getshellpar.ShellKey,getshellpar.ShellValue);
                        CommandParameter cmdpara = new CommandParameter(getshellpar.ShellKey, getshellpar.ShellValue);
                        newline.Commands[count].Parameters.Add(cmdpara);
                    }
                }

                //Exec Restult
                var getresult = newline.Invoke();
                if (getresult != null)
                {
                    StringBuilder getbuilder = new StringBuilder();
                    foreach (var getresstr in getresult)
                    {
                        getbuilder.AppendLine(getresstr.ToString());
                    }
                    getresutl = getbuilder.ToString();
                }

                //close 
                newspace.Close();
            }
            catch (Exception se)
            {
                //catch Excetption 
            }
            return getresutl;
        }
Пример #4
0
        static void Main(string[] args)
        {
            string scriptPath = @".\simple_example.ps1";
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            Command myCommand = new Command(scriptPath);
            CommandParameter userParam = new CommandParameter("message", "hello, i'm a message");
            myCommand.Parameters.Add(userParam);

            pipeline.Commands.Add(myCommand);
            Collection<PSObject> results = pipeline.Invoke();

            foreach (PSObject obj in results)
            {
                Console.Out.WriteLine(obj.ToString());
            }

            Console.ReadLine();
        }
        /// <summary>
        /// Invokes a powershell script using the same runspace as the caller.
        /// </summary>
        /// <param name="scriptName">script name</param>
        /// <param name="parameters">parameters for the script</param>
        /// <returns></returns>
        private static Collection<PSObject> InvokeScript(string scriptName, Hashtable parameters)
        {
            using (Pipeline pipe = Runspace.DefaultRunspace.CreateNestedPipeline())
            {
                Command scriptCommand = new Command(scriptName);

                foreach (DictionaryEntry parameter in parameters)
                {
                    CommandParameter commandParm = new CommandParameter(parameter.Key.ToString(), parameter.Value);
                    scriptCommand.Parameters.Add(commandParm);
                }
                pipe.Commands.Add(scriptCommand);

                var result = pipe.Invoke();

                //Error handling
                if (pipe.Error.Count > 0)
                {
                    StringBuilder errorStringBuilder = new StringBuilder();
                    while (!pipe.Error.EndOfPipeline)
                    {
                        var value = pipe.Error.Read() as PSObject;
                        if (value != null)
                        {
                            var r = value.BaseObject as ErrorRecord;
                            if (r != null)
                            {
                                errorStringBuilder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
                                errorStringBuilder.AppendLine(r.InvocationInfo.PositionMessage);
                            }
                        }
                    }

                    throw new AzureAutomationOperationException(string.Format(CultureInfo.CurrentCulture,
                        Resources.PowershellJsonDecrypterFailed, errorStringBuilder.ToString()));
                }
                return result;
            }
        }
Пример #6
0
        private static string RunPowerShellScript(string command, Dictionary<string,string> parameters)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

            Pipeline pipeline = runspace.CreatePipeline();

            //Here's how you add a new script with arguments
            Command myCommand = new Command(command);

            foreach (KeyValuePair<string, string> parameter in parameters)
            {
                CommandParameter param = new CommandParameter(parameter.Key, parameter.Value);
                myCommand.Parameters.Add(param);
            }

            pipeline.Commands.Add(myCommand);

            // Execute PowerShell script
            var results = pipeline.Invoke();

            // close the runspace

            runspace.Close();

            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            string returnText =  stringBuilder.ToString();
            return returnText;
        }
Пример #7
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            btnSubmit.Visible = false;

            #region "Submit Form"
            string approve = ddlApprove.SelectedItem.ToString();
            string comment = txtComments.Text;

            ManagementScope scope = new ManagementScope("\\\\" + sSiteServer + "\\root\\sms\\Site_" + sSiteCode);
            scope.Connect();
            ObjectQuery query = new ObjectQuery("SELECT * FROM SMS_UserApplicationRequest WHERE CurrentState = 1 and RequestGuid ='" + sUID + "'");
            ManagementObjectSearcher search = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection queryCollection = search.Get();

            foreach (ManagementObject User in queryCollection)
            {

                strUser = User["User"].ToString();
                strAppR = User["Application"].ToString();
                strAppC = User["Comments"].ToString();

                ManagementBaseObject inParams = User.GetMethodParameters(approve);
                inParams["Comments"] = comment;
                User.InvokeMethod(approve, inParams, null);

            }
            #endregion

            #region "Orchestrator Runbook"

            if (sRB == "True")
            {

                Guid runbookId = new Guid(sRBUID);
                string serviceRoot = sSCORCH;

                SCOService.OrchestratorContext context = new SCOService.OrchestratorContext(new Uri(serviceRoot));
                context.Credentials = System.Net.CredentialCache.DefaultCredentials;

                var runbookParams = context.RunbookParameters.Where(runbookParam => runbookParam.RunbookId == runbookId && runbookParam.Direction == "In");

                StringBuilder parametersXml = new StringBuilder();
                if (runbookParams != null && runbookParams.Count() > 0)
                {
                    parametersXml.Append("<Data>");
                    foreach (var param in runbookParams)
                    {
                        if (param.Name == sRBPUser)
                        {
                            parametersXml.AppendFormat("<Parameter><ID>{0}</ID><Value>{1}</Value></Parameter>", param.Id.ToString("B"), strUser);
                        }

                        if (param.Name == sRBPUserComments)
                        {
                            parametersXml.AppendFormat("<Parameter><ID>{0}</ID><Value>{1}</Value></Parameter>", param.Id.ToString("B"), strAppC);
                        }

                        if (param.Name == sRBPApplication)
                        {
                            parametersXml.AppendFormat("<Parameter><ID>{0}</ID><Value>{1}</Value></Parameter>", param.Id.ToString("B"), strAppR);
                        }

                        if (param.Name == sRBPAppComments)
                        {
                            parametersXml.AppendFormat("<Parameter><ID>{0}</ID><Value>{1}</Value></Parameter>", param.Id.ToString("B"), comment);
                        }

                        if (param.Name == sRBPAppAproveDeny)
                        {
                            parametersXml.AppendFormat("<Parameter><ID>{0}</ID><Value>{1}</Value></Parameter>", param.Id.ToString("B"), approve);
                        }

                    }
                    parametersXml.Append("</Data>");
                }

                try
                {
                    // Create new job and assign runbook Id and parameters.
                    AppApproval.SCOService.Job job = new AppApproval.SCOService.Job();
                    job.RunbookId = runbookId;
                    job.Parameters = parametersXml.ToString();

                    // Add newly created job.
                    context.AddToJobs(job);
                    context.SaveChanges();

                }

                catch (DataServiceQueryException ex)
                {
                    throw new ApplicationException("Error starting runbook.", ex);
                }
            }

            #endregion

            #region "PS Script"
            if (sPS == "True")
            {

                RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
                Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
                runspace.Open();

                RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                Pipeline pipeline = runspace.CreatePipeline();

                Command myCommand = new Command(ScriptPath);

                if (string.IsNullOrEmpty(PSUser)) {
                }
                else {
                    CommandParameter cpPSUser = new CommandParameter(PSUser, strUser);
                    myCommand.Parameters.Add(cpPSUser);
                }

                if (string.IsNullOrEmpty(PSApplication)) {
                }
                else {
                    CommandParameter cpPSApplication = new CommandParameter(PSApplication, strAppR);
                    myCommand.Parameters.Add(cpPSApplication);
                }

                if (string.IsNullOrEmpty(PSUserComments)) {
                }
                else {
                    CommandParameter cpPSUserComments = new CommandParameter(PSUserComments, strAppC);
                    myCommand.Parameters.Add(cpPSUserComments);
                }

                if (string.IsNullOrEmpty(PSAppComments)) {
                }
                else {
                    CommandParameter cpPSAppComments = new CommandParameter(PSAppComments, comment);
                    myCommand.Parameters.Add(cpPSAppComments);
                }

                if (string.IsNullOrEmpty(PSAppAproveDeny)) {
                }
                else {
                    CommandParameter cpPSAppAproveDeny = new CommandParameter(PSAppAproveDeny, approve);
                    myCommand.Parameters.Add(cpPSAppAproveDeny);
                }

                pipeline.Commands.Add(myCommand);
                Collection<PSObject> results = pipeline.Invoke();

            }
            #endregion
        }
Пример #8
0
 private object GetParameterValue(ParameterAst scriptParameter, CommandParameter argument)
 {
     if (argument != null)
     {
         return argument.Value;
     }
     if (scriptParameter.DefaultValue == null)
     {
         return null;
     }
     return _executionVisitor.EvaluateAst(scriptParameter.DefaultValue);
 }
Пример #9
0
        public void RunScript()
        {
            cancel = false;
            rslts.Clear();
            InitializeSessionVars();
            PSAlert.ScriptName = scriptcommand.Replace(poshsecframework.Properties.Settings.Default.ScriptPath, "");
            PSTab.ScriptName = scriptcommand.Replace(poshsecframework.Properties.Settings.Default.ScriptPath, "");
            Pipeline pline = null;
            bool cancelled = false;
            try
            {
                if (clicked && !scheduled)
                {
                    //Only run this if the user double clicked a script or command.
                    //If they typed the command then they should have passed params.
                    //If it was scheduled and there were params, they should be passed.
                    scriptparams = CheckForParams(scriptcommand);
                }
                if (!cancel)
                {
                    Command pscmd = new Command(scriptcommand);
                    String cmdparams = "";
                    if (scriptparams != null)
                    {
                        foreach (psparameter param in scriptparams)
                        {
                            CommandParameter prm = new CommandParameter(param.Name, param.Value ?? param.DefaultValue);
                            pscmd.Parameters.Add(prm);
                            cmdparams += " -" + param.Name + " " + param.Value;
                        }
                    }

                    pline = rspace.CreatePipeline();
                    if (iscommand)
                    {
                        String cmdscript = scriptcommand + cmdparams;
                        if (clicked)
                        {
                            rslts.AppendLine(scriptcommand + cmdparams);
                        }
                        pline.Commands.AddScript(cmdscript);
                        pline.Commands.Add(StringValue.OutString);
                    }
                    else
                    {
                        rslts.AppendLine("Running script: " + scriptcommand.Replace(poshsecframework.Properties.Settings.Default.ScriptPath, ""));
                        pline.Commands.Add(pscmd);
                    }
                    Collection<PSObject> rslt = null;
                    try
                    {
                        rslt = pline.Invoke();
                    }
                    catch (System.Threading.ThreadAbortException)
                    {
                        if (pline != null)
                        {
                            HandleWarningsErrors(pline.Error);
                        }
                        cancelled = true;
                        if (iscommand)
                        {
                            rslts.AppendLine(StringValue.CommandCancelled);
                        }
                        else
                        {
                            rslts.AppendLine(StringValue.ScriptCancelled);
                        }
                    }
                    catch (Exception pex)
                    {
                        rslts.AppendLine(psexec.psexceptionhandler(pex, iscommand, pline.Commands));
                    }
                    HandleWarningsErrors(pline.Error);
                    pline.Dispose();
                    pline = null;
                    if (rslt != null)
                    {
                        foreach (PSObject po in rslt)
                        {
                            if (po != null)
                            {
                                rslts.AppendLine(po.ToString());
                            }
                        }
                    }
                }
                else
                {
                    rslts.AppendLine(StringValue.ScriptCancelled);
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                if (pline != null)
                {
                    pline.Stop();
                    pline.Dispose();
                    pline = null;
                }
                GC.Collect();
            }
            catch (Exception e)
            {
                if (pline != null)
                {
                    HandleWarningsErrors(pline.Error);
                }                
                rslts.AppendLine(psexec.psexceptionhandler(e, iscommand));
            }
            finally
            {
                if (pline != null)
                {
                    pline.Dispose();
                }
                pline = null;
                GC.Collect();
                OnScriptComplete(new pseventargs(rslts.ToString(), scriptlvw, cancelled));
                rslts.Clear();
            }            
        }
Пример #10
0
        private void CreateChildJob(JobInvocationInfo specification, Activity activity, ContainerParentJob newJob, CommandParameterCollection commandParameterCollection, Dictionary<string, object> parameterDictionary, string computerName, string[] computerNames)
        {
            if (!string.IsNullOrEmpty(computerName))
            {
                string[] childTargetComputerList = { computerName };

                // Set the target computer for this child job...
                parameterDictionary[Constants.ComputerName] = childTargetComputerList;
            }

            var childSpecification = new JobInvocationInfo(specification.Definition, parameterDictionary);

            // Job objects will be disposed of on parent job removal.
            var childJob = new PSWorkflowJob(_runtime, childSpecification);
            childJob.JobMetadata = CreateJobMetadata(childJob, newJob.InstanceId, newJob.Id, newJob.Name, newJob.Command, computerNames);

            // Remove the parameter from the collection...
            for (int index = 0; index < commandParameterCollection.Count; index++)
            {
                if (string.Equals(commandParameterCollection[index].Name, Constants.ComputerName, StringComparison.OrdinalIgnoreCase))
                {
                    commandParameterCollection.RemoveAt(index);
                    break;
                }
            }

            if (!string.IsNullOrEmpty(computerName))
            {
                var computerNameParameter = new CommandParameter(Constants.ComputerName, computerName);
                commandParameterCollection.Add(computerNameParameter);
            }

            this.AddJob(childJob);
            childJob.LoadWorkflow(commandParameterCollection, activity, null);
            newJob.AddChildJob(childJob);
            StructuredTracer.ChildWorkflowJobAddition(childJob.InstanceId, newJob.InstanceId);
            Tracer.TraceJob(childJob);
            StructuredTracer.WorkflowJobCreated(newJob.InstanceId, childJob.InstanceId, childJob.WorkflowGuid);
        }
Пример #11
0
 private object GetParameterValue(ParameterAst scriptParameter, CommandParameter parameter)
 {
     if (parameter != null)
     {
         return parameter.Value;
     }
     return _scopedExecutionVisitor.EvaluateAst(scriptParameter.DefaultValue);;
 }
Пример #12
0
        internal static CommandParameterInternal ToCommandParameterInternal(CommandParameter publicParameter, bool forNativeCommand)
        {
            if (publicParameter == null)
            {
                throw PSTraceSource.NewArgumentNullException("publicParameter");
            }

            string name  = publicParameter.Name;
            object value = publicParameter.Value;

            Debug.Assert((name == null) || (name.Trim().Length != 0), "Parameter name has to null or have some non-whitespace characters in it");

            if (name == null)
            {
                return(CommandParameterInternal.CreateArgument(value));
            }

            string parameterText;

            if (!name[0].IsDash())
            {
                parameterText = forNativeCommand ? name : "-" + name;
                return(CommandParameterInternal.CreateParameterWithArgument(
                           /*parameterAst*/ null, name, parameterText,
                           /*argumentAst*/ null, value,
                           true));
            }

            // if first character of name is '-', then we try to fake the original token
            // reconstructing dashes, colons and followed-by-space information

            // find the last non-whitespace character
            bool spaceAfterParameter = false;
            int  endPosition         = name.Length;

            while ((endPosition > 0) && char.IsWhiteSpace(name[endPosition - 1]))
            {
                spaceAfterParameter = true;
                endPosition--;
            }
            Debug.Assert(endPosition > 0, "parameter name should have some non-whitespace characters in it");

            // now make sure that parameterText doesn't have whitespace at the end,
            parameterText = name.Substring(0, endPosition);

            // parameterName should contain only the actual name of the parameter (no whitespace, colons, dashes)
            bool hasColon      = (name[endPosition - 1] == ':');
            var  parameterName = parameterText.Substring(1, parameterText.Length - (hasColon ? 2 : 1));

            // At this point we have rebuilt the token.  There are 3 strings that might be different:
            //           name = nameToken.Script = "-foo: " <- needed to fake FollowedBySpace=true (i.e. for "testecho.exe -a:b -c: d")
            // tokenString = nameToken.TokenText = "-foo:" <- needed to preserve full token text (i.e. for write-output)
            //                    nameToken.Data =  "foo" <- needed to preserve name of parameter so parameter binding works
            // Now we just need to use the token to build appropriate CommandParameterInternal object

            // is this a name+value pair, or is it just a name (of a parameter)?
            if (!hasColon && value == null)
            {
                // just a name
                return(CommandParameterInternal.CreateParameter(parameterName, parameterText));
            }

            // name+value pair
            return(CommandParameterInternal.CreateParameterWithArgument(
                       /*parameterAst*/ null, parameterName, parameterText,
                       /*argumentAst*/ null, value,
                       spaceAfterParameter));
        }
Пример #13
0
    protected void Button3_Click(object sender, EventArgs e)
    {
        Button1.Enabled = true;
        commit.Enabled = false;
        rollback.Enabled = false;
        GridView1.DataSource = null;
        GridView1.DataBind();
        msg.Text = "";
        //SqlConnection.ClearAllPools();
        switch (DropDownList1.SelectedItem.Text)
        {
            case "SQL Server":
                string s = "Data Source=localhost;Initial Catalog=master" + "; User ID=sa; Password=***;";
                SqlConnection ProcConn = new SqlConnection(s);

                try
                {
                    ProcConn.Open();
                    SqlCommand cmd = new SqlCommand("spCreateUserDb", ProcConn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(
                            new SqlParameter("@sourceDb", DropDownList2.SelectedItem.Text));
                    cmd.Parameters.Add(
                            new SqlParameter("@destDb", User.Identity.Name + DropDownList2.SelectedItem.Text));
                    cmd.ExecuteNonQuery();
                    //msg.Text += "Database Created: " + User.Identity.Name + DropDownList2.SelectedItem.Text;
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";

                }
                catch (Exception)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database "+ DropDownList2.Text + " creation failed');</script>"));
                }
                finally
                {
                    if (ProcConn != null)
                    {
                        ProcConn.Close();
                    }

                }
                break;
            case "Access":

                RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
                try
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
                    {
                        runspace.Open();
                        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                        Pipeline pipeline = runspace.CreatePipeline();
                        string scriptfile = "C:\\SourceDatabase\\Access\\powershellCreateDB.ps1";
                        //add a new script with arguments
                        Command myCommand = new Command(scriptfile);
                        CommandParameter SourceParam = new CommandParameter("source", DropDownList2.SelectedItem.Text);
                        CommandParameter TargetParam = new CommandParameter("target", User.Identity.Name);
                        myCommand.Parameters.Add(SourceParam);
                        myCommand.Parameters.Add(TargetParam);
                        pipeline.Commands.Add(myCommand);
                        // Execute PowerShell script; powershell should set-executionpolicy remotesigned.
                        // Otherwise Error: "File C:\SourceDatabase\Access\powershellCreateDB.ps1 cannot be loaded because running scripts is disabled on this system.
                        // For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170."
                        // error "AuthorizationManager check failed" caused by the version of 32bit or 64 bit, solution : resave it.
                        pipeline.Invoke();

                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    msg.Text = ex.Message;
                }
                break;
            case "MySQL":
                string str = "server=localhost;Database=" + DropDownList2.SelectedItem.Text + ";Uid=root;Pwd=***;";
                string file = "C:\\SourceDatabase\\MySQL\\" + DropDownList2.SelectedItem.Text + ".sql";
                try
                {
                    using (MySqlConnection conn = new MySqlConnection(str))
                    {
                        using (MySqlCommand cmd = new MySqlCommand())
                        {
                            cmd.CommandText = "DROP DATABASE IF EXISTS " + User.Identity.Name + DropDownList2.SelectedItem.Text;
                            cmd.Connection = conn;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            using (MySqlBackup mb = new MySqlBackup(cmd))
                            {
                                //cmd.Connection = conn;
                                //conn.Open();
                                mb.ImportInfo.TargetDatabase = User.Identity.Name + DropDownList2.SelectedItem.Text;
                                mb.ImportFromFile(file);
                            }
                        }
                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    output.Text = ex.Message;
                }
                break;

            case "PostgreSQL":
                string ps = "Server=127.0.0.1;Port=5432;Database=template1;User Id=postgres; Password=***;Pooling=false;";
                try
                {
                    using (NpgsqlConnection conn = new NpgsqlConnection(ps))
                    {
                        using (NpgsqlCommand cmd = new NpgsqlCommand())
                        {
                            cmd.CommandText = "DROP DATABASE IF EXISTS " + User.Identity.Name + DropDownList2.SelectedItem.Text;
                            cmd.Connection = conn;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            cmd.CommandText = "CREATE DATABASE " + User.Identity.Name + DropDownList2.SelectedItem.Text + " TEMPLATE " + DropDownList2.SelectedItem.Text;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    output.Text = ex.Message;
                }
                break;
            case "SQLite":
                RunspaceConfiguration SQLiterunspaceConfiguration = RunspaceConfiguration.Create();
                try
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(SQLiterunspaceConfiguration))
                    {
                        runspace.Open();
                        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                        Pipeline pipeline = runspace.CreatePipeline();
                        string scriptfile = "C:\\SourceDatabase\\SQLite\\powershellCreateDB.ps1";
                        //add a new script with arguments
                        Command myCommand = new Command(scriptfile);
                        CommandParameter SourceParam = new CommandParameter("source", DropDownList2.SelectedItem.Text);
                        CommandParameter TargetParam = new CommandParameter("target", User.Identity.Name);
                        myCommand.Parameters.Add(SourceParam);
                        myCommand.Parameters.Add(TargetParam);
                        pipeline.Commands.Add(myCommand);
                        // Execute PowerShell script; powershell should set-executionpolicy remotesigned.
                        // Otherwise Error: "File C:\SourceDatabase\Access\powershellCreateDB.ps1 cannot be loaded because running scripts is disabled on this system.
                        // For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170."
                        // error "AuthorizationManager check failed" caused by the version of 32bit or 64 bit, solution : resave it.
                        pipeline.Invoke();

                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    msg.Text = ex.Message;
                }
                break;
            case "Oracle":
            case "DB2":
                Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Error\\nDataBase already exists, no need to create.');</script>"));
                break;
            default:
                //msg.Text = "no such database";
                Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Error\\nPlease choose a database');</script>"));
                break;
        }
    }
Пример #14
0
        CreateCommandProcessor
        (
            ExecutionContext executionContext,
            bool addToHistory,
            CommandOrigin origin
        )
        {
            Dbg.Assert(executionContext != null, "Caller should verify the parameters");

            CommandProcessorBase commandProcessorBase;

            if (IsScript)
            {
                if ((executionContext.LanguageMode == PSLanguageMode.NoLanguage) &&
                    (origin == Automation.CommandOrigin.Runspace))
                {
                    throw InterpreterError.NewInterpreterException(CommandText, typeof(ParseException),
                                                                   null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed);
                }

                ScriptBlock scriptBlock = executionContext.Engine.ParseScriptBlock(CommandText, addToHistory);
                if (origin == Automation.CommandOrigin.Internal)
                {
                    scriptBlock.LanguageMode = PSLanguageMode.FullLanguage;
                }

                // If running in restricted language mode, verify that the parse tree represents on legitimate
                // constructions...
                switch (scriptBlock.LanguageMode)
                {
                case PSLanguageMode.RestrictedLanguage:
                    scriptBlock.CheckRestrictedLanguage(null, null, false);
                    break;

                case PSLanguageMode.FullLanguage:
                    // Interactive script commands are permitted in this mode.
                    break;

                case PSLanguageMode.ConstrainedLanguage:
                    // Constrained Language is checked at runtime.
                    break;

                default:
                    // This should never happen...
                    Diagnostics.Assert(false, "Invalid language mode was set when building a ScriptCommandProcessor");
                    throw new InvalidOperationException("Invalid language mode was set when building a ScriptCommandProcessor");
                }

                if (scriptBlock.UsesCmdletBinding)
                {
                    FunctionInfo functionInfo = new FunctionInfo(string.Empty, scriptBlock, executionContext);
                    commandProcessorBase = new CommandProcessor(functionInfo, executionContext,
                                                                _useLocalScope ?? false, fromScriptFile: false, sessionState: executionContext.EngineSessionState);
                }
                else
                {
                    commandProcessorBase = new DlrScriptCommandProcessor(scriptBlock,
                                                                         executionContext, _useLocalScope ?? false,
                                                                         origin,
                                                                         executionContext.EngineSessionState,
                                                                         DollarUnderbar);
                }
            }
            else
            {
                // RestrictedLanguage / NoLanguage do not support dot-sourcing when CommandOrigin is Runspace
                if ((_useLocalScope.HasValue) && (!_useLocalScope.Value))
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        string message = StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed,
                                                           "UseLocalScope",
                                                           PSLanguageMode.RestrictedLanguage.ToString(),
                                                           PSLanguageMode.NoLanguage.ToString());
                        throw new RuntimeException(message);

                    case PSLanguageMode.FullLanguage:
                        // Interactive script commands are permitted in this mode...
                        break;
                    }
                }

                commandProcessorBase = executionContext.CommandDiscovery.LookupCommandProcessor(CommandText, origin, _useLocalScope);
            }

            CommandParameterCollection parameters = Parameters;

            if (parameters != null)
            {
                bool isNativeCommand = commandProcessorBase is NativeCommandProcessor;
                foreach (CommandParameter publicParameter in parameters)
                {
                    CommandParameterInternal internalParameter = CommandParameter.ToCommandParameterInternal(publicParameter, isNativeCommand);
                    commandProcessorBase.AddParameter(internalParameter);
                }
            }

            string       helpTarget;
            HelpCategory helpCategory;

            if (commandProcessorBase.IsHelpRequested(out helpTarget, out helpCategory))
            {
                commandProcessorBase = CommandProcessorBase.CreateGetHelpCommandProcessor(
                    executionContext,
                    helpTarget,
                    helpCategory);
            }

            // Set the merge settings
            SetMergeSettingsOnCommandProcessor(commandProcessorBase);

            return(commandProcessorBase);
        }
Пример #15
0
		private void DeserializeInvocationInfo(SerializationInfo info)
		{
			string str = info.GetString("InvocationInfo_Command");
			string str1 = info.GetString("InvocationInfo_Name");
			string str2 = info.GetString("InvocationInfo_ModuleName");
			string str3 = info.GetString("InvocationInfo_AdapterTypeName");
			Dictionary<string, object> strs = new Dictionary<string, object>();
			string str4 = info.GetString("InvocationParam_ScriptBlock");
			if (str4 != null)
			{
				strs.Add("ScriptBlock", ScriptBlock.Create(str4));
			}
			string str5 = info.GetString("InvocationParam_FilePath");
			if (!string.IsNullOrEmpty(str5))
			{
				strs.Add("FilePath", str5);
			}
			str4 = info.GetString("InvocationParam_InitScript");
			if (!string.IsNullOrEmpty(str4))
			{
				strs.Add("InitializationScript", ScriptBlock.Create(str4));
			}
			bool flag = info.GetBoolean("InvocationParam_RunAs32");
			strs.Add("RunAs32", flag);
			AuthenticationMechanism value = (AuthenticationMechanism)info.GetValue("InvocationParam_Authentication", typeof(AuthenticationMechanism));
			strs.Add("Authentication", value);
			object[] objArray = (object[])info.GetValue("InvocationParam_ArgList", typeof(object[]));
			if (objArray != null)
			{
				strs.Add("ArgumentList", objArray);
			}
			JobDefinition jobDefinition = new JobDefinition(null, str, str1);
			jobDefinition.ModuleName = str2;
			jobDefinition.JobSourceAdapterTypeName = str3;
			CommandParameterCollection commandParameterCollection = new CommandParameterCollection();
			foreach (KeyValuePair<string, object> keyValuePair in strs)
			{
				CommandParameter commandParameter = new CommandParameter(keyValuePair.Key, keyValuePair.Value);
				commandParameterCollection.Add(commandParameter);
			}
			base.Definition = jobDefinition;
			base.Name = str1;
			base.Command = str;
			base.Parameters.Add(commandParameterCollection);
		}
Пример #16
0
        internal PSWorkflowJob CreateJobInternal(Guid jobInstanceId, Activity workflow, string command, string name, Dictionary<string, object> parameters, string xaml, Dictionary<string, object> creationContext)
        {
            AssertNotDisposed();

            if (jobInstanceId == Guid.Empty)
                throw new ArgumentNullException("jobInstanceId");

            if (workflow == null)
                throw new ArgumentNullException("workflow");

            if (command == null)
                throw new ArgumentNullException("command");

            if (name == null)
                throw new ArgumentNullException("name");

            if (_wfJobTable.ContainsKey(jobInstanceId))
            {
                ArgumentException exception = new ArgumentException(Resources.DuplicateInstanceId);
                Tracer.TraceException(exception);
                throw exception;
            }

            lock (lockObjects.GetLockObject(jobInstanceId))
            {

                if (_wfJobTable.ContainsKey(jobInstanceId))
                {
                    ArgumentException exception = new ArgumentException(Resources.DuplicateInstanceId);
                    Tracer.TraceException(exception);
                    throw exception;
                }

                JobDefinition definition = new JobDefinition(typeof(WorkflowJobSourceAdapter), command, name);

                var parameterDictionary = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);

                if (parameters != null)
                {
                    foreach (KeyValuePair<string, object> param in parameters)
                    {
                        parameterDictionary.Add(param.Key, param.Value);
                    }
                }

                string[] computerNames = null;
                bool gotComputerNames = false;
                object value;
                if (parameterDictionary.Count != 0 && parameterDictionary.TryGetValue(Constants.ComputerName, out value))
                {
                    if (LanguagePrimitives.TryConvertTo(value, CultureInfo.InvariantCulture, out computerNames))
                        gotComputerNames = computerNames != null;
                }

                if (gotComputerNames)
                {
                    if (computerNames.Length > 1)
                        throw new ArgumentException(Resources.OneComputerNameAllowed);

                    parameterDictionary.Remove(Constants.ComputerName);
                }

                var childSpecification = new JobInvocationInfo(definition, parameterDictionary);
                childSpecification.Command = command;

                // If actual computernames were specified, then set the PSComputerName parameter.
                if (gotComputerNames)
                {
                    var computerNameParameter = new CommandParameter(Constants.ComputerName, computerNames);
                    childSpecification.Parameters[0].Add(computerNameParameter);
                }

                // Job objects will be disposed of on parent job removal.
                var childJob = new PSWorkflowJob(_runtime, childSpecification, jobInstanceId, creationContext);
                childJob.JobMetadata = CreateJobMetadataWithNoParentDefined(childJob, computerNames);

                childJob.LoadWorkflow(childSpecification.Parameters[0], workflow, xaml);
                this.AddJob(childJob);

                return childJob;
            }
        }
Пример #17
0
        /// <summary>
        /// CreateJob
        /// </summary>
        /// <param name="jobInvocationInfo"></param>
        /// <param name="activity"></param>
        /// <returns></returns>
        internal ContainerParentJob CreateJob(JobInvocationInfo jobInvocationInfo, Activity activity)
        {
            if (jobInvocationInfo == null)
                throw new ArgumentNullException("jobInvocationInfo");

            if (jobInvocationInfo.Definition == null)
                throw new ArgumentException(Resources.NewJobDefinitionNull, "jobInvocationInfo");

            if (jobInvocationInfo.Command == null)
                throw new ArgumentException(Resources.NewJobDefinitionNull, "jobInvocationInfo");

            DynamicActivity dynamicActivity = activity as DynamicActivity;

            Debug.Assert(dynamicActivity != null, "Passed workflow must be a DynamicActivity");

            Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Creating Workflow job with definition: {0}", jobInvocationInfo.Definition.InstanceId));

            // Create parent job. All PSWorkflowJob objects will be a child of some ContainerParentJob
            // This job will be disposed of when RemoveJob is called.
            ContainerParentJob newJob = new ContainerParentJob(
                jobInvocationInfo.Command, 
                jobInvocationInfo.Name,
                WorkflowJobSourceAdapter.AdapterTypeName);

            foreach (CommandParameterCollection commandParameterCollection in jobInvocationInfo.Parameters)
            {
                var parameterDictionary = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);
                foreach (CommandParameter param in commandParameterCollection)
                {
                    parameterDictionary.Add(param.Name, param.Value);
                }

                string[] computerNames = null;
                bool gotComputerNames = false;
                object value;
                if (parameterDictionary.Count != 0 && parameterDictionary.TryGetValue(Constants.ComputerName, out value))
                {
                    if (LanguagePrimitives.TryConvertTo(value, CultureInfo.InvariantCulture, out computerNames))
                        gotComputerNames = computerNames != null;
                }

                StructuredTracer.ParentJobCreated(newJob.InstanceId);

                bool isComputerNameExists = false;

                if (dynamicActivity != null && dynamicActivity.Properties.Any(x => x.Name.Equals(Constants.ComputerName, StringComparison.CurrentCultureIgnoreCase)))
                {
                    isComputerNameExists = true;
                }

                dynamicActivity = null;

                if (isComputerNameExists)
                {
                    var childSpecification = new JobInvocationInfo(jobInvocationInfo.Definition, parameterDictionary);
                    childSpecification.Command = newJob.Command;

                    // If actual computernames were specified, then set the PSComputerName parameter.
                    if (gotComputerNames)
                    {
                        var computerNameParameter = new CommandParameter(Constants.ComputerName, computerNames);
                        childSpecification.Parameters[0].Add(computerNameParameter);
                    }

                    // Job objects will be disposed of on parent job removal.
                    var childJob = new PSWorkflowJob(_runtime, childSpecification);
                    childJob.JobMetadata = CreateJobMetadata(childJob, newJob.InstanceId, newJob.Id, newJob.Name, newJob.Command, computerNames);

                    childJob.LoadWorkflow(commandParameterCollection, activity, null);
                    this.AddJob(childJob);
                    newJob.AddChildJob(childJob);
                    StructuredTracer.ChildWorkflowJobAddition(childJob.InstanceId, newJob.InstanceId);
                    StructuredTracer.WorkflowJobCreated(newJob.InstanceId, childJob.InstanceId, childJob.WorkflowGuid);
                }
                else
                {
                    // Remove array of computerNames from collection.
                    parameterDictionary.Remove(Constants.ComputerName);

                    if (gotComputerNames)
                    {
                        foreach (var computerName in computerNames)
                        {
                            CreateChildJob(jobInvocationInfo, activity, newJob, commandParameterCollection, parameterDictionary, computerName, computerNames);
                        }
                    }
                    else
                    {
                        CreateChildJob(jobInvocationInfo, activity, newJob, commandParameterCollection, parameterDictionary, null, computerNames);
                    }
                }
            }

            StructuredTracer.JobCreationComplete(newJob.InstanceId, jobInvocationInfo.InstanceId);
            Tracer.TraceJob(newJob);

            return newJob;
        }
Пример #18
0
        /// <summary> Executes shell command.</summary>
        /// <param name="runspace"> The runspace.</param>
        /// <param name="command"> The command.</param>
        /// <param name="useDomainController"> True - if domain controller should be used.</param>
        /// <param name="errors"> Errors list.</param>
        /// <returns> The result.</returns>
        internal Collection<PSObject> ExecuteShellCommand(Runspace runspace, Command command, bool useDomainController, out object[] errors)
        {
            HostedSolutionLog.LogStart("ExecuteShellCommand");
            var errorList = new List<object>();

            if (useDomainController)
            {
                var dc = new CommandParameter("DomainController", PrimaryDomainController);
                if (!command.Parameters.Contains(dc))
                {
                    command.Parameters.Add(dc);
                }
            }

            HostedSolutionLog.DebugCommand(command);
            Collection<PSObject> results;
            Pipeline pipeLine = runspace.CreatePipeline();

            using (pipeLine)
            {
                pipeLine.Commands.Add(command);
                results = pipeLine.Invoke();

                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    foreach (object item in pipeLine.Error.ReadToEnd())
                    {
                        errorList.Add(item);
                        string errorMessage = string.Format("Invoke error: {0}", item);
                        HostedSolutionLog.LogWarning(errorMessage);
                    }
                }
            }

            errors = errorList.ToArray();
            HostedSolutionLog.LogEnd("ExecuteShellCommand");

            return results;
        }
Пример #19
0
 private object GetParameterValue(ParameterAst scriptParameter, CommandParameter parameter)
 {
     if (parameter != null)
     {
         return parameter.Value;
     }
     return GetDefaultParameterValue(scriptParameter);
 }
Пример #20
0
        public void RunScript()
        {
            InitializeSessionVars();
            PSAlert.ScriptName = scriptcommand.Replace(poshsecframework.Properties.Settings.Default.ScriptPath, "");
            if (scriptparams != null)
            {
                scriptparams.Clear();
            }
            Pipeline pline = null;
            bool cancelled = false;
            try
            {
                if (clicked)
                {
                    //Only run this if the user double clicked a script or command.
                    //If they typed the command then they should have passed params.
                    scriptparams = CheckForParams(rspace, scriptcommand);
                }
                if (!cancel)
                {
                    Command pscmd = new Command(scriptcommand);
                    String cmdparams = "";
                    if (scriptparams != null)
                    {
                        foreach (psparameter param in scriptparams)
                        {
                            CommandParameter prm = new CommandParameter(param.Name, param.Value ?? param.DefaultValue);
                            pscmd.Parameters.Add(prm);
                            cmdparams += " -" + param.Name + " " + param.Value;
                        }
                    }

                    pline = rspace.CreatePipeline();
                    if (iscommand)
                    {
                        String cmdscript = "Import-Module \"$PSFramework\"" + Environment.NewLine + scriptcommand + cmdparams;
                        if (clicked)
                        {
                            rslts.AppendLine(scriptcommand + cmdparams);
                        }
                        pline.Commands.AddScript(cmdscript);
                    }
                    else
                    {
                        rslts.AppendLine("Running script: " + scriptcommand.Replace(poshsecframework.Properties.Settings.Default.ScriptPath, ""));
                        pline.Commands.Add(pscmd);
                    }
                    Collection<PSObject> rslt = pline.Invoke();
                    pline.Dispose();
                    pline = null;
                    if (rslt != null)
                    {
                        foreach (PSObject po in rslt)
                        {
                            if (po != null)
                            {
                                rslts.AppendLine(po.ToString());
                            }
                        }
                    }
                }
                else
                {
                    rslts.AppendLine("Script cancelled by user.");
                }
            }
            catch (ThreadAbortException thde)
            {
                if (pline != null)
                {
                    pline.Stop();
                    pline.Dispose();
                    pline = null;
                }
                GC.Collect();
                cancelled = true;
                if (iscommand)
                {
                    rslts.AppendLine("Command cancelled by user." + Environment.NewLine + thde.Message);
                }
                else
                {
                    rslts.AppendLine("Script cancelled by user." + Environment.NewLine + thde.Message);
                }
            }
            catch (Exception e)
            {
                rslts.AppendLine(psexec.psexceptionhandler(e,iscommand));
            }
            finally
            {
                if (pline != null)
                {
                    pline.Dispose();
                }
                pline = null;
                GC.Collect();
                OnScriptComplete(new pseventargs(rslts.ToString(), scriptlvw, cancelled));
                rslts.Clear();
            }
        }
Пример #21
0
 private void BindVariable(ParameterAst scriptParameter, CommandParameter argument)
 {
     var value = GetParameterValue(scriptParameter, argument);
     _executionContext.SetVariable(scriptParameter.Name.VariablePath.UserPath, value);
 }
Пример #22
0
        internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors)
        {
            Log.WriteStart("ExecuteShellCommand");

            // 05.09.2015 [email protected]
            // New: Add LogInfo
            Log.WriteInfo("Command              : {0}", cmd.CommandText);
            foreach (var par in cmd.Parameters)
                Log.WriteInfo("Parameter            : Name {0}, Value {1}", par.Name, par.Value);
            Log.WriteInfo("UseDomainController  : {0}", useDomainController);

            List<object> errorList = new List<object>();

            if (useDomainController)
            {
                CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController);
                if (!cmd.Parameters.Contains(dc))
                {
                    cmd.Parameters.Add(dc);
                }
            }

            Collection<PSObject> results = null;
            // Create a pipeline
            Pipeline pipeLine = runSpace.CreatePipeline();
            using (pipeLine)
            {
                // Add the command
                pipeLine.Commands.Add(cmd);
                // Execute the pipeline and save the objects returned.
                results = pipeLine.Invoke();

                // Log out any errors in the pipeline execution
                // NOTE: These errors are NOT thrown as exceptions!
                // Be sure to check this to ensure that no errors
                // happened while executing the command.
                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    foreach (object item in pipeLine.Error.ReadToEnd())
                    {
                        errorList.Add(item);
                        string errorMessage = string.Format("Invoke error: {0}", item);
                        Log.WriteWarning(errorMessage);
                    }
                }
            }
            pipeLine = null;
            errors = errorList.ToArray();
            Log.WriteEnd("ExecuteShellCommand");
            return results;
        }
Пример #23
0
        private void DeserializeInvocationInfo(SerializationInfo info)
        {
            string command = info.GetString("InvocationInfo_Command");
            string name = info.GetString("InvocationInfo_Name");
            string moduleName = info.GetString("InvocationInfo_ModuleName");
            string adapterTypeName = info.GetString("InvocationInfo_AdapterTypeName");

            //
            // Parameters
            Dictionary<string, object> parameters = new Dictionary<string, object>();

            // ScriptBlock
            string script = info.GetString("InvocationParam_ScriptBlock");
            if (script != null)
            {
                parameters.Add(ScriptBlockParameter, ScriptBlock.Create(script));
            }

            // FilePath
            string filePath = info.GetString("InvocationParam_FilePath");
            if (!string.IsNullOrEmpty(filePath))
            {
                parameters.Add(FilePathParameter, filePath);
            }

            // InitializationScript
            script = info.GetString("InvocationParam_InitScript");
            if (!string.IsNullOrEmpty(script))
            {
                parameters.Add(InitializationScriptParameter, ScriptBlock.Create(script));
            }

            // RunAs32
            bool runAs32 = info.GetBoolean("InvocationParam_RunAs32");
            parameters.Add(RunAs32Parameter, runAs32);

            // Authentication
            AuthenticationMechanism authentication = (AuthenticationMechanism)info.GetValue("InvocationParam_Authentication",
                typeof(AuthenticationMechanism));
            parameters.Add(AuthenticationParameter, authentication);

            // ArgumentList
            object[] argList = (object[])info.GetValue("InvocationParam_ArgList", typeof(object[]));
            if (argList != null)
            {
                parameters.Add(ArgumentListParameter, argList);
            }

            JobDefinition jobDefinition = new JobDefinition(null, command, name);
            jobDefinition.ModuleName = moduleName;
            jobDefinition.JobSourceAdapterTypeName = adapterTypeName;

            // Convert to JobInvocationParameter collection
            CommandParameterCollection paramCollection = new CommandParameterCollection();
            foreach (KeyValuePair<string, object> param in parameters)
            {
                CommandParameter paramItem = new CommandParameter(param.Key, param.Value);
                paramCollection.Add(paramItem);
            }

            this.Definition = jobDefinition;
            this.Name = name;
            this.Command = command;
            this.Parameters.Add(paramCollection);
        }
Пример #24
0
		private void CreateChildJob(JobInvocationInfo specification, Activity activity, ContainerParentJob newJob, CommandParameterCollection commandParameterCollection, Dictionary<string, object> parameterDictionary, string computerName, string[] computerNames)
		{
			if (!string.IsNullOrEmpty(computerName))
			{
				string[] strArrays = new string[1];
				strArrays[0] = computerName;
				string[] strArrays1 = strArrays;
				parameterDictionary["PSComputerName"] = strArrays1;
			}
			JobInvocationInfo jobInvocationInfo = new JobInvocationInfo(specification.Definition, parameterDictionary);
			PSWorkflowJob pSWorkflowJob = new PSWorkflowJob(this._runtime, jobInvocationInfo);
			pSWorkflowJob.JobMetadata = PSWorkflowJobManager.CreateJobMetadata(pSWorkflowJob, newJob.InstanceId, newJob.Id, newJob.Name, newJob.Command, computerNames);
			int num = 0;
			while (num < commandParameterCollection.Count)
			{
				if (!string.Equals(commandParameterCollection[num].Name, "PSComputerName", StringComparison.OrdinalIgnoreCase))
				{
					num++;
				}
				else
				{
					commandParameterCollection.RemoveAt(num);
					break;
				}
			}
			if (!string.IsNullOrEmpty(computerName))
			{
				CommandParameter commandParameter = new CommandParameter("PSComputerName", computerName);
				commandParameterCollection.Add(commandParameter);
			}
			this.AddJob(pSWorkflowJob);
			pSWorkflowJob.LoadWorkflow(commandParameterCollection, activity, null);
			newJob.AddChildJob(pSWorkflowJob);
			PSWorkflowJobManager.StructuredTracer.ChildWorkflowJobAddition(pSWorkflowJob.InstanceId, newJob.InstanceId);
			PSWorkflowJobManager.Tracer.TraceJob(pSWorkflowJob);
			PSWorkflowJobManager.StructuredTracer.WorkflowJobCreated(newJob.InstanceId, pSWorkflowJob.InstanceId, pSWorkflowJob.WorkflowGuid);
		}
 public static void Add(this List<CommandParameter> target, string name, object value)
 {
     var parameter = new CommandParameter(name, value);
     target.Add(parameter);
 }
Пример #26
0
		internal ContainerParentJob CreateJob(JobInvocationInfo jobInvocationInfo, Activity activity)
		{
			object obj = null;
			if (jobInvocationInfo != null)
			{
				if (jobInvocationInfo.Definition != null)
				{
					if (jobInvocationInfo.Command != null)
					{
						DynamicActivity dynamicActivity = activity as DynamicActivity;
						object[] instanceId = new object[1];
						instanceId[0] = jobInvocationInfo.Definition.InstanceId;
						PSWorkflowJobManager.Tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Creating Workflow job with definition: {0}", instanceId));
						ContainerParentJob containerParentJob = new ContainerParentJob(jobInvocationInfo.Command, jobInvocationInfo.Name, "PSWorkflowJob");
						foreach (CommandParameterCollection commandParameterCollection in commandParameterCollection)
						{
							Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);
							IEnumerator<CommandParameter> enumerator = commandParameterCollection.GetEnumerator();
							using (enumerator)
							{
								while (enumerator.MoveNext())
								{
									CommandParameter commandParameter = commandParameterCollection;
									strs.Add(commandParameter.Name, commandParameter.Value);
								}
							}
							string[] strArrays = null;
							bool flag = false;
							if (strs.Count != 0 && strs.TryGetValue("PSComputerName", out obj) && LanguagePrimitives.TryConvertTo<string[]>(obj, CultureInfo.InvariantCulture, out strArrays))
							{
								flag = strArrays != null;
							}
							PSWorkflowJobManager.StructuredTracer.ParentJobCreated(containerParentJob.InstanceId);
							bool flag1 = false;
							if (dynamicActivity != null && dynamicActivity.Properties.Contains("PSComputerName"))
							{
								flag1 = true;
							}
							dynamicActivity = null;
							if (!flag1)
							{
								strs.Remove("PSComputerName");
								if (!flag)
								{
									this.CreateChildJob(jobInvocationInfo, activity, containerParentJob, commandParameterCollection, strs, null, strArrays);
								}
								else
								{
									string[] strArrays1 = strArrays;
									for (int i = 0; i < (int)strArrays1.Length; i++)
									{
										string str = strArrays1[i];
										this.CreateChildJob(jobInvocationInfo, activity, containerParentJob, commandParameterCollection, strs, str, strArrays);
									}
								}
							}
							else
							{
								JobInvocationInfo command = new JobInvocationInfo(jobInvocationInfo.Definition, strs);
								command.Command = containerParentJob.Command;
								if (flag)
								{
									CommandParameter commandParameter1 = new CommandParameter("PSComputerName", strArrays);
									command.Parameters[0].Add(commandParameter1);
								}
								PSWorkflowJob pSWorkflowJob = new PSWorkflowJob(this._runtime, command);
								pSWorkflowJob.JobMetadata = PSWorkflowJobManager.CreateJobMetadata(pSWorkflowJob, containerParentJob.InstanceId, containerParentJob.Id, containerParentJob.Name, containerParentJob.Command, strArrays);
								pSWorkflowJob.LoadWorkflow(commandParameterCollection, activity, null);
								this.AddJob(pSWorkflowJob);
								containerParentJob.AddChildJob(pSWorkflowJob);
								PSWorkflowJobManager.StructuredTracer.ChildWorkflowJobAddition(pSWorkflowJob.InstanceId, containerParentJob.InstanceId);
								PSWorkflowJobManager.StructuredTracer.WorkflowJobCreated(containerParentJob.InstanceId, pSWorkflowJob.InstanceId, pSWorkflowJob.WorkflowGuid);
							}
						}
						PSWorkflowJobManager.StructuredTracer.JobCreationComplete(containerParentJob.InstanceId, jobInvocationInfo.InstanceId);
						PSWorkflowJobManager.Tracer.TraceJob(containerParentJob);
						PSSQMAPI.InitiateWorkflowStateDataTracking(containerParentJob);
						return containerParentJob;
					}
					else
					{
						throw new ArgumentException(Resources.NewJobDefinitionNull, "jobInvocationInfo");
					}
				}
				else
				{
					throw new ArgumentException(Resources.NewJobDefinitionNull, "jobInvocationInfo");
				}
			}
			else
			{
				throw new ArgumentNullException("jobInvocationInfo");
			}
		}
        internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors)
        {
            HostedSolutionLog.LogStart("ExecuteShellCommand");
            List<object> errorList = new List<object>();

            if (useDomainController)
            {
                CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController);
                if (!cmd.Parameters.Contains(dc))
                {
                    cmd.Parameters.Add(dc);
                }
            }

            HostedSolutionLog.DebugCommand(cmd);
            Collection<PSObject> results = null;
            // Create a pipeline
            Pipeline pipeLine = runSpace.CreatePipeline();
            using (pipeLine)
            {
                // Add the command
                pipeLine.Commands.Add(cmd);
                // Execute the pipeline and save the objects returned.
                results = pipeLine.Invoke();

                // Log out any errors in the pipeline execution
                // NOTE: These errors are NOT thrown as exceptions! 
                // Be sure to check this to ensure that no errors 
                // happened while executing the command.
                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    foreach (object item in pipeLine.Error.ReadToEnd())
                    {
                        errorList.Add(item);
                        string errorMessage = string.Format("Invoke error: {0}", item);
                        HostedSolutionLog.LogWarning(errorMessage);
                    }
                }
            }
            pipeLine = null;
            errors = errorList.ToArray();
            HostedSolutionLog.LogEnd("ExecuteShellCommand");
            return results;
        }
Пример #28
0
		internal PSWorkflowJob CreateJobInternal(Guid jobInstanceId, Activity workflow, string command, string name, Dictionary<string, object> parameters, string xaml)
		{
			object obj = null;
			PSWorkflowJob pSWorkflowJob;
			if (jobInstanceId != Guid.Empty)
			{
				if (workflow != null)
				{
					if (command != null)
					{
						if (name != null)
						{
							if (!this._wfJobTable.ContainsKey(jobInstanceId))
							{
								lock (this.lockObjects.GetLockObject(jobInstanceId))
								{
									if (!this._wfJobTable.ContainsKey(jobInstanceId))
									{
										JobDefinition jobDefinition = new JobDefinition(typeof(WorkflowJobSourceAdapter), command, name);
										Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);
										if (parameters != null)
										{
											foreach (KeyValuePair<string, object> parameter in parameters)
											{
												strs.Add(parameter.Key, parameter.Value);
											}
										}
										string[] strArrays = null;
										bool flag = false;
										if (strs.Count != 0 && strs.TryGetValue("PSComputerName", out obj) && LanguagePrimitives.TryConvertTo<string[]>(obj, CultureInfo.InvariantCulture, out strArrays))
										{
											flag = strArrays != null;
										}
										if (flag)
										{
											if ((int)strArrays.Length <= 1)
											{
												strs.Remove("PSComputerName");
											}
											else
											{
												throw new ArgumentException(Resources.OneComputerNameAllowed);
											}
										}
										JobInvocationInfo jobInvocationInfo = new JobInvocationInfo(jobDefinition, strs);
										jobInvocationInfo.Command = command;
										if (flag)
										{
											CommandParameter commandParameter = new CommandParameter("PSComputerName", strArrays);
											jobInvocationInfo.Parameters[0].Add(commandParameter);
										}
										PSWorkflowJob pSWorkflowJob1 = new PSWorkflowJob(this._runtime, jobInvocationInfo, jobInstanceId);
										pSWorkflowJob1.JobMetadata = PSWorkflowJobManager.CreateJobMetadataWithNoParentDefined(pSWorkflowJob1, strArrays);
										pSWorkflowJob1.LoadWorkflow(jobInvocationInfo.Parameters[0], workflow, xaml);
										this.AddJob(pSWorkflowJob1);
										pSWorkflowJob = pSWorkflowJob1;
									}
									else
									{
										ArgumentException argumentException = new ArgumentException(Resources.DuplicateInstanceId);
										PSWorkflowJobManager.Tracer.TraceException(argumentException);
										throw argumentException;
									}
								}
								return pSWorkflowJob;
							}
							else
							{
								ArgumentException argumentException1 = new ArgumentException(Resources.DuplicateInstanceId);
								PSWorkflowJobManager.Tracer.TraceException(argumentException1);
								throw argumentException1;
							}
						}
						else
						{
							throw new ArgumentNullException("name");
						}
					}
					else
					{
						throw new ArgumentNullException("command");
					}
				}
				else
				{
					throw new ArgumentNullException("workflow");
				}
			}
			else
			{
				throw new ArgumentNullException("jobInstanceId");
			}
		}