public void ConvertToCanHandleSwitchParameters(object value, bool expectedValue) { var result = LanguagePrimitives.ConvertTo(value, typeof(SwitchParameter)); var expected = new SwitchParameter(expectedValue); Assert.AreEqual(expected.GetType(), result.GetType()); Assert.AreEqual(expected.IsPresent, ((SwitchParameter)result).IsPresent); }
protected override void BeginProcessing() { if (Hidden) { Output = Return = false; KeepSeconds = 0; } else if (Return) { Output = true; KeepSeconds = int.MaxValue; } else if (Output) { KeepSeconds = int.MaxValue; } // new Job job = new Job( Command, Parameters == null ? null : Parameters.BaseObject, Name, !Hidden && !Output, KeepSeconds); // start if (!Return) job.StartJob(); // write if (Output) WriteObject(job); }
public void ConvertToCanHandleSwitchParameters() { var result = LanguagePrimitives.ConvertTo(3, typeof(SwitchParameter)); var expected = new SwitchParameter(true); Assert.AreEqual(expected.GetType(), result.GetType()); Assert.AreEqual(expected, result); }
protected override void ExecuteCmdlet() { if (!MyInvocation.BoundParameters.ContainsKey("Folder")) { if (!Indexed) { // If it is already an indexed property we still have to add it back to the indexed properties Indexed = !string.IsNullOrEmpty(SelectedWeb.GetIndexedPropertyBagKeys().FirstOrDefault(k => k == Key)); } SelectedWeb.SetPropertyBagValue(Key, Value); if (Indexed) { SelectedWeb.AddIndexedPropertyBagKey(Key); } else { SelectedWeb.RemoveIndexedPropertyBagKey(Key); } } else { SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); var folderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder); var folder = SelectedWeb.GetFolderByServerRelativeUrl(folderUrl); folder.EnsureProperty(f => f.Properties); folder.Properties[Key] = Value; folder.Update(); ClientContext.ExecuteQueryRetry(); } }
protected override void BeginProcessing() { base.BeginProcessing(); XmlSchemaSet _xmlSchemaSet = new XmlSchemaSet(); if (_schemaPaths != null) { if (_schemaPaths.Length > 0) { foreach (PscxPathInfo _schemaPath in _schemaPaths) { using (FileStream stream = new FileStream(_schemaPath.ProviderPath, FileMode.Open, FileAccess.Read)) { XmlSchema xmlSchema = XmlSchema.Read(stream, SchemaReadValidationHandler); _xmlSchemaSet.Add(xmlSchema); } } // If the user specified a schema they want validation, so force _validate to true _validate = true; } } if (_validate) { XmlReaderSettings.ValidationType = ValidationType.Schema; XmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; XmlReaderSettings.Schemas.Add(_xmlSchemaSet); XmlReaderSettings.ValidationEventHandler += SchemaValidationHandler; } }
protected override void ExecuteCmdlet() { if (!Indexed) { // If it is already an indexed property we still have to add it back to the indexed properties Indexed = !string.IsNullOrEmpty(SelectedWeb.GetIndexedPropertyBagKeys().FirstOrDefault(k => k == Key)); } SelectedWeb.SetPropertyBagValue(Key, Value); if(Indexed) { SelectedWeb.AddIndexedPropertyBagKey(Key); } else { SelectedWeb.RemoveIndexedPropertyBagKey(Key); } }
protected override void ExecuteCmdlet() { if (SelectedWeb.IsNoScriptSite()) { WriteError(new ErrorRecord(new Exception("Site has NoScript enabled, and setting property bag values is not supported"), "NoScriptEnabled", ErrorCategory.InvalidOperation, this)); return; } if (!MyInvocation.BoundParameters.ContainsKey("Folder")) { if (!Indexed) { // If it is already an indexed property we still have to add it back to the indexed properties Indexed = !string.IsNullOrEmpty(SelectedWeb.GetIndexedPropertyBagKeys().FirstOrDefault(k => k == Key)); } SelectedWeb.SetPropertyBagValue(Key, Value); if (Indexed) { SelectedWeb.AddIndexedPropertyBagKey(Key); } else { SelectedWeb.RemoveIndexedPropertyBagKey(Key); } } else { SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); var folderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder); var folder = SelectedWeb.GetFolderByServerRelativeUrl(folderUrl); folder.EnsureProperty(f => f.Properties); folder.Properties[Key] = Value; folder.Update(); ClientContext.ExecuteQueryRetry(); } }
// 20120123 // private void checkTimeout(ref System.Windows.Automation.AutomationElement aeWindow, private void checkTimeout(GetWindowCmdletBase cmdlet, //System.Windows.Automation.AutomationElement aeWindow, ArrayList aeWindowList, bool fromCmdlet) { // RunOnRefreshScriptBlocks(this); // System.Threading.Thread.Sleep(Preferences.SleepInterval); // RunScriptBlocks(this); SleepAndRunScriptBlocks(this); System.DateTime nowDate = System.DateTime.Now; WriteVerbose(this, "process: " + // processName + cmdlet.ProcessName + ", name: " + cmdlet.Name + ", seconds: " + (nowDate - StartDate).TotalSeconds); try { // 20120824 //if ((aeWindow != null && (int)aeWindow.Current.ProcessId > 0) || if ((null != aeWindowList && //(int)((AutomationElement)aeWindowList[0]).Current.ProcessId > 0) || aeWindowList.Count > 0) || (nowDate - StartDate).TotalSeconds > this.Timeout / 1000) { // 20120824 //if (aeWindow == null) { if (null == aeWindowList) { // ErrorRecord err = // new ErrorRecord( // new Exception(), // "ControlIsNull", // ErrorCategory.OperationTimeout, // aeWindow); // err.ErrorDetails = // new ErrorDetails( // CmdletName(this) + ": timeout expired for process: " + // cmdlet.ProcessName + ", title: " + cmdlet.Name); // WriteError(this, err, false); // //WriteError(this, err, true); //// 20120306 //return; this.Wait = false; Exception eReturn = new Exception( CmdletName(this) + ": timeout expired for process: " + cmdlet.ProcessName + ", title: " + cmdlet.Name); throw(eReturn); }else{ // WriteVerbose(this, "got the window: " + // // 20120824 // //aeWindow.Current.Name); // ((AutomationElement)aeWindowList[0]).Current.Name); } this.Wait = false; // break; } } catch (Exception eEvaluatingWindowOrMeasuringTimeout) { // try { WriteDebug(CmdletName(this) + ": exception: " + // eEvaluatingWindowOrMeasuringTimeout.Message); } catch { } WriteDebug(this, "exception: " + eEvaluatingWindowOrMeasuringTimeout.Message); // 20121001 //UIAHelper.GetScreenshotOfAutomationElement(this, CmdletName(this) + "_Timeout", true, 0, 0, 0, 0, string.Empty, System.Drawing.Imaging.ImageFormat.Jpeg); cmdlet.WriteError( cmdlet, "An error raised during checking the timeout. " + eEvaluatingWindowOrMeasuringTimeout.Message, "CheckingTimeout", ErrorCategory.InvalidOperation, true); } }
public RestartComputerCommand() { this._asjob = false; this._dcomAuthentication = AuthenticationLevel.Packet; this._impersonation = ImpersonationLevel.Impersonate; this._protocol = "DCOM"; string[] strArrays = new string[1]; strArrays[0] = "."; this._computername = strArrays; this._validatedComputerNames = new List<string>(); this._waitOnComputers = new List<string>(); this._uniqueComputerNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); this._throttlelimit = 32; this._timeout = -1; this._waitFor = WaitForServiceTypes.PowerShell; this._delay = 5; string[] strArrays1 = new string[4]; strArrays1[0] = "|"; strArrays1[1] = "/"; strArrays1[2] = "-"; strArrays1[3] = "\\"; this._indicator = strArrays1; this._cancel = new CancellationTokenSource(); this._waitHandler = new ManualResetEventSlim(false); this._computerInfos = new Dictionary<string, RestartComputerCommand.ComputerInfo>(StringComparer.OrdinalIgnoreCase); this._shortLocalMachineName = Dns.GetHostName(); this._fullLocalMachineName = Dns.GetHostEntry("").HostName; }
public TestPathCommand() { this.isValid = new SwitchParameter(); }
public override void ExecuteCmdlet() { this.VM.OSProfile = new OSProfile { ComputerName = this.ComputerName, AdminUsername = this.Credential.UserName, AdminPassword = SecureStringExtensions.ConvertToString(this.Credential.Password), CustomData = string.IsNullOrWhiteSpace(this.CustomData) ? null : Convert.ToBase64String(Encoding.UTF8.GetBytes(this.CustomData)), }; if (this.ParameterSetName == LinuxParamSet) { if (this.VM.OSProfile.WindowsConfiguration != null) { throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified); } if (this.VM.OSProfile.LinuxConfiguration == null) { this.VM.OSProfile.LinuxConfiguration = new LinuxConfiguration(); } this.VM.OSProfile.LinuxConfiguration.DisablePasswordAuthentication = (this.DisablePasswordAuthentication.IsPresent) ? (bool?)true : null; } else { if (this.VM.OSProfile.LinuxConfiguration != null) { throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified); } if (this.VM.OSProfile.WindowsConfiguration == null) { this.VM.OSProfile.WindowsConfiguration = new WindowsConfiguration(); this.VM.OSProfile.WindowsConfiguration.AdditionalUnattendContent = null; } var listenerList = new List<WinRMListener>(); if (this.WinRMHttp.IsPresent) { listenerList.Add(new WinRMListener { Protocol = ProtocolTypes.Http, CertificateUrl = null, }); } if (this.WinRMHttps.IsPresent) { listenerList.Add(new WinRMListener { Protocol = ProtocolTypes.Https, CertificateUrl = this.WinRMCertificateUrl.ToString(), }); } // OS Profile this.VM.OSProfile.WindowsConfiguration.ProvisionVMAgent = (this.ProvisionVMAgent.IsPresent) ? (bool?)true : null; this.VM.OSProfile.WindowsConfiguration.EnableAutomaticUpdates = this.EnableAutoUpdate.IsPresent ? (bool?)true : null; this.VM.OSProfile.WindowsConfiguration.TimeZone = this.TimeZone; this.VM.OSProfile.WindowsConfiguration.WinRM = !(this.WinRMHttp.IsPresent || this.WinRMHttps.IsPresent) ? null : new WinRMConfiguration { Listeners = listenerList, }; } WriteObject(this.VM); }
public ProviderRemoveItemDynamicParameters() { this.deleteKey = new SwitchParameter(); }
public CertificateProviderCodeSigningDynamicParameters() { this.codeSigningCert = new SwitchParameter(); }
internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, SwitchParameter newest) { lock (this._syncRoot) { if (count < -1L) { throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException("newest"); } if ((count > this._countEntriesAdded) || (count == -1L)) { count = this._countEntriesInBuffer; } ArrayList list = new ArrayList(); long num = 1L; if (this._capacity != 0x1000) { num = this.SmallestIDinBuffer(); } if (count != 0L) { if (!newest.IsPresent) { long id = 1L; if ((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) { id = num; } long num3 = 0L; while (num3 <= (count - 1L)) { if (id > this._countEntriesAdded) { break; } if (!this._buffer[this.GetIndexFromId(id)].Cleared && wildcardpattern.IsMatch(this._buffer[this.GetIndexFromId(id)].CommandLine.Trim())) { list.Add(this._buffer[this.GetIndexFromId(id)].Clone()); num3 += 1L; } id += 1L; } } else { long num4 = this._countEntriesAdded; long num5 = 0L; while (num5 <= (count - 1L)) { if ((((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) && (num4 < num)) || (num4 < 1L)) { break; } if (!this._buffer[this.GetIndexFromId(num4)].Cleared && wildcardpattern.IsMatch(this._buffer[this.GetIndexFromId(num4)].CommandLine.Trim())) { list.Add(this._buffer[this.GetIndexFromId(num4)].Clone()); num5 += 1L; } num4 -= 1L; } } } else { for (long i = 1L; i <= this._countEntriesAdded; i += 1L) { if (!this._buffer[this.GetIndexFromId(i)].Cleared && wildcardpattern.IsMatch(this._buffer[this.GetIndexFromId(i)].CommandLine.Trim())) { list.Add(this._buffer[this.GetIndexFromId(i)].Clone()); } } } HistoryInfo[] array = new HistoryInfo[list.Count]; list.CopyTo(array); return array; } }
internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { this.ReallocateBufferIfNeeded(); if (count < -1L) { throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException("newest"); } if (((count == -1L) || (count > this._countEntriesAdded)) || (count > this._countEntriesInBuffer)) { count = this._countEntriesInBuffer; } if ((count == 0L) || (this._countEntriesInBuffer == 0)) { return new HistoryInfo[0]; } lock (this._syncRoot) { ArrayList list = new ArrayList(); if (id > 0L) { long num; long num2 = id; if (!newest.IsPresent) { num = (num2 - count) + 1L; if (num < 1L) { num = 1L; } for (long i = num2; i >= num; i -= 1L) { if (num <= 1L) { break; } if ((this._buffer[this.GetIndexFromId(i)] != null) && this._buffer[this.GetIndexFromId(i)].Cleared) { num -= 1L; } } for (long j = num; j <= num2; j += 1L) { if ((this._buffer[this.GetIndexFromId(j)] != null) && !this._buffer[this.GetIndexFromId(j)].Cleared) { list.Add(this._buffer[this.GetIndexFromId(j)].Clone()); } } } else { num = (num2 + count) - 1L; if (num >= this._countEntriesAdded) { num = this._countEntriesAdded; } for (long k = num2; k <= num; k += 1L) { if (num >= this._countEntriesAdded) { break; } if ((this._buffer[this.GetIndexFromId(k)] != null) && this._buffer[this.GetIndexFromId(k)].Cleared) { num += 1L; } } for (long m = num; m >= num2; m -= 1L) { if ((this._buffer[this.GetIndexFromId(m)] != null) && !this._buffer[this.GetIndexFromId(m)].Cleared) { list.Add(this._buffer[this.GetIndexFromId(m)].Clone()); } } } } else { long num7; long num8 = 0L; if (this._capacity != 0x1000) { num8 = this.SmallestIDinBuffer(); } if (!newest.IsPresent) { num7 = 1L; if ((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) { num7 = num8; } long num9 = count - 1L; while (num9 >= 0L) { if (num7 > this._countEntriesAdded) { break; } if (((num7 <= 0L) || (this.GetIndexFromId(num7) >= this._buffer.Length)) || this._buffer[this.GetIndexFromId(num7)].Cleared) { num7 += 1L; } else { list.Add(this._buffer[this.GetIndexFromId(num7)].Clone()); num9 -= 1L; num7 += 1L; } } } else { num7 = this._countEntriesAdded; long num10 = count - 1L; while (num10 >= 0L) { if ((((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) && (num7 < num8)) || (num7 < 1L)) { break; } if (((num7 <= 0L) || (this.GetIndexFromId(num7) >= this._buffer.Length)) || this._buffer[this.GetIndexFromId(num7)].Cleared) { num7 -= 1L; } else { list.Add(this._buffer[this.GetIndexFromId(num7)].Clone()); num10 -= 1L; num7 -= 1L; } } } } HistoryInfo[] array = new HistoryInfo[list.Count]; list.CopyTo(array); return array; } }
public AddComputerCommand() { string[] strArrays = new string[1]; strArrays[0] = "localhost"; this._computerName = strArrays; this._joinOptions = JoinOptions.AccountCreate; this._restart = false; this._joinDomainflags = 1; this._shortLocalMachineName = Dns.GetHostName(); this._fullLocalMachineName = Dns.GetHostEntry("").HostName; }
public GetWmiObjectCommand() { string[] strArrays = new string[1]; strArrays[0] = "*"; this.property = strArrays; this.list = false; this.recurse = false; }
public string pgrep( SwitchParameter AllMatches , SwitchParameter CaseSensitive , Int32[] Context , string Encoding , string[] Exclude, string[] Include , PSObject InputObject , SwitchParameter List , SwitchParameter NotMatch , string[] Path , string[] Pattern , SwitchParameter Quiet, SwitchParameter SimpleMatch) //string CommonParameters) { Runspace runSpace = RunspaceFactory.CreateRunspace(); runSpace.Open(); Pipeline pipeline = runSpace.CreatePipeline(); StringBuilder param = new StringBuilder(); if (AllMatches != null) { param.Append("-AllMatches "); param.Append(AllMatches); } if(CaseSensitive != null){ param.Append("-CaseSensitive "); param.Append(CaseSensitive); } if (Context != null) { param.Append("-Context "); param.Append(Context); } if(Encoding != null){ param.Append("-Encoding "); param.Append(Encoding); } if (Exclude != null) { param.Append("-Exclude "); param.Append(Exclude); } if (Include != null) { param.Append("-Include "); param.Append(Include); } if (InputObject != null) { param.Append("-InputObject "); param.Append(InputObject); } if (List != null) { param.Append("-List "); param.Append(List); } if (NotMatch != null) { param.Append("-NotMatch "); param.Append(NotMatch); } if (Path != null) { param.Append("-Path "); param.Append(Path); } if (Pattern != null) { param.Append("-Pattern "); param.Append(Pattern); } if (Quiet != null) { param.Append("-Quiet "); param.Append(Quiet); } if (SimpleMatch != null) { param.Append("-SimpleMatch "); param.Append(SimpleMatch); } //AllMatches,CaseSensitive ,Context ,Encoding ,Exclude,Include ,InputObject ,List ,NotMatch ,Path ,Pattern ,Quiet ,SimpleMatch //string.Format(@"-AllMatches {0}, -CaseSensitive {1} ,-Context {2} ,Encoding {3},Exclude {4},Include {5},InputObject {6},List {7},NotMatch {8},Path {9},Pattern {10},Quiet {11},SimpleMatch {12}") //string CommonParameters) string pgrep = string.Format("{0} {1}", "Select-String", param); Console.WriteLine(pgrep); pipeline.Commands.AddScript(pgrep); pipeline.Commands.Add("Out-String"); Collection<PSObject> results = pipeline.Invoke(); runSpace.Close(); StringBuilder strBuilder = new StringBuilder(); foreach (PSObject obj in results) { strBuilder.AppendLine(obj.ToString()); } Console.WriteLine(strBuilder.ToString()); Console.Read(); return strBuilder.ToString(); }
public StartProcessCommand() { this._loaduserprofile = SwitchParameter.Present; }
public WSManProviderSetItemDynamicParameters() { this._concatenate = false; }
protected override void BeginProcessing() { string warning = String.Format(Properties.Resources.DeprecatedCmdlet_F2, CmdletName, @"PowerShell's built-in Microsoft.PowerShell.Management\Start-Process cmdlet"); WriteWarning(warning); if (WildcardPattern.ContainsWildcardCharacters(_fileName)) { ErrorHandler.ThrowIllegalCharsInPath(_fileName); } if (_credentials != null) { // If using credentials, NoShellExecute must be set to true _noShellExecute = true; } if (_workingDir == null) { _workingDir = SessionState.Path.CurrentFileSystemLocation.Path; } }
public RemoveComputerCommand() { this._restart = false; string[] strArrays = new string[1]; strArrays[0] = "localhost"; this._computerName = strArrays; this._workGroup = "WORKGROUP"; this._shortLocalMachineName = Dns.GetHostName(); this._fullLocalMachineName = Dns.GetHostEntry("").HostName; }
protected ScheduledJobOptionCmdletBase() { this._runElevated = false; this._hideInTaskScheduler = false; this._restartOnIdleResume = false; this._multipleInstancePolicy = TaskMultipleInstancePolicy.IgnoreNew; this._doNotAllowDemandStart = false; this._requireNetwork = false; this._stopIfGoingOffIdle = false; this._wakeToRun = false; this._continueIfGoingOnBattery = false; this._startIfOnBattery = false; this._idleTimeout = new TimeSpan(1, 0, 0); this._idleDuration = new TimeSpan(0, 10, 0); this._startIfIdle = false; }
private string GetQueryStringForOrderBy(string orderBy, SwitchParameter @descending) { if( String.IsNullOrEmpty( orderBy)) { return null; } return String.Format("$orderby={0} {1}", Uri.EscapeDataString(orderBy), @descending.IsPresent ? "desc" : "asc"); }
protected override void BeginProcessing() { this.CheckCmdletParameters(); switch (this.DriverName.ToUpper()) { case SeHelper.driverNameChrome: case SeHelper.driverNameChrome2: this.CH = true; this.DriverType = Drivers.Chrome; break; case SeHelper.driverNameFirefox: case SeHelper.driverNameFirefox2: this.FF = true; this.DriverType = Drivers.Firefox; break; case SeHelper.driverNameInternetExplorer: case SeHelper.driverNameInternetExplorer2: case SeHelper.driverNameInternetExplorer3: case SeHelper.driverNameInternetExplorer4: case SeHelper.driverNameInternetExplorer5: case SeHelper.driverNameInternetExplorer6: this.IE = true; this.DriverType = Drivers.InternetExplorer; break; default: this.WriteError( this, "Could not determine the type of driver.", "DriverType", ErrorCategory.InvalidArgument, true); break; } SeStartWebDriverCommand command = new SeStartWebDriverCommand(this); //WebDriverFactory.Container.Resolve<SeStartWebDriverCommand>(new NamedParameter("cmdlet", this)); command.Execute(); }
public WmiBaseCmdlet() { string[] strArrays = new string[1]; strArrays[0] = "localhost"; this.computerName = strArrays; this.nameSpace = "root\\cimv2"; this.impersonationLevel = ImpersonationLevel.Impersonate; this.authenticationLevel = AuthenticationLevel.Packet; this.async = false; this.throttleLimit = WmiBaseCmdlet.DEFAULT_THROTTLE_LIMIT; this._context = LocalPipeline.GetExecutionContextFromTLS(); }
public CertificateProviderDynamicParameters() { this.codeSigningCert = new SwitchParameter(); this.sslServerAuthentication = new SwitchParameter(); this.expiringInDays = -1; }
public DriveParams() { PersistentConnection = new SwitchParameter(true); }
protected override void StopProcessing() { WriteVerbose(this, "User interrupted"); this.Wait = false; }
private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) { if (cmdline == null) { if (id > 0L) { HistoryInfo entry = this.history.GetEntry(id); if ((entry == null) || (entry.Id != id)) { Exception exception = new ArgumentException(StringUtil.Format(HistoryStrings.NoHistoryForId, id)); base.WriteError(new ErrorRecord(exception, "GetHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, id)); } this.entries = this.history.GetEntries(id, (long) count, newest); } else { this.entries = this.history.GetEntries((long) 0L, (long) count, newest); } } else { WildcardPattern wildcardpattern = new WildcardPattern(cmdline, WildcardOptions.IgnoreCase); if (!this._countParamterSpecified && WildcardPattern.ContainsWildcardCharacters(cmdline)) { count = 0; } this.entries = this.history.GetEntries(wildcardpattern, (long) count, newest); } foreach (HistoryInfo info2 in this.entries) { if ((info2 != null) && !info2.Cleared) { this.history.ClearEntry(info2.Id); } } }
private object CoerceTypeAsNeeded(CommandParameterInternal argument, string parameterName, Type toType, ParameterCollectionTypeInformation collectionTypeInfo, object currentValue) { if (argument == null) { throw PSTraceSource.NewArgumentNullException("argument"); } if (toType == null) { throw PSTraceSource.NewArgumentNullException("toType"); } if (collectionTypeInfo == null) { collectionTypeInfo = new ParameterCollectionTypeInformation(toType); } object result = currentValue; using (bindingTracer.TraceScope("COERCE arg to [{0}]", new object[] { toType })) { Type c = null; try { if (IsNullParameterValue(currentValue)) { return(this.HandleNullParameterForSpecialTypes(argument, parameterName, toType, currentValue)); } c = currentValue.GetType(); if (toType.IsAssignableFrom(c)) { bindingTracer.WriteLine("Parameter and arg types the same, no coercion is needed.", new object[0]); return(currentValue); } bindingTracer.WriteLine("Trying to convert argument value from {0} to {1}", new object[] { c, toType }); if (toType == typeof(PSObject)) { if ((this.command != null) && (currentValue == this.command.CurrentPipelineObject.BaseObject)) { currentValue = this.command.CurrentPipelineObject; } bindingTracer.WriteLine("The parameter is of type [{0}] and the argument is an PSObject, so the parameter value is the argument value wrapped into an PSObject.", new object[] { toType }); return(LanguagePrimitives.AsPSObjectOrNull(currentValue)); } if ((toType == typeof(string)) && (c == typeof(PSObject))) { PSObject obj3 = (PSObject)currentValue; if (obj3 == AutomationNull.Value) { bindingTracer.WriteLine("CONVERT a null PSObject to a null string.", new object[0]); return(null); } } if (((toType == typeof(bool)) || (toType == typeof(SwitchParameter))) || (toType == typeof(bool?))) { Type type = null; if (c == typeof(PSObject)) { PSObject obj4 = (PSObject)currentValue; currentValue = obj4.BaseObject; if (currentValue is SwitchParameter) { SwitchParameter parameter = (SwitchParameter)currentValue; currentValue = parameter.IsPresent; } type = currentValue.GetType(); } else { type = c; } if (type == typeof(bool)) { if (LanguagePrimitives.IsBooleanType(toType)) { return(ParserOps.BoolToObject((bool)currentValue)); } return(new SwitchParameter((bool)currentValue)); } if (type == typeof(int)) { if (((int)LanguagePrimitives.ConvertTo(currentValue, typeof(int), CultureInfo.InvariantCulture)) != 0) { if (LanguagePrimitives.IsBooleanType(toType)) { return(ParserOps.BoolToObject(true)); } return(new SwitchParameter(true)); } if (LanguagePrimitives.IsBooleanType(toType)) { return(ParserOps.BoolToObject(false)); } return(new SwitchParameter(false)); } if (LanguagePrimitives.IsNumeric(Type.GetTypeCode(type))) { double num = (double)LanguagePrimitives.ConvertTo(currentValue, typeof(double), CultureInfo.InvariantCulture); if (num == 0.0) { if (LanguagePrimitives.IsBooleanType(toType)) { return(ParserOps.BoolToObject(false)); } return(new SwitchParameter(false)); } if (LanguagePrimitives.IsBooleanType(toType)) { return(ParserOps.BoolToObject(true)); } return(new SwitchParameter(true)); } ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { type, "" }); throw exception; } if ((collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.ICollectionGeneric) || (collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.IList)) { object obj5 = PSObject.Base(currentValue); if (obj5 != null) { ConversionRank conversionRank = LanguagePrimitives.GetConversionRank(obj5.GetType(), toType); if ((((conversionRank == ConversionRank.Constructor) || (conversionRank == ConversionRank.ImplicitCast)) || (conversionRank == ConversionRank.ExplicitCast)) && LanguagePrimitives.TryConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture, out result)) { return(result); } } } if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection) { bindingTracer.WriteLine("ENCODING arg into collection", new object[0]); bool coercionRequired = false; return(this.EncodeCollection(argument, parameterName, collectionTypeInfo, toType, currentValue, collectionTypeInfo.ElementType != null, out coercionRequired)); } if (((((GetIList(currentValue) != null) && (toType != typeof(object))) && ((toType != typeof(PSObject)) && (toType != typeof(PSListModifier)))) && ((!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(PSListModifier <>))) && (!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(FlagsExpression <>))))) && !toType.IsEnum) { throw new NotSupportedException(); } bindingTracer.WriteLine("CONVERT arg type to param type using LanguagePrimitives.ConvertTo", new object[0]); bool flag2 = false; if (this.context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { object obj6 = PSObject.Base(currentValue); bool flag3 = obj6 is PSObject; bool flag4 = (obj6 != null) && typeof(IDictionary).IsAssignableFrom(obj6.GetType()); flag2 = ((((PSLanguageMode)this.Command.CommandInfo.DefiningLanguageMode) == PSLanguageMode.FullLanguage) && !flag3) && !flag4; } try { if (flag2) { this.context.LanguageMode = PSLanguageMode.FullLanguage; } result = LanguagePrimitives.ConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture); } finally { if (flag2) { this.context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } } bindingTracer.WriteLine("CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [{0}]", new object[] { (result == null) ? "null" : result.ToString() }); return(result); } catch (NotSupportedException exception2) { bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", new object[] { (result == null) ? "null" : result, toType }); ParameterBindingException exception3 = new ParameterBindingException(exception2, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { (result == null) ? "null" : result, exception2.Message }); throw exception3; } catch (PSInvalidCastException exception4) { object[] args = new object[] { result ?? "null", toType }; bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", args); ParameterBindingException exception5 = new ParameterBindingException(exception4, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgumentNoMessage", new object[] { exception4.Message }); throw exception5; } } return(result); }