private async Task <bool> PerformPowershellAsync(string command, bool importNavContainerHelper) { if (asyncScript.InvocationStateInfo.State == PSInvocationState.Running) { ErrorCallback?.Invoke(this, Resources.GlobalRessources.ErrorWaitForPreviousTask); return(false); } StringBuilder sb = new StringBuilder(); if (importNavContainerHelper) { sb.AppendLine("import-module navcontainerhelper"); } sb.AppendLine(command); asyncScript.Commands.Clear(); asyncScript.AddScript(sb.ToString()); SendCommandToLog(command); pso.Clear(); var result = asyncScript.BeginInvoke <PSObject, PSObject>(null, pso); await Task.Factory.FromAsync(result, x => { }); if (asyncScript.HadErrors) { ErrorCallback?.Invoke(this, GlobalRessources.ErrorScriptCompletedWithError); } InitializePSO(); EndScriptCallback?.Invoke(this, null); return(true); }
public void ProgressDataAdded(Object sender, DataAddedEventArgs e) { PSDataCollection <ProgressRecord> dc = asyncScript.Streams.Progress; foreach (ProgressRecord progress in dc) { MessageCallback?.Invoke(this, progress.StatusDescription); } dc.Clear(); }
public void MessageDataAdded(Object sender, DataAddedEventArgs e) { PSDataCollection <InformationRecord> informations = (PSDataCollection <InformationRecord>)sender; foreach (InformationRecord information in informations) { MessageCallback?.Invoke(this, information.ToString()); } informations.Clear(); }
public void ErrorDataAdded(Object sender, DataAddedEventArgs e) { PSDataCollection <ErrorRecord> dc = asyncScript.Streams.Error; foreach (ErrorRecord error in dc) { ErrorCallback?.Invoke(this, error.Exception.Message); } dc.Clear(); }
public void ProgressDataAdded(Object sender, DataAddedEventArgs e) { PSDataCollection <ProgressRecord> dc = asyncScript.Streams.Progress; for (int i = 0; i < dc.Count; i++) { MessageCallback?.Invoke(this, dc[i].StatusDescription); } dc.Clear(); }
public void PSODataAdded(Object sender, DataAddedEventArgs e) { PSDataCollection <PSObject> informations = (PSDataCollection <PSObject>)sender; for (int i = 0; i < informations.Count; i++) { MessageCallback?.Invoke(this, informations[i].ToString()); } informations.Clear(); }
public void ErrorDataAdded(Object sender, DataAddedEventArgs e) { PSDataCollection <ErrorRecord> dc = asyncScript.Streams.Error; for (int i = 0; i < dc.Count; i++) { ErrorCallback?.Invoke(this, dc[i].Exception.Message); } dc.Clear(); }
/// <summary> /// Execution of PowerShell value activity. /// PowerShell expression will be evaluated using PowerShell runspace and the value of Type T will be returned. /// </summary> /// <param name="context"></param> protected override void Execute(NativeActivityContext context) { Token[] tokens; ParseError[] errors; ScriptBlockAst exprAst = Parser.ParseInput(Expression, out tokens, out errors); bool hasErrorActionPreference = false; bool hasWarningPreference = false; bool hasInformationPreference = false; // Custom activity participant tracker for updating debugger with current variables and sequence stop points. // Regex looks for debugger sequence points like: Expression="'3:5:WFFunc1'". // We specifically disallow TimeSpan values that look like sequence points: Expression="'00:00:01'". bool isDebugSequencePoint = (!string.IsNullOrEmpty(Expression) && (System.Text.RegularExpressions.Regex.IsMatch(Expression, @"^'\d+:\d+:\S+'$")) && (typeof(T) != typeof(System.TimeSpan))); var dataProperties = context.DataContext.GetProperties(); if (isDebugSequencePoint || (dataProperties.Count > 0)) { System.Activities.Tracking.CustomTrackingRecord customRecord = new System.Activities.Tracking.CustomTrackingRecord("PSWorkflowCustomUpdateDebugVariablesTrackingRecord"); foreach (System.ComponentModel.PropertyDescriptor property in dataProperties) { if (String.Equals(property.Name, "ParameterDefaults", StringComparison.OrdinalIgnoreCase)) { continue; } Object value = property.GetValue(context.DataContext); if (value != null) { object tempValue = value; PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>; if (collectionObject != null && collectionObject.Count == 1) { tempValue = collectionObject[0]; } customRecord.Data.Add(property.Name, tempValue); } } if (isDebugSequencePoint) { customRecord.Data.Add("DebugSequencePoint", Expression); } context.Track(customRecord); } if (tokens != null) { foreach (Token token in tokens) { VariableToken variable = token as VariableToken; if (variable != null) { if (variable.Name.Equals("ErrorActionPreference", StringComparison.OrdinalIgnoreCase)) { hasErrorActionPreference = true; } else if (variable.Name.Equals("WarningPreference", StringComparison.OrdinalIgnoreCase)) { hasWarningPreference = true; } else if (variable.Name.Equals("InformationPreference", StringComparison.OrdinalIgnoreCase)) { hasInformationPreference = true; } } } } if (string.IsNullOrEmpty(Expression)) { throw new ArgumentException(ActivityResources.NullArgumentExpression); } if (_ci == null) { lock (syncroot) { // Invoke using the CommandInfo for Invoke-Command directly, rather than going through // command discovery (which is very slow). if (_ci == null) { _ci = new CmdletInfo("Invoke-Command", typeof(Microsoft.PowerShell.Commands.InvokeCommandCommand)); } } } Collection <PSObject> returnedvalue; Runspace runspace = null; bool borrowedRunspace = false; PSWorkflowHost workflowHost = null; if (typeof(ScriptBlock).IsAssignableFrom(typeof(T))) { Result.Set(context, ScriptBlock.Create(Expression)); return; } else if (typeof(ScriptBlock[]).IsAssignableFrom(typeof(T))) { Result.Set(context, new ScriptBlock[] { ScriptBlock.Create(Expression) }); return; } PropertyDescriptorCollection col = context.DataContext.GetProperties(); HostParameterDefaults hostValues = context.GetExtension <HostParameterDefaults>(); // Borrow a runspace from the host if we're not trying to create a ScriptBlock. // If we are trying to create one, we need to keep it around so that it can be // invoked multiple times. if (hostValues != null) { workflowHost = hostValues.Runtime; try { runspace = workflowHost.UnboundedLocalRunspaceProvider.GetRunspace(null, 0, 0); borrowedRunspace = true; } catch (Exception) { // it is fine to catch generic exception here // if the local runspace provider does not give us // a runspace we will create one locally (fallback) } } if (runspace == null) { // Not running with the PowerShell workflow host so directly create the runspace... runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); runspace.Open(); } using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { try { ps.Runspace = runspace; // Subscribe to DataAdding on the error stream so that we can add position tracking information if (hostValues != null) { HostSettingCommandMetadata sourceCommandMetadata = hostValues.HostCommandMetadata; CommandMetadataTable.TryAdd(ps.InstanceId, sourceCommandMetadata); ps.Streams.Error.DataAdding += HandleErrorDataAdding; } // First, set the variables from the host defaults if ((hostValues != null) && (hostValues.Parameters != null)) { if (hostValues.Parameters.ContainsKey("PSCurrentDirectory")) { string path = hostValues.Parameters["PSCurrentDirectory"] as string; if (path != null) { ps.Runspace.SessionStateProxy.Path.SetLocation(path); } } foreach (string hostDefault in hostValues.Parameters.Keys) { string mappedHostDefault = hostDefault; if (hostDefault.Equals("ErrorAction", StringComparison.OrdinalIgnoreCase)) { if (hasErrorActionPreference) { mappedHostDefault = "ErrorActionPreference"; } else { continue; } } else if (hostDefault.Equals("WarningAction", StringComparison.OrdinalIgnoreCase)) { if (hasWarningPreference) { mappedHostDefault = "WarningPreference"; } else { continue; } } else if (hostDefault.Equals("InformationAction", StringComparison.OrdinalIgnoreCase)) { if (hasInformationPreference) { mappedHostDefault = "InformationPreference"; } else { continue; } } object propertyValue = hostValues.Parameters[hostDefault]; if (propertyValue != null) { ps.Runspace.SessionStateProxy.PSVariable.Set(mappedHostDefault, propertyValue); } } } // Then, set the variables from the workflow foreach (PropertyDescriptor p in col) { string name = p.Name; object value = p.GetValue(context.DataContext); if (value != null) { object tempValue = value; PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>; if (collectionObject != null && collectionObject.Count == 1) { tempValue = collectionObject[0]; } ps.Runspace.SessionStateProxy.PSVariable.Set(name, tempValue); } } ps.AddCommand(_ci).AddParameter("NoNewScope").AddParameter("ScriptBlock", ExpressionScriptBlock); // If this needs to consume input, take it from the host stream. PSDataCollection <PSObject> inputStream = null; if (UseDefaultInput) { // Retrieve our host overrides hostValues = context.GetExtension <HostParameterDefaults>(); if (hostValues != null) { Dictionary <string, object> incomingArguments = hostValues.Parameters; if (incomingArguments.ContainsKey("Input")) { inputStream = incomingArguments["Input"] as PSDataCollection <PSObject>; } } } // Now invoke the pipeline try { if (inputStream != null) { returnedvalue = ps.Invoke(inputStream); inputStream.Clear(); } else { returnedvalue = ps.Invoke(); } } catch (CmdletInvocationException cie) { if (cie.ErrorRecord != null && cie.ErrorRecord.Exception != null) { throw cie.InnerException; } else { throw; } } } finally { if (hostValues != null) { ps.Streams.Error.DataAdding -= HandleErrorDataAdding; HostSettingCommandMetadata removedValue; CommandMetadataTable.TryRemove(ps.InstanceId, out removedValue); } if (borrowedRunspace) { workflowHost.UnboundedLocalRunspaceProvider.ReleaseRunspace(runspace); } else { // This will be disposed when the command is done with it. runspace.Dispose(); runspace = null; } } if (ps.Streams.Error != null && ps.Streams.Error.Count > 0) { PSDataCollection <ErrorRecord> errorStream = null; // Retrieve our host overrides hostValues = context.GetExtension <HostParameterDefaults>(); if (hostValues != null) { Dictionary <string, object> incomingArguments = hostValues.Parameters; if (incomingArguments.ContainsKey("PSError")) { errorStream = incomingArguments["PSError"] as PSDataCollection <ErrorRecord>; } } if (errorStream != null && errorStream.IsOpen) { foreach (ErrorRecord record in ps.Streams.Error) { errorStream.Add(record); } } } T valueToReturn = default(T); if (returnedvalue != null && returnedvalue.Count > 0) { try { if (returnedvalue.Count == 1) { if (returnedvalue[0] != null) { Object result = returnedvalue[0]; Object baseObject = ((PSObject)result).BaseObject; if (!(baseObject is PSCustomObject)) { result = baseObject; } // Try regular PowerShell conversion valueToReturn = LanguagePrimitives.ConvertTo <T>(result); } } else { valueToReturn = LanguagePrimitives.ConvertTo <T>(returnedvalue); } } catch (PSInvalidCastException) { // Handle the special case of emitting a PSDataCollection - use its array constructor. // This special case is why we aren't using PowerShell.Invoke<T> if (typeof(T) == typeof(PSDataCollection <PSObject>)) { Object tempValueToReturn = new PSDataCollection <PSObject>( new List <PSObject> { LanguagePrimitives.ConvertTo <PSObject>(returnedvalue[0]) }); valueToReturn = (T)tempValueToReturn; } else { throw; } } Result.Set(context, valueToReturn); } } }
PutExportEntriesResults IMAExtensible2CallExport.PutExportEntries(IList <CSEntryChange> csentries) { Tracer.Enter("putexportentries"); Tracer.Indent(); PutExportEntriesResults exportEntries = new PutExportEntriesResults(); PSDataCollection <PSObject> exportPipeline = new PSDataCollection <PSObject>(); try { Command cmd = new Command(Path.GetFullPath(ExportScript)); cmd.Parameters.Add(new CommandParameter("User", Username)); cmd.Parameters.Add(new CommandParameter("Password", Password)); cmd.Parameters.Add(new CommandParameter("Credentials", GetSecureCredentials())); cmd.Parameters.Add(new CommandParameter("ExportType", exportType)); foreach (CSEntryChange csentryChange in csentries) { Tracer.TraceInformation("adding-object id: {0}, dn: '{1}' [{2}]", csentryChange.Identifier, csentryChange.DN, csentryChange.ObjectModificationType); if (ExportSimpleObjects) { // http://karlprosser.com/coder/2008/06/12/generating-a-propertybag-aka-pscustomobject-in-c/ // creating a PSobject without any parameters in the constructor creates a PSCustomObject PSObject obj = new PSObject(); // PSNoteProperties are not strongly typed but do contain an explicit type. obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.Identifier, csentryChange.Identifier.ToString())); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.Anchor, csentryChange.AnchorAttributes.Count > 0 ? csentryChange.AnchorAttributes.FirstOrDefault().Value : "")); obj.Properties.Add(new PSAliasProperty(Constants.ControlValues.IdentifierAsGuid, csentryChange.Identifier.ToString(), typeof(Guid))); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.ObjectModificationType, csentryChange.ObjectModificationType.ToString())); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.ObjectType, csentryChange.ObjectType)); List <string> attrs = schema.Types[csentryChange.ObjectType].Attributes.Select(a => a.Name).ToList <string>(); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.AttributeNames, attrs)); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.ChangedAttributeNames, csentryChange.ChangedAttributeNames == null ? new List <string>() : csentryChange.ChangedAttributeNames)); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.DN, csentryChange.DN)); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.RDN, csentryChange.RDN)); foreach (AttributeChange ac in csentryChange.AttributeChanges) { if (!ac.IsMultiValued) { foreach (ValueChange vc in ac.ValueChanges) { obj.Properties.Add(new PSNoteProperty(string.Format("{0}", ac.Name), vc.Value)); } } else { List <object> values = new List <object>(); foreach (ValueChange vc in ac.ValueChanges) { values.Add(vc.Value); } obj.Properties.Add(new PSNoteProperty(string.Format("{0}", ac.Name), values.ToArray())); } } exportPipeline.Add(obj); } else { exportPipeline.Add(new PSObject(csentryChange)); } } exportResults = InvokePowerShellScript(cmd, exportPipeline); if (exportResults != null) { foreach (PSObject result in exportResults) { if (result.BaseObject.GetType() != typeof(System.Collections.Hashtable)) { continue; } Hashtable hashTable = (Hashtable)result.BaseObject; string ErrorName = "unspecified-error"; string ErrorDetail = "No details specified"; Guid identifier = new Guid(); // get anchor attribute changes List <AttributeChange> attrchanges = new List <AttributeChange>(); foreach (string key in hashTable.Keys) { if (key.Equals(Constants.ControlValues.Identifier, StringComparison.OrdinalIgnoreCase)) { try { identifier = new Guid(hashTable[key].ToString()); Tracer.TraceInformation("got-identifier {0}, {1}", identifier, key); } catch (FormatException fex) { Tracer.TraceError("identifier-format-error '{0}'", fex.ToString()); } continue; } if (key.Equals(Constants.ControlValues.ErrorName, StringComparison.OrdinalIgnoreCase)) { ErrorName = hashTable[key].ToString(); Tracer.TraceInformation("got-errorname {0}, {1}", ErrorName, key); continue; } if (key.Equals(Constants.ControlValues.ErrorDetail, StringComparison.OrdinalIgnoreCase)) { ErrorDetail = hashTable[key].ToString(); Tracer.TraceInformation("got-errordetail {0}, {1}", ErrorDetail, key); continue; } if (!(Regex.IsMatch(key, @"^\[.+\]$", RegexOptions.IgnoreCase))) { Tracer.TraceInformation("got-attribute-change {0}: '{1}'", key, hashTable[key]); attrchanges.Add(AttributeChange.CreateAttributeAdd(key, hashTable[key])); continue; } } if (string.IsNullOrEmpty(ErrorName) || ErrorName.Equals("success", StringComparison.OrdinalIgnoreCase)) { Tracer.TraceInformation("returning-success id: {0}", identifier); CSEntryChangeResult cschangeresult = CSEntryChangeResult.Create(identifier, attrchanges, MAExportError.Success); exportEntries.CSEntryChangeResults.Add(cschangeresult); } else { Tracer.TraceInformation("returning-error id: {0}, name: {1}, details: {2}", identifier, ErrorName, ErrorDetail); CSEntryChangeResult cschangeresult = CSEntryChangeResult.Create(identifier, attrchanges, MAExportError.ExportErrorCustomContinueRun, ErrorName, ErrorDetail); exportEntries.CSEntryChangeResults.Add(cschangeresult); } } } exportPipeline.Clear(); exportResults.Clear(); exportResults = null; return(exportEntries); } catch (Exception ex) { Tracer.TraceError("putexportentries", ex); throw; } finally { Tracer.Unindent(); Tracer.Exit("putexportentries"); } }