/// <summary> /// Parses a string input into one or multiple alias expressions. /// </summary> /// <param name="StringValue">the string to parse</param> public SelectScriptMethodParameter(string StringValue) { InputObject = StringValue; foreach (string value in StringValue.Split(',')) { if (!Regex.IsMatch(value, " => ", RegexOptions.IgnoreCase)) { throw new ArgumentException(String.Format("Invalid input string, could not evaluate '{0}' as scriptmethod", value)); } Match match = Regex.Match(value, "^(.*?) => (.*?)$", RegexOptions.IgnoreCase); Value[match.Groups[1].Value.Trim()] = ScriptBlock.Create(match.Groups[2].Value.Trim()); } }
public void CtorWithTwoParamsSavesArgs() { // Arrange. const string name = "test name"; var testScript = ScriptBlock.Create(""); // Act. var res = new Test(name, testScript); // Assert. Assert.AreEqual(name, res.Name); Assert.AreEqual(testScript, res.TestScript); }
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); }
void OnClosing(object sender, ClosingEventArgs e) { //! Do not change combo texts, , at least in Far 2.0.1345, //! it triggers autocomplete that prevents closing. if (e.Control == null) { return; } if (Type == 0) { if (!int.TryParse(UIMatter.Text, out int value) || value <= 0) { Far.Api.Message("Invalid line number", "Line"); UIDialog.Focused = UIMatter; e.Ignore = true; return; } if (UIScript.Text.TrimEnd().Length == 0) { Far.Api.Message("Script has to be defined", "Script"); UIDialog.Focused = UIScript; e.Ignore = true; return; } } // script: trim, file may not exist Script = UIScript.Text.TrimEnd(); // action: Action = null; string action = UIAction.Text.TrimEnd(); if (action.Length > 0) { try { Action = ScriptBlock.Create(action); } catch (RuntimeException ex) { Far.Api.Message(ex.Message, "Action"); UIDialog.Focused = UIAction; e.Ignore = true; return; } } }
public void GlobalSetup() { SetupRunspace(); scriptBlock = ScriptBlock.Create(InvokeMethodScript); // Run it once to get the C# code jitted and the script compiled. // The first call to this takes relatively too long, which makes the BDN's heuristic incorrectly // believe that there is no need to run many ops in each interation. However, the subsequent runs // of this method is much faster than the first run, and this causes 'MinIterationTime' warnings // to our benchmarks and make the benchmark results not reliable. // Calling this method once in 'GlobalSetup' is a workaround. // See https://github.com/dotnet/BenchmarkDotNet/issues/837#issuecomment-828600157 scriptBlock.Invoke(); }
internal static ScriptBlock CreateInvocationScriptBlock(string command) { string script = new StringBuilder(256) .Append("param($wordToComplete,$commandAst,$cursorPosition)[") .Append(s_fullTypeName) .Append("]::") .Append(nameof(CompleteCommand)) .Append("('") .Append(command) .Append("',$wordToComplete,$commandAst,$cursorPosition)") .ToString(); return(ScriptBlock.Create(script)); }
/// <summary> /// Implements the begin action of the command /// </summary> protected override void BeginProcessing() { object outBuffer; if (MyInvocation.BoundParameters.TryGetValue("OutBuffer", out outBuffer)) { MyInvocation.BoundParameters["OutBuffer"] = 1; } Hashtable clonedBoundParameters = new Hashtable(); foreach (string key in MyInvocation.BoundParameters.Keys) { if (!_NonclonedProperties.Contains(key)) { clonedBoundParameters[key] = MyInvocation.BoundParameters[key]; } } if (MyInvocation.BoundParameters.ContainsKey("Property")) { clonedBoundParameters["Property"] = Property.Select(o => o.Value).AsEnumerable().ToArray(); } if ((ShowExcludeProperty.Length > 0) || (ShowProperty.Length > 0) || (!String.IsNullOrEmpty(TypeName)) || (KeepInputObject.ToBool())) { _NoAdjustment = false; } if (ShowProperty.Length > 0) { _DisplayPropertySet = new PSMemberInfo[] { new PSPropertySet("DefaultDisplayPropertySet", ShowProperty) } } ; // Set the list of parameters to a variable in the caller scope, so it can be splatted this.SessionState.PSVariable.Set("__PSFramework_SelectParam", clonedBoundParameters); ScriptBlock scriptCommand = ScriptBlock.Create("Select-Object @__PSFramework_SelectParam"); _Pipeline = scriptCommand.GetSteppablePipeline(MyInvocation.CommandOrigin); if (_NoAdjustment) { _Pipeline.Begin(this); } else { _Pipeline.Begin(true); } }
private Boolean ExecutePSShellGetModulesCmdlet() { //demo_bc_general_one_message.exe Collection <PSObject> psObjects = null; using (Pipeline psPipeline = psRunspace.CreatePipeline()) { // Define the command to be executed in this pipeline Command command1 = new Command("Get-Process"); // Add this command to the pipeline psPipeline.Commands.Add(command1); Command command2 = new Command("Sort-Object"); command2.Parameters.Add("Property", "Name"); psPipeline.Commands.Add(command2); Command command3 = new Command("Select"); command3.Parameters.Add("ExpandProperty", "modules"); psPipeline.Commands.Add(command3); Command command4 = new Command("Where-Object"); ScriptBlock scriptBlock = ScriptBlock.Create("$_.ModuleName -eq 'galpcep.dll'"); command4.Parameters.Add("FilterScript", scriptBlock); psPipeline.Commands.Add(command4); Command command5 = new Command("group"); command5.Parameters.Add("Property", "FileName"); psPipeline.Commands.Add(command5); Command command6 = new Command("Select"); command6.Parameters.Add("Property", "name"); psPipeline.Commands.Add(command6); //command.Parameters.Add("Sort-Object -Property Name | ft Name, DriverVersion, DriverProvider, IsPresent, HasProblem -AutoSize"); try { // Process the results psObjects = psPipeline.Invoke(); foreach (var psObject in psObjects) { ;//WriteObject(psObject); //_deviceMagaerDataReport.HasProblem = psObject.Properties["HasProblem"].Value.ToString(); FullDataReport.DeviceDriverDataList.Add(_deviceMagaerDataReport); } } catch (CmdletInvocationException exception) { // Process the exception here } } return(true); }
public void NewAzureVMWithWindowsAndCustomData() { try { _serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); string newAzureVMName = Utilities.GetUniqueShortName("PSWinVM"); var customDataFile = @".\CustomData.bin"; var customDataContent = File.ReadAllText(customDataFile); // Add-AzureProvisioningConfig with X509Certificate var azureVMConfigInfo = new AzureVMConfigInfo(newAzureVMName, InstanceSize.Small.ToString(), imageName); var azureProvisioningConfig = new AzureProvisioningConfigInfo(username, password, customDataFile); var persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); // New-AzureVM vmPowershellCmdlets.NewAzureVM(_serviceName, new[] { vm }, locationName, true); Console.WriteLine("New Azure service with name:{0} created successfully.", _serviceName); // Get-AzureVM var vmContext = vmPowershellCmdlets.GetAzureVM(newAzureVMName, _serviceName); // Get-AzureCertificate var winRmCert = vmPowershellCmdlets.GetAzureCertificate(_serviceName, vmContext.VM.DefaultWinRmCertificateThumbprint, "sha1").First(); // Install the WinRM cert to the local machine's root location. InstallCertificate(winRmCert, StoreLocation.LocalMachine, StoreName.Root); var connUri = vmPowershellCmdlets.GetAzureWinRMUri(_serviceName, newAzureVMName); var cred = new PSCredential(username, Utilities.convertToSecureString(password)); Utilities.RetryActionUntilSuccess(() => { // Invoke Command var scriptBlock = ScriptBlock.Create(@"Get-Content -Path 'C:\AzureData\CustomData.bin'"); var invokeInfo = new InvokeCommandCmdletInfo(connUri, cred, scriptBlock); var invokeCmd = new PowershellCmdlet(invokeInfo); var results = invokeCmd.Run(false); Assert.IsTrue(customDataContent == results.First().BaseObject as string); }, "Access is denied", 10, 30); pass = true; } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } }
/// <summary> /// Perform the actual logic /// </summary> protected override void ProcessRecord() { bool test = PSCmdlet.ShouldProcess(LanguagePrimitives.ConvertTo <string>(Target), _Message); if (test) { WriteMessage(Localization.LocalizationHost.ReadLog("PSFramework.FlowControl.Invoke-PSFProtectedCommand.Confirmed", new object[] { _Message }), Message.MessageLevel.SomewhatVerbose, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, null, Target); } else { WriteMessage(Localization.LocalizationHost.ReadLog("PSFramework.FlowControl.Invoke-PSFProtectedCommand.Denied", new object[] { _Message }), Message.MessageLevel.SomewhatVerbose, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, null, Target); return; } try { WriteObject(PSCmdlet.InvokeCommand.InvokeScript(false, ScriptBlock, null, null)); } catch (Exception e) { ScriptBlock errorBlock = ScriptBlock.Create(@" param ( $__PSFramework__Message, $__PSFramework__Exception, $__PSFramework__Target, $__PSFramework__Continue, $__PSFramework__FunctionName, $__PSFramework__ModuleName, $__PSFramework__File, $__PSFramework__Line, $__PSFramework__Cmdlet, $__PSFramework__EnableException ) Stop-PSFFunction -Message $__PSFramework__Message -Exception $__PSFramework__Exception -Target $__PSFramework__Target -Continue:$__PSFramework__Continue -FunctionName $__PSFramework__FunctionName -ModuleName $__PSFramework__ModuleName -File $__PSFramework__File -Line $__PSFramework__Line -Cmdlet $__PSFramework__Cmdlet -EnableException $__PSFramework__EnableException -StepsUpward 1 return "); object[] arguments = new object[] { _ErrorMessage, e, Target, Continue, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, PSCmdlet, EnableException }; PSCmdlet.InvokeCommand.InvokeScript(false, errorBlock, null, arguments); } }
public override CodeCompileUnit Parse(TextReader codeStream) { var script = codeStream.ReadToEnd(); var ast = ScriptBlock.Create(script).Ast; var visitor = new CodeDomAstVisitor(); var unit = ast.Visit(visitor) as CodeCompileUnit; unit.ReferencedAssemblies.Add(typeof(Point).Assembly.FullName); unit.ReferencedAssemblies.Add(typeof(Form).Assembly.FullName); return(unit); }
/// <summary> /// Applies a value to a configuration item, invoking validation and handler scriptblocks. /// </summary> /// <param name="Value">The value to apply</param> private void ApplyValue(object Value) { object tempValue = Value; #region Validation if (!DisableValidation.ToBool() && (!String.IsNullOrEmpty(_Config.Validation))) { ScriptBlock tempValidation = ScriptBlock.Create(_Config.Validation.ToString()); //if ((tempValue != null) && ((tempValue as ICollection) != null)) // tempValue = new object[1] { tempValue }; PSObject validationResult = tempValidation.Invoke(tempValue)[0]; if (!(bool)validationResult.Properties["Success"].Value) { _ValidationErrorMessage = (string)validationResult.Properties["Message"].Value; throw new ArgumentException(String.Format("Failed validation: {0}", _ValidationErrorMessage)); } tempValue = validationResult.Properties["Value"].Value; } #endregion Validation #region Handler if (!DisableHandler.ToBool() && (_Config.Handler != null)) { object handlerValue = tempValue; ScriptBlock tempHandler = ScriptBlock.Create(_Config.Handler.ToString()); if ((tempValue != null) && ((tempValue as ICollection) != null)) { handlerValue = new object[1] { tempValue } } ; tempHandler.Invoke(handlerValue); } #endregion Handler _Config.Value = tempValue; if (Register.ToBool()) { ScriptBlock registerCodeblock = ScriptBlock.Create(@" param ($Config) $Config | Register-DbatoolsConfig "); registerCodeblock.Invoke(_Config); } }
private static ScriptBlock CreateMethodReference(Func <IArgumentCompleter> completerConstructor) //where T: class, IArgumentCompleter { return((ScriptBlock)ScriptBlock.Create("" + "{" + " $argumentCompleter = $psBuildCompletionConstructor.Invoke();" + " $argumentCompleter.CompleteArgument($args[0], $args[1], $args[2], $args[3], $args[4])" + "}.GetNewClosure()") // pass arguments as named variables to avoid conflict with $args[] .InvokeWithContext(null, new List <PSVariable>() { new PSVariable("psBuildCompletionConstructor", completerConstructor) })[0] .BaseObject); }
public void ShoudGenerateHelpForUnknownCmdLet() { ScriptBlock.Create("get-myunknownCmdlet") .Ast .Visit(explainer); AnalysisResult res = explainer.GetAnalysisResult(); Assert.That( res .Explanations[0] .Description .StartsWith( "Unrecognized cmdlet. Try finding the module that contains this cmdlet and add it to my database.")); }
//********************************************************************************************************** // Device Drivers //********************************************************************************************************** private Boolean ExecutePSShellGetDeviceCmdlet() { //Get - Device | Sort - Object - Property Name | ft Name, DriverVersion, DriverProvider, IsPresent, HasProblem - AutoSize Collection <PSObject> psObjects = null; using (Pipeline psPipeline = psRunspace.CreatePipeline()) { // Define the command to be executed in this pipeline Command command1 = new Command("Get-Device"); // Add this command to the pipeline psPipeline.Commands.Add(command1); Command command2 = new Command("Sort-Object"); command2.Parameters.Add("Property", "Name"); psPipeline.Commands.Add(command2); Command command3 = new Command("Where-Object"); ScriptBlock scriptBlock = ScriptBlock.Create("$_.DriverProvider -like '*Excalibur*'"); command3.Parameters.Add("FilterScript", scriptBlock); psPipeline.Commands.Add(command3); //command.Parameters.Add("Sort-Object -Property Name | ft Name, DriverVersion, DriverProvider, IsPresent, HasProblem -AutoSize"); try { // Process the results psObjects = psPipeline.Invoke(); foreach (var psObject in psObjects) { ;//WriteObject(psObject); _deviceMagaerDataReport = new DeviceManagerDataModel(); _deviceMagaerDataReport.Name = psObject.Properties["Name"].Value.ToString(); _deviceMagaerDataReport.Manufacturer = psObject.Properties["Manufacturer"].Value.ToString(); _deviceMagaerDataReport.HardwareIds = psObject.Properties["HardwareIds"].Value.ToString(); _deviceMagaerDataReport.DriverVersion = psObject.Properties["DriverVersion"].Value.ToString(); _deviceMagaerDataReport.DriverProvider = psObject.Properties["DriverProvider"].Value.ToString(); _deviceMagaerDataReport.LocationInfo = psObject.Properties["LocationInfo"].Value.ToString(); _deviceMagaerDataReport.IsPresent = psObject.Properties["IsPresent"].Value.ToString(); _deviceMagaerDataReport.IsEnabled = psObject.Properties["IsEnabled"].Value.ToString(); _deviceMagaerDataReport.HasProblem = psObject.Properties["HasProblem"].Value.ToString(); FullDataReport.DeviceDriverDataList.Add(_deviceMagaerDataReport); } } catch (CmdletInvocationException exception) { // Process the exception here } } return(true); }
private object GetPropertyValue(PSObject sourceItem, string sectionName, string propertyName) { var value = sourceItem.Properties["Value"].Value; if (value is PSObject) { value = ((PSObject)value).BaseObject; } if (value == null) { return(null); } var expectedType = GetExpectedType(sectionName, propertyName); if (expectedType == typeof(ScriptBlock[])) { ArrayList scriptBlocks = new ArrayList(); foreach (string scriptBlock in (ArrayList)value) { scriptBlocks.Add(ScriptBlock.Create(scriptBlock)); } value = scriptBlocks; } if (expectedType == typeof(ContainerInfo[])) { ArrayList containers = new ArrayList(); foreach (PSObject container in (ArrayList)value) { var containerInfo = Pester.ContainerInfo.Create(); containerInfo.Type = (string)container.Properties["Type"].Value; containerInfo.Item = container.Properties["Item"].Value; containerInfo.Data = container.Properties["Data"].Value; containers.Add(containerInfo); } value = containers; } if (value is ArrayList) { value = ((ArrayList)value).ToArray(); } return(value); }
/// <summary> /// Create ScriptBlock that registers the correct location for tab completetion of the -Location parameter /// </summary> /// <param name="resourceTypes"></param> /// <returns></returns> public static ScriptBlock CreateScriptBlock(string resourceType, string[] parentResourceNames) { string script = "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)\n" + "$parentResources = @()\n"; foreach (var parentResourceName in parentResourceNames) { script += String.Format("$parentResources += $fakeBoundParameter[\"{0}\"]\n", parentResourceName); } script += String.Format("$resourceType = \"{0}\"\n", resourceType) + "$resources = [Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters.ResourceNameCompleterAttribute]::FindResources($resourceType, $parentResources)\n" + "$resources | Where-Object { $_ -Like \"$wordToComplete*\" } | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }"; ScriptBlock scriptBlock = ScriptBlock.Create(script); return(scriptBlock); }
// Warm up the PowerShell instance so that the subsequent function load and invocation requests are faster private static void WarmUpPowerShell(System.Management.Automation.PowerShell firstPowerShellInstance) { // It turns out that creating/removing a function warms up the runspace enough. // We just need this name to be unique, so that it does not coincide with an actual function. const string DummyFunctionName = "DummyFunction-71b09c92-6bce-42d0-aba1-7b985b8c3563"; firstPowerShellInstance.AddCommand("Microsoft.PowerShell.Management\\New-Item") .AddParameter("Path", "Function:") .AddParameter("Name", DummyFunctionName) .AddParameter("Value", ScriptBlock.Create(string.Empty)) .InvokeAndClearCommands(); firstPowerShellInstance.AddCommand("Microsoft.PowerShell.Management\\Remove-Item") .AddParameter("Path", $"Function:{DummyFunctionName}") .InvokeAndClearCommands(); }
private Dictionary <string, ScriptBlock> CreateDslDefinitionFromSchema(IDictionary <string, ObjectProperty> schemaProperties) { var functionDict = new Dictionary <string, ScriptBlock>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair <string, ObjectProperty> propertySchemaEntry in schemaProperties) { using (var sw = new StringWriter()) { var writer = new PSArmDslWriter(sw); writer.WriteSchemaDefinition(propertySchemaEntry.Key, propertySchemaEntry.Value.Type.Type, out string functionName); functionDict[functionName] = ScriptBlock.Create(sw.ToString()); } } return(functionDict); }
public void TestParallelOutput() { using (var ps = PowerShell.Create()) { //ps.RunspacePool = m_runspacePool; ps.AddCommand("Invoke-Parallel") .AddParameter("ScriptBlock", ScriptBlock.Create("$_* 2")) .AddParameter("ThrottleLimit", 10); var input = new PSDataCollection <int>(Enumerable.Range(1, 1000)); input.Complete(); var output = ps.Invoke <int>(input); var sum = output.Aggregate(0, (a, b) => a + b); Assert.AreEqual(1001000, sum); } }
}//VIPTokenCheckasSystem end. protected void SelectRP_Click(object sender, EventArgs e) { DropDownList1.Items.Clear(); Label3.Text = ""; GridView3.DataSource = null; GridView3.DataBind(); try { System.Net.Sockets.TcpClient client = new TcpClient(TextBox1.Text, 5985); using (PowerShell PowerShellInstance = PowerShell.Create()) { PowerShellInstance.AddCommand("invoke-command"); PowerShellInstance.AddParameter("ComputerName", TextBox1.Text); ScriptBlock filter = ScriptBlock.Create("Get-AdfsRelyingPartyTrust | select -ExpandProperty Identifier"); PowerShellInstance.AddParameter("ScriptBlock", filter); Collection <PSObject> PSOutput = PowerShellInstance.Invoke(); foreach (Object Identifier in PSOutput) { if (Identifier != null) { string RPNameS = Identifier.ToString(); DropDownList1.Items.Add(RPNameS); DropDownList1.Items[0].Selected = true; Label3.Text = "Default selected RP Identifier " + DropDownList1.SelectedItem.Text; Label3.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000"); } } if (PowerShellInstance.Streams.Error.Count > 0) { var errors = PowerShellInstance.Streams.Error; var sb = new StringBuilder(); foreach (var error in errors) { sb.Append(error); } string errorResult = sb.ToString(); Label3.Text = errorResult; Label3.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000"); } } // PS End } catch (Exception ExSelRP) { Label3.Text = ExSelRP.Message; Label3.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000"); } }
public void Should_trace_command() { using (var shell = PowerShell.Create()) { var twtl = new TextWriterTraceListener("twtlout"); twtl.WriteLine("TWTL" + DateTime.Now.ToString()); twtl.Flush(); var scriptBlock = ScriptBlock.Create(@"Get-Date"); shell.AddScript(@"$t = New-Object System.Diagnostics.TextWriterTraceListener -Arg 'pst4'; $t.WriteLine('woo'); Get-TraceSource | % { $_.Listeners.Add($t); $_.Options='All'; $_.Switch.Level='All' }; Get-Date; $t.Dispose();"); shell.Invoke(); shell.Commands.Clear(); shell.AddCommand("Trace-Command") .AddParameter("Name", "*") .AddParameter("FilePath", @"pstrace2") .AddParameter("Option", @"All") .AddParameter("Force", true) .AddParameter("PSHost", true) .AddParameter("Debugger", true) .AddParameter("Expression", scriptBlock); shell.AddScript(@"Get-TraceSource | % { $_.Listeners } | % { $_.Flush() }"); var result = shell.Invoke(); foreach (var item in result) { Console.WriteLine(string.Format("Item: {0}", item)); } foreach (var item in shell.Streams.Debug) { Console.WriteLine(string.Format("DBG: {0}", item)); } foreach (var item in shell.Streams.Error) { Console.WriteLine(string.Format("ERR: {0}", item)); } Assert.AreEqual(0, shell.Streams.Error.Count, "ErrorStream"); Assert.AreNotEqual(0, result.Count); //Assert.AreEqual("z", Environment.GetEnvironmentVariable("MONO_TRACE_LISTENER")); Console.WriteLine("WOO!"); } }
void WriteResult(ulong sz, string p) { PSObject o = new PSObject(); // probably should just calculate that here and insert it as another column string human = @"switch($this.Length) { { $_ -gt 1tb } { ""{ 0:n2}T"" -f ($_ / 1tb) ; break } { $_ -gt 1gb } { ""{0:n2}G"" -f ($_ / 1gb) ; break } { $_ -gt 1mb } { ""{0:n2}M"" -f ($_ / 1mb) ; break } { $_ -gt 1kb } { ""{0:n2}K"" -f ($_ / 1Kb) ; break } default { ""{0}"" -f $_} } "; string[] props = { "Length", "FullName" }; string[] propsh = { "ReadableLength", "FullName" }; ScriptBlock sb = ScriptBlock.Create(human); PSScriptProperty psp = new PSScriptProperty("ReadableLength", sb); PSPropertySet ps; if (humanreadable) { ps = new PSPropertySet("DefaultDisplayPropertySet", propsh); } else { ps = new PSPropertySet("DefaultDisplayPropertySet", props); } PSMemberSet pm = new PSMemberSet("PSStandardMembers", new PSMemberInfo[] { ps }); // pm.Members.Add(); o.Members.Add(pm); o.Properties.Add(new PSNoteProperty("Length", sz)); o.Properties.Add(new PSNoteProperty("FullName", p)); o.Members.Add(psp); WriteObject(o); }
public void TestAssingmentExpressionVariableCapture() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript("[int]$x=10;", false).Invoke(); ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("$y = $x * 5; $y")) .AddParameter("ThrottleLimit", 1) .AddParameter("InputObject", 1); var result = ps.Invoke <int>().First(); Assert.AreEqual(50, result); } }
public Collection <PSObject> InvokeScript( string script, bool useNewScope, PipelineResultTypes writeToPipeline, IList input, params object[] args) { if (script == null) { throw new ArgumentNullException(nameof(script)); } // Compile the script text into an executable script block. ScriptBlock sb = ScriptBlock.Create(_context, script); return(InvokeScript(sb, useNewScope, writeToPipeline, input, args)); }
object TransformItem(EngineIntrinsics engineIntrinsics, object inputData) { var inputObject = inputData.ToPSObject().BaseObject; var scriptBlock = inputObject as ScriptBlock; if (null == scriptBlock) { return(inputData); } scriptBlock = ScriptBlock.Create("if( -not($_) ){ $_ = $this; } " + scriptBlock); var property = new PSScriptProperty("_" + Guid.NewGuid().ToString("N"), scriptBlock); return(property); }
private PSCommand ParsePsCommandUsingScriptBlock(string line, bool?useLocalScope) { try { ExecutionContext executionContext = this._runspaceRef.OldValue.ExecutionContext; return(ScriptBlock.Create(executionContext, line).GetPowerShell(executionContext, useLocalScope, new object[0]).Commands); } catch (ScriptBlockToPowerShellNotSupportedException exception) { CommandProcessorBase.CheckForSevereException(exception); } catch (RuntimeException exception2) { CommandProcessorBase.CheckForSevereException(exception2); } return(null); }
public void TestBinaryExpressionVariableCapture() { using (var ps = PowerShell.Create()) { ps.RunspacePool = m_runspacePool; ps.AddScript("[int]$x=10", false).Invoke(); ps.Commands.Clear(); ps.AddStatement() .AddCommand("Invoke-Parallel", false) .AddParameter("ScriptBlock", ScriptBlock.Create("$x -eq 10")) .AddParameter("ThrottleLimit", 1) .AddParameter("InputObject", 1); var result = ps.Invoke <bool>().First(); Assert.IsTrue(result); } }
// Static Method to parse a script file public static List <Node> ParseFile(string file) { string script = File.ReadAllText(file); FileInfo ScriptFileInfo = new FileInfo(file); ScriptBlock scriptblock = ScriptBlock.Create(script); Ast NamedBlock = scriptblock.Ast.Find(Args => Args is NamedBlockAst, false); // IEnumerable<Ast> enumerable = NamedBlock.FindAll(Args => Args is Ast && FlowChartCore.Utility.GetValidTypes().Contains(Args.GetType()) && Args.Parent == NamedBlock, false); IEnumerable <Ast> enumerable = NamedBlock.FindAll(Args => Args is Ast && Args.Parent == NamedBlock, false); int Position = 1; List <Node> Nodes = new List <Node>(); Tree Arbre = new Tree(Nodes, scriptblock.Ast, NodesOrigin.File, ScriptFileInfo); bool tmp = true; foreach (var block in enumerable) { if (FlowChartCore.Utility.GetValidTypes().Contains(block.GetType())) { // valid type found Node tmpNode = block.CreateNode(0, Position, null, Arbre); // tmpNode.Origin = NodesOrigin.File; // tmpNode.FileInfo = ScriptFileInfo; Nodes.Add(tmpNode); Position++; // reset tmp tmp = true; } else if (tmp) { // not a valid type, and tmp is false, create code node tmp = false; Node tmpNode = new CodeNode(0, Position, null, Arbre); // tmpNode.Origin = NodesOrigin.File; // tmpNode.FileInfo = ScriptFileInfo; Nodes.Add(tmpNode); Position++; } } return(Arbre.Nodes); }
public void ShouldGenerateHelpForUsingExpressions() { ScriptBlock.Create("$using:var").Ast.Visit(explainer); AnalysisResult res = explainer.GetAnalysisResult(); Assert.AreEqual( "A variable named 'var', with the 'using' scope modifier: a local variable used in a remote scope.", res.Explanations[1].Description); Assert.AreEqual( "https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Remote_Variables", res.Explanations[1].HelpResult?.DocumentationLink); Assert.AreEqual( "Scoped variable", res.Explanations[1].CommandName); Assert.That( res.Explanations[1].HelpResult?.RelatedLinks, Is.Not.Null.And.Not.Empty); }