Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```// Decompiled with JetBrains decompiler
- // Type: Microsoft.PowerShell.Commands.GetRandomCommand
- // Assembly: Microsoft.PowerShell.Commands.Utility, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
- // MVID: 3BD7B47C-588A-4217-80BE-3EE52156DF03
- // Assembly location: C:\Windows\WinSxS\msil_microsoft.powershell.commands.utility_31bf3856ad364e35_1.0.0.0_none_b77a5f49a3ba5d1f\Microsoft.PowerShell.Commands.Utility.dll
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Management.Automation;
- using System.Management.Automation.Runspaces;
- using System.Threading;
- namespace Microsoft.PowerShell.Commands
- {
- [Cmdlet("Get", "Random", DefaultParameterSetName = "RandomNumberParameterSet")]
- public class GetRandomCommand : PSCmdlet
- {
- [TraceSource("GetRandomCommand", "Class that has get-random command implementation")]
- private static PSTraceSource tracer = PSTraceSource.GetTracer("GetRandomCommand", "Class that has get-random command implementation");
- private static ReaderWriterLock runspaceGeneratorMapLock = new ReaderWriterLock();
- private static Dictionary<Guid, Random> RunspaceGeneratorMap = new Dictionary<Guid, Random>();
- private const string RandomNumberParameterSet = "RandomNumberParameterSet";
- private const string RandomListItemParameterSet = "RandomListItemParameterSet";
- private GetRandomCommand.MyParameterSet effectiveParameterSet;
- private Random generator;
- private int? setSeed;
- private object maximum;
- private object minimum;
- private List<object> chosenListItems;
- private int numberOfProcessedListItems;
- private object[] inputObject;
- private int count;
- private GetRandomCommand.MyParameterSet EffectiveParameterSet
- {
- get
- {
- if (this.effectiveParameterSet == GetRandomCommand.MyParameterSet.Unknown)
- {
- if (this.MyInvocation.ExpectingInput && this.Maximum == null && this.Minimum == null)
- this.effectiveParameterSet = GetRandomCommand.MyParameterSet.RandomListItem;
- else if (this.ParameterSetName.Equals("RandomListItemParameterSet", StringComparison.OrdinalIgnoreCase))
- this.effectiveParameterSet = GetRandomCommand.MyParameterSet.RandomListItem;
- else if (this.ParameterSetName.Equals("RandomNumberParameterSet", StringComparison.OrdinalIgnoreCase))
- {
- if (this.Maximum != null && this.Maximum.GetType().IsArray)
- {
- this.InputObject = (object[]) this.Maximum;
- this.effectiveParameterSet = GetRandomCommand.MyParameterSet.RandomListItem;
- }
- else
- this.effectiveParameterSet = GetRandomCommand.MyParameterSet.RandomNumber;
- }
- }
- return this.effectiveParameterSet;
- }
- }
- private Random Generator
- {
- get
- {
- if (this.generator == null)
- {
- Guid instanceId = this.Context.CurrentRunspace.InstanceId;
- bool flag = false;
- try
- {
- GetRandomCommand.runspaceGeneratorMapLock.AcquireReaderLock(-1);
- flag = !GetRandomCommand.RunspaceGeneratorMap.TryGetValue(instanceId, out this.generator);
- }
- finally
- {
- GetRandomCommand.runspaceGeneratorMapLock.ReleaseReaderLock();
- }
- if (flag)
- this.Generator = new Random();
- }
- return this.generator;
- }
- set
- {
- this.generator = value;
- Runspace currentRunspace = this.Context.CurrentRunspace;
- try
- {
- GetRandomCommand.runspaceGeneratorMapLock.AcquireWriterLock(-1);
- if (!GetRandomCommand.RunspaceGeneratorMap.ContainsKey(currentRunspace.InstanceId))
- currentRunspace.StateChanged += new EventHandler<RunspaceStateEventArgs>(GetRandomCommand.CurrentRunspace_StateChanged);
- GetRandomCommand.RunspaceGeneratorMap[currentRunspace.InstanceId] = this.generator;
- }
- finally
- {
- GetRandomCommand.runspaceGeneratorMapLock.ReleaseWriterLock();
- }
- }
- }
- [Parameter]
- [ValidateNotNull]
- public int? SetSeed
- {
- get
- {
- return this.setSeed;
- }
- set
- {
- this.setSeed = value;
- }
- }
- [Parameter(ParameterSetName = "RandomNumberParameterSet", Position = 0)]
- public object Maximum
- {
- get
- {
- return this.maximum;
- }
- set
- {
- this.maximum = value;
- }
- }
- [Parameter(ParameterSetName = "RandomNumberParameterSet")]
- public object Minimum
- {
- get
- {
- return this.minimum;
- }
- set
- {
- this.minimum = value;
- }
- }
- [ValidateNotNullOrEmpty]
- [Parameter(Mandatory = true, ParameterSetName = "RandomListItemParameterSet", Position = 0, ValueFromPipeline = true)]
- public object[] InputObject
- {
- get
- {
- return this.inputObject;
- }
- set
- {
- this.inputObject = value;
- }
- }
- [ValidateRange(1, 2147483647)]
- [Parameter(ParameterSetName = "RandomListItemParameterSet")]
- public int Count
- {
- get
- {
- return this.count;
- }
- set
- {
- this.count = value;
- }
- }
- private ErrorDetails GetErrorDetails(string errorId, params object[] args)
- {
- if (string.IsNullOrEmpty(errorId))
- throw GetRandomCommand.tracer.NewArgumentNullException("errorId");
- return new ErrorDetails(this.GetType().Assembly, "GetRandomCommandStrings", errorId, args);
- }
- private void ThrowMinGreaterThanOrEqualMax(object min, object max)
- {
- if (min == null)
- throw GetRandomCommand.tracer.NewArgumentNullException("min");
- if (max == null)
- throw GetRandomCommand.tracer.NewArgumentNullException("max");
- string errorId = "MinGreaterThanOrEqualMax";
- this.ThrowTerminatingError(new ErrorRecord((Exception) new ArgumentException(this.GetErrorDetails(errorId, min, max).Message), errorId, ErrorCategory.InvalidArgument, (object) null));
- }
- private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e)
- {
- switch (e.RunspaceStateInfo.State)
- {
- case RunspaceState.Closed:
- case RunspaceState.Broken:
- try
- {
- GetRandomCommand.runspaceGeneratorMapLock.AcquireWriterLock(-1);
- GetRandomCommand.RunspaceGeneratorMap.Remove(((Runspace) sender).InstanceId);
- break;
- }
- finally
- {
- GetRandomCommand.runspaceGeneratorMapLock.ReleaseWriterLock();
- }
- }
- }
- private bool IsInt(object o)
- {
- if (o == null)
- return true;
- PSObject psObject = PSObject.AsPSObject(o);
- if (psObject.BaseObject is int)
- return true;
- if (psObject.BaseObject is string)
- {
- int result;
- return int.TryParse((string) psObject.BaseObject, out result);
- }
- return false;
- }
- private double ConvertToDouble(object o, double defaultIfNull)
- {
- if (o == null)
- return defaultIfNull;
- return (double) LanguagePrimitives.ConvertTo(o, typeof (double), (IFormatProvider) CultureInfo.InvariantCulture);
- }
- private int ConvertToInt(object o, int defaultIfNull)
- {
- if (o == null)
- return defaultIfNull;
- return (int) LanguagePrimitives.ConvertTo(o, typeof (int), (IFormatProvider) CultureInfo.InvariantCulture);
- }
- private double GetRandomDouble(double min, double max)
- {
- double d = max - min;
- double num1;
- if (double.IsInfinity(d))
- {
- do
- {
- double num2 = this.Generator.NextDouble();
- num1 = min + num2 * max - num2 * min;
- }
- while (num1 >= max);
- }
- else
- {
- do
- {
- double num2 = this.Generator.NextDouble();
- num1 = min + num2 * d;
- d *= num2;
- }
- while (num1 >= max);
- }
- return num1;
- }
- protected override void BeginProcessing()
- {
- using (GetRandomCommand.tracer.TraceMethod())
- {
- if (this.SetSeed.HasValue)
- this.Generator = new Random(this.SetSeed.Value);
- if (this.EffectiveParameterSet == GetRandomCommand.MyParameterSet.RandomNumber)
- {
- if (this.IsInt(this.Maximum) && this.IsInt(this.Minimum))
- {
- int minValue = this.ConvertToInt(this.Minimum, 0);
- int maxValue = this.ConvertToInt(this.Maximum, int.MaxValue);
- if (minValue >= maxValue)
- this.ThrowMinGreaterThanOrEqualMax((object) minValue, (object) maxValue);
- this.WriteObject((object) this.Generator.Next(minValue, maxValue));
- }
- else
- {
- double min = this.ConvertToDouble(this.Minimum, 0.0);
- double max = this.ConvertToDouble(this.Maximum, double.MaxValue);
- if (min >= max)
- this.ThrowMinGreaterThanOrEqualMax((object) min, (object) max);
- this.WriteObject((object) this.GetRandomDouble(min, max));
- }
- }
- else
- {
- if (this.EffectiveParameterSet != GetRandomCommand.MyParameterSet.RandomListItem)
- return;
- this.chosenListItems = new List<object>();
- this.numberOfProcessedListItems = 0;
- if (this.Count != 0)
- return;
- this.Count = 1;
- }
- }
- }
- protected override void ProcessRecord()
- {
- using (GetRandomCommand.tracer.TraceMethod())
- {
- if (this.EffectiveParameterSet != GetRandomCommand.MyParameterSet.RandomListItem)
- return;
- foreach (object obj in this.InputObject)
- {
- if (this.numberOfProcessedListItems < this.Count)
- this.chosenListItems.Add(obj);
- else if (this.Generator.Next(this.numberOfProcessedListItems + 1) < this.Count)
- this.chosenListItems[this.Generator.Next(this.chosenListItems.Count)] = obj;
- ++this.numberOfProcessedListItems;
- }
- }
- }
- protected override void EndProcessing()
- {
- using (GetRandomCommand.tracer.TraceMethod())
- {
- if (this.EffectiveParameterSet != GetRandomCommand.MyParameterSet.RandomListItem)
- return;
- int count = this.chosenListItems.Count;
- for (int minValue = 0; minValue < count; ++minValue)
- {
- int index = this.Generator.Next(minValue, count);
- if (minValue != index)
- {
- object chosenListItem = this.chosenListItems[minValue];
- this.chosenListItems[minValue] = this.chosenListItems[index];
- this.chosenListItems[index] = chosenListItem;
- }
- }
- foreach (object chosenListItem in this.chosenListItems)
- this.WriteObject(chosenListItem);
- }
- }
- private enum MyParameterSet
- {
- Unknown,
- RandomNumber,
- RandomListItem,
- }
- }
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement