/// <summary> /// Opens the file using <see cref="AsOpenFile"/> or the default method. /// </summary> /// <param name="file">The file to be opened.</param> public sealed override void UIOpenFile(FarFile file) { if (file == null) { return; } // lookup closer? if (UserWants == UserAction.Enter && Lookup != null) { Lookup.Invoke(this, new OpenFileEventArgs(file)); UIEscape(false); return; } // script if (AsOpenFile != null) { AsOpenFile.InvokeReturnAsIs(this, new OpenFileEventArgs(file)); return; } // base if (Explorer.CanOpenFile) { base.UIOpenFile(file); return; } // PSF OpenFile(file); }
/// <summary> /// Adds the object to the queue unless it is filtered out. /// Callers check the maximum queue count. /// </summary> void Enqueue(PSObject value) { // filter if (Filter != null) { if (_FilterHash != null) { if (_FilterHash.Contains(value.BaseObject)) { return; } _FilterHash.Add(value, null); } else { if (!LanguagePrimitives.IsTrue(_FilterScript.InvokeReturnAsIs(value))) { return; } } } // enqueue _queue.Enqueue(value); // update info ++_infoItemCount; if (_infoMaxQueue < _queue.Count) { _infoMaxQueue = _queue.Count; } }
private static bool?InvokeScriptBlock(ScriptBlock script_block, params object[] args) { if (script_block.InvokeReturnAsIs(args) is PSObject result && result.BaseObject is bool b) { return(b); } return(null); }
/// <summary> /// Invokes the handler-like script and returns the result as it is. /// </summary> /// <param name="script">The script block to invoke.</param> /// <param name="args">Script arguments.</param> internal static object InvokeScriptReturnAsIs(ScriptBlock script, params object[] args) { if (Runspace.DefaultRunspace == null) { Runspace.DefaultRunspace = Psf.Runspace; } return(script.InvokeReturnAsIs(args)); }
/// <summary> /// Invokes the action. /// </summary> /// <param name="sender">The sender.</param> public void Invoke(T sender) { if (_action != null) { _action(sender); } else if (_script != null) { _script.InvokeReturnAsIs(sender); } }
/// <summary> /// Invokes the handler. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The arguments.</param> public void Invoke(object sender, T args) { if (_handler != null) { _handler(sender, args); } else if (_script != null) { _script.InvokeReturnAsIs(sender, args); } }
/// <include file='doc.xml' path='doc/ScriptFork/*'/> /// <param name="file">The file to view.</param> public sealed override void UIViewFile(FarFile file) //_091202_073429 { if (AsViewFile != null) { AsViewFile.InvokeReturnAsIs(this, file); } else { DoViewFile(file); } }
/// <include file='doc.xml' path='doc/ScriptFork/*'/> /// <param name="file">The file to edit.</param> public sealed override void UIEditFile(FarFile file) //_091202_073429 NB: Data can be wrapped by PSObject. { if (AsEditFile != null) { AsEditFile.InvokeReturnAsIs(this, file); } else { DoEditFile(file); } }
/// <summary> /// Gets a meta value. /// </summary> /// <param name="value">The input object.</param> public object GetValue(object value) { if (_Script != null) { //! _100410_051915 Use module session state otherwise $_ is not visible, only $global:_ is visible var session = _Script.Module == null ? A.Psf.Engine.SessionState : _Script.Module.SessionState; session.PSVariable.Set("_", value); //??? suppress for now // ps: .{ls; ps} | op // -- this with fail on processes with file scripts try { object result = _Script.InvokeReturnAsIs(); if (result == null) { return(null); } else { return(((PSObject)result).BaseObject); } } catch (RuntimeException) { return(null); } finally { //! Null $_ to avoid a leak session.PSVariable.Set("_", null); } } PSObject pso = PSObject.AsPSObject(value); PSPropertyInfo pi = pso.Properties[_Property]; if (pi == null) { return(null); } // Exception case: cert provider, search all try { return(pi.Value); } catch (RuntimeException e) { FarNet.Log.TraceException(e); return(null); } }
protected override void ProcessRecord() { try { if (Body == null) { return; } // Evalute type pre-condition if (Type != null) { var comparer = PipelineContext.CurrentThread.Baseline.GetTargetBinding().IgnoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; if (!Type.Contains(value: PipelineContext.CurrentThread.RuleRecord.TargetType, comparer: comparer)) { PipelineContext.CurrentThread.Logger.DebugMessage("Target failed Type precondition"); return; } } // Evaluate script pre-condition if (If != null) { PipelineContext.CurrentThread.ExecutionScope = ExecutionScope.Precondition; var ifResult = If.InvokeReturnAsIs() as PSObject; if (ifResult == null || !(ifResult.BaseObject is bool) || !(bool)ifResult.BaseObject) { PipelineContext.CurrentThread.Logger.DebugMessage("Target failed If precondition"); return; } } // Evaluate script block PipelineContext.CurrentThread.ExecutionScope = ExecutionScope.Condition; var invokeResult = RuleConditionResult.Create(Body.Invoke()); WriteObject(invokeResult); } finally { PipelineContext.CurrentThread.ExecutionScope = ExecutionScope.None; } }
protected override void ProcessRecord() { string filePath = this.GetFilePath(); if (filePath != null) { if (!File.Exists(filePath)) { InvalidOperationException exception = PSTraceSource.NewInvalidOperationException("ImportLocalizedData", "FileNotExist", new object[] { filePath }); base.WriteError(new ErrorRecord(exception, "ImportLocalizedData", ErrorCategory.ObjectNotFound, filePath)); } else { string script = this.GetScript(filePath); if (script != null) { try { object obj2; ScriptBlock block = base.Context.Engine.ParseScriptBlock(script, false); block.CheckRestrictedLanguage(this.SupportedCommand, null, false); PSLanguageMode languageMode = base.Context.LanguageMode; base.Context.LanguageMode = PSLanguageMode.RestrictedLanguage; try { obj2 = block.InvokeReturnAsIs(new object[0]); if (obj2 == AutomationNull.Value) { obj2 = null; } } finally { base.Context.LanguageMode = languageMode; } if (this._bindingVariable != null) { VariablePath variablePath = new VariablePath(this._bindingVariable); if (variablePath.IsUnscopedVariable) { variablePath = variablePath.CloneAndSetLocal(); } if (string.IsNullOrEmpty(variablePath.UnqualifiedPath)) { InvalidOperationException exception2 = PSTraceSource.NewInvalidOperationException("ImportLocalizedData", "IncorrectVariableName", new object[] { this._bindingVariable }); base.WriteError(new ErrorRecord(exception2, "ImportLocalizedData", ErrorCategory.InvalidArgument, this._bindingVariable)); } else { SessionStateScope scope = null; PSVariable variableItem = base.SessionState.Internal.GetVariableItem(variablePath, out scope); if (variableItem == null) { variableItem = new PSVariable(variablePath.UnqualifiedPath, obj2, ScopedItemOptions.None); base.Context.EngineSessionState.SetVariable(variablePath, variableItem, false, CommandOrigin.Internal); } else { variableItem.Value = obj2; } } } else { base.WriteObject(obj2); } } catch (RuntimeException exception3) { throw PSTraceSource.NewInvalidOperationException(exception3, "ImportLocalizedData", "ErrorLoadingDataFile", new object[] { filePath, exception3.Message }); } } } } }
void Fail(object message = null, int conditionIndex = 0) { // break a macro MacroState macroState = Far.Api.MacroState; if (macroState == MacroState.Executing || macroState == MacroState.ExecutingCommon) { Far.Api.UI.Break(); } // get the message if (message == null) { ScriptBlock messageScript = Cast <ScriptBlock> .From(Message); if (messageScript != null) { try { Message = messageScript.InvokeReturnAsIs(); } catch (RuntimeException ex) { Message = "Error in the message script: " + ex.Message; Title = null; } } } else { Message = message; } // body //! use "\n" as the separator, not "\r": PositionMessage starts with "\n". string body = Message == null ? "Assertion failed" : Message.ToString(); if (IsError) { if (conditionIndex > 0) { body = string.Concat(body, (body.Length > 0 ? "\n" : string.Empty), "Condition #", conditionIndex + 1); } //! Trim() for PowerShell 2.0 body = string.Concat(body, (body.Length > 0 ? "\n" : string.Empty), MyInvocation.PositionMessage.Trim()); } // buttons string[] buttons; if (!IsError) { buttons = new string[] { BtnBreak, BtnThrow } } ; else if (string.IsNullOrEmpty(MyInvocation.ScriptName)) { buttons = new string[] { BtnBreak, BtnThrow, BtnDebug } } ; else { buttons = new string[] { BtnBreak, BtnThrow, BtnDebug, BtnEdit } }; // prompt for (; ;) { int result = Far.Api.Message( body, Title ?? MyName, IsError ? (MessageOptions.Warning | MessageOptions.LeftAligned) : MessageOptions.None, buttons); if (result < 0) { continue; } switch (buttons[result]) { case BtnBreak: { throw new PipelineStoppedException(); } case BtnThrow: { throw new PSInvalidOperationException(body); } case BtnDebug: { A.InvokeCode("Set-PSBreakpoint -Variable daf01ff6-f004-43bd-b6bf-cf481e9333d3 -Mode Read"); SessionState.PSVariable.Set("daf01ff6-f004-43bd-b6bf-cf481e9333d3", null); GetVariableValue("daf01ff6-f004-43bd-b6bf-cf481e9333d3"); return; } case BtnEdit: { IEditor editor = Far.Api.CreateEditor(); editor.FileName = MyInvocation.ScriptName; editor.GoToLine(MyInvocation.ScriptLineNumber - 1); editor.Open(); goto case BtnBreak; } } } } const string BtnBreak = "&Break", BtnThrow = "&Throw", BtnDebug = "&Debug", BtnEdit = "&Edit"; }
void runSBEvent(ScriptBlock sb, AutomationElement src, AutomationEventArgs e) { // inform the Wait-UiaEventRaised cmdlet SaveEventInput( src, e, e.EventId.ProgrammaticName, true); // try { // CurrentData.LastEventSource = src; // as AutomationElement; // CurrentData.LastEventArgs = e; // as AutomationEventArgs; // CurrentData.LastEventType = e.EventId.ProgrammaticName; // CurrentData.LastEventInfoAdded = true; // } // catch { // //WriteVerbose(this, "failed to register an event in the collection"); // } // 20120206 Collection<PSObject> psObjects = null; try { Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace(); try { Runspace.DefaultRunspace.Open(); } catch (Exception e1) { // 20130318 // ErrorRecord err = // new ErrorRecord(e1, // "ErrorOnOpeningRunspace", // ErrorCategory.InvalidOperation, // sb); // err.ErrorDetails = // new ErrorDetails( // "Unable to run a scriptblock:\r\n" + // sb.ToString()); // WriteError(this, err, false); WriteError( this, "Unable to run a scriptblock:\r\n" + sb + "." + e1.Message, "ErrorOnOpeningRunspace", ErrorCategory.InvalidOperation, // 20130318 //false); true); } try { var inputParams = new List <object>(); inputParams.Add(src); inputParams.Add(e); object[] inputParamsArray = inputParams.ToArray(); // psObjects = sb.InvokeReturnAsIs(inputParamsArray); // sb.Invoke(inputParamsArray); } catch (Exception e2) { // 20130318 // ErrorRecord err = // new ErrorRecord(e2, // "ErrorInOpenedRunspace", // ErrorCategory.InvalidOperation, // sb); // err.ErrorDetails = // new ErrorDetails("Unable to run a scriptblock"); // WriteError(this, err, true); WriteError( this, "Unable to run a scriptblock." + e2.Message, "ErrorInOpenedRunspace", ErrorCategory.InvalidOperation, true); } // psObjects = // sb.Invoke(); } catch (Exception eOuter) { // 20130318 // ErrorRecord err = // new ErrorRecord(eOuter, // "ErrorInInvokingScriptBlock", //"ErrorinCreatingRunspace", // ErrorCategory.InvalidOperation, // System.Management.Automation.Runspaces.Runspace.DefaultRunspace); // err.ErrorDetails = // new ErrorDetails("Unable to issue the following command:\r\n" + // "System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();" + // "\r\nException raised is\r\n" + // eOuter.Message); WriteError( this, "Unable to issue the following command:\r\n" + "System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();" + "\r\nException raised is\r\n" + eOuter.Message, "ErrorInInvokingScriptBlock", ErrorCategory.InvalidOperation, true); } }
internal object GetValue(object value) { using (new SetDollar(_Cmdlet.SessionState, value)) return(_ScriptBlock.InvokeReturnAsIs()); }