Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes372downloads
Engine.ScriptBlock.cs78 linesDownload Raw Back to benchmarks
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System.Collections.Generic;5using System.Collections.ObjectModel;6using System.Management.Automation;7using System.Management.Automation.Runspaces;8using System.Runtime.InteropServices;9using BenchmarkDotNet.Attributes;10using MicroBenchmarks;11 12namespace Engine13{14    [BenchmarkCategory(Categories.Engine, Categories.Public)]15    public class Scripting16    {17        private Runspace runspace;18        private ScriptBlock scriptBlock;19 20        private void SetupRunspace()21        {22            // Unless you want to run commands from any built-in modules, using 'CreateDefault2' is enough.23            runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2());24            runspace.Open();25            Runspace.DefaultRunspace = runspace;26        }27 28        #region Invoke-Method29 30        [ParamsSource(nameof(ValuesForScript))]31        public string InvokeMethodScript { get; set; }32 33        public IEnumerable<string> ValuesForScript()34        {35            yield return @"'String'.GetType()";36            yield return @"[System.IO.Path]::HasExtension('')";37 38            // Test on COM method invocation.39            if (Platform.IsWindows)40            {41                yield return @"$sh=New-Object -ComObject Shell.Application; $sh.Namespace('c:\')";42                yield return @"$fs=New-Object -ComObject scripting.filesystemobject; $fs.Drives";43            }44        }45 46        [GlobalSetup(Target = nameof(InvokeMethod))]47        public void GlobalSetup()48        {49            SetupRunspace();50            scriptBlock = ScriptBlock.Create(InvokeMethodScript);51 52            // Run it once to get the C# code jitted and the script compiled.53            // The first call to this takes relatively too long, which makes the BDN's heuristic incorrectly54            // believe that there is no need to run many ops in each iteration. However, the subsequent runs55            // of this method is much faster than the first run, and this causes 'MinIterationTime' warnings56            // to our benchmarks and make the benchmark results not reliable.57            // Calling this method once in 'GlobalSetup' is a workaround.58            // See https://github.com/dotnet/BenchmarkDotNet/issues/837#issuecomment-82860015759            scriptBlock.Invoke();60        }61 62        [Benchmark]63        public Collection<PSObject> InvokeMethod()64        {65            return scriptBlock.Invoke();66        }67 68        #endregion69 70        [GlobalCleanup]71        public void GlobalCleanup()72        {73            runspace.Dispose();74            Runspace.DefaultRunspace = null;75        }76    }77}78