public object GetDynamicParameterObject( IDynamicParameterContext context) { if (context is null) { throw new ArgumentNullException(nameof(context)); } var rdpd = new RuntimeDefinedParameterDictionary(); foreach (var parameter in context.GetParameters()) { var descriptor = parameter.ParameterDescriptor; var attributes = new Collection <Attribute>(); foreach (var attributeData in descriptor.Attributes) { attributes.Add((Attribute)attributeData.GetInstance()); } var rdp = new RuntimeDefinedParameter( descriptor.ParameterName, descriptor.ParameterType, attributes); if (parameter.IsSet) { rdp.Value = parameter.Value; } rdpd.Add(descriptor.ParameterName, rdp); } return(rdpd); }
public object GetDynamicParameters() { if (_Collections == null) { Initialize().Wait(); } // IEnumerable<string> Collections = new string[] { "entities", "workflow_instances", "nodered", "openrpa_instances", "workflow", "users", "audit", "forms", "openrpa" }; var runtimeDefinedParameterDictionary = new RuntimeDefinedParameterDictionary(); var attrib = new Collection <Attribute>() { // Mandatory = true, new ParameterAttribute() { HelpMessage = "What collection to query, default is entities", Position = 1 }, new ValidateSetAttribute(_Collections) }; var parameter = new RuntimeDefinedParameter("Collection", typeof(string), attrib); runtimeDefinedParameterDictionary.Add("Collection", parameter); _staticStorage = runtimeDefinedParameterDictionary; return(runtimeDefinedParameterDictionary); }
public object GetDynamicParameters() { _runtimeParamsCollection = new RuntimeDefinedParameterDictionary(); if (string.IsNullOrEmpty(this.ArgumentList) == true) { return(_runtimeParamsCollection); } string[] argNames = this.ArgumentList.Split(','); foreach (string argName in argNames) { RuntimeDefinedParameter dynamicParam = new RuntimeDefinedParameter() { Name = argName, ParameterType = typeof(string), }; dynamicParam.Attributes.Add(new ParameterAttribute() { Mandatory = false }); _runtimeParamsCollection.Add(argName, dynamicParam); } return(_runtimeParamsCollection); }
private RuntimeDefinedParameter CreateCacheMemoryDynamicParameter(CacheServiceSkuType sku) { var parameter = new RuntimeDefinedParameter { Name = MemoryParameterName, ParameterType = typeof(string), }; // add the [parameter] attribute var parameterAttribute = new ParameterAttribute { Mandatory = false, }; parameter.Attributes.Add(parameterAttribute); string[] values = (new CacheSkuCountConvert(sku)).GetValueList(); parameter.Attributes.Add(new ValidateSetAttribute(values) { IgnoreCase = true }); return(parameter); }
public void ConstructsDynamicParameter() { string[] parameters = { "Name", "Location", "Mode" }; string[] parameterSetNames = { "__AllParameterSets" }; string key = "computeMode"; TemplateFileParameterV1 value = new TemplateFileParameterV1() { AllowedValues = new List <object>() { "Mode1", "Mode2", "Mode3" }, DefaultValue = "Mode1", MaxLength = "5", MinLength = "1", Type = "string" }; KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value); RuntimeDefinedParameter dynamicParameter = TemplateUtility.ConstructDynamicParameter(parameters, parameter); Assert.Equal("computeMode", dynamicParameter.Name); Assert.Equal(value.DefaultValue, dynamicParameter.Value); Assert.Equal(typeof(string), dynamicParameter.ParameterType); Assert.Equal(2, dynamicParameter.Attributes.Count); ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0]; Assert.False(parameterAttribute.Mandatory); Assert.True(parameterAttribute.ValueFromPipelineByPropertyName); Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName); ValidateLengthAttribute validateLengthAttribute = (ValidateLengthAttribute)dynamicParameter.Attributes[1]; Assert.Equal(int.Parse(value.MinLength), validateLengthAttribute.MinLength); Assert.Equal(int.Parse(value.MaxLength), validateLengthAttribute.MaxLength); }
/// <summary> /// This function is part of the IDynamicParameters interface. /// PowerShell uses it to generate parameters dynamically. /// We have to generate -ResourceType parameter dynamically because the array /// of resources that we used to validate against are not generated before compile time, /// i.e. [ValidateSet(ArrayGeneratedAtRunTime)] will throw an error for parameters /// that are not generated dynamically. /// </summary> public object GetDynamicParameters() { if (_dynamicParameters == null) { ParameterAttribute paramAttribute = new ParameterAttribute() { Mandatory = false, ParameterSetName = ParameterSetNames.NoFilter }; ValidateSetAttribute validateSetAttribute = new ValidateSetAttribute(AllResourceTypes); validateSetAttribute.IgnoreCase = true; Collection <Attribute> attributes = new Collection <Attribute>(new Attribute[] { validateSetAttribute, paramAttribute }); // This parameter can now be thought of as: // [Parameter(Mandatory = false, ParameterSetName = ParameterSetNames.NoFilter)] // [ValidateSet(validTypeValues)] // public string { get; set; } RuntimeDefinedParameter typeParameter = new RuntimeDefinedParameter("ResourceType", typeof(string), attributes); _dynamicParameters = new RuntimeDefinedParameterDictionary(); _dynamicParameters.Add("ResourceType", typeParameter); } return(_dynamicParameters); }
protected static bool AddDynamicParameter(Type type, string name, ref RuntimeDefinedParameterDictionary dic, bool valueFromPipeline, bool valueFromPipelineByPropertyName, string paramSetName, bool mandatory = false) { var paramAdded = false; if (dic == null || !dic.ContainsKey(name)) { var attrib = new ParameterAttribute { Mandatory = mandatory, ValueFromPipeline = valueFromPipeline, ValueFromPipelineByPropertyName = valueFromPipelineByPropertyName }; if (!string.IsNullOrEmpty(paramSetName)) { attrib.ParameterSetName = paramSetName; } var param = new RuntimeDefinedParameter { IsSet = false, Name = name, ParameterType = type }; param.Attributes.Add(attrib); if (dic == null) { dic = new RuntimeDefinedParameterDictionary(); } dic.Add(name, param); paramAdded = true; } return(paramAdded); }
public override object GetDynamicParameters() { base.GetDynamicParameters(); if (this.InputObject == null) { RuntimeDefinedParameter param = IBXDynamicParameters.DhcpType(true); base.ParameterDictionary.Add(param.Name, param); string RecordType = this.GetUnboundValue <string>("DhcpType"); if (!String.IsNullOrEmpty(RecordType)) { if (Enum.TryParse <InfoBloxObjectsEnum>(RecordType, out base.ObjectType)) { foreach (RuntimeDefinedParameter Param in IBXDynamicParameters.ObjectTypeProperties(base.ObjectType, new string[] { _GRID_BY_ATTRIBUTE, _SESSION_BY_ATTRIBUTE, _ENTERED_SESSION_BY_ATTRIBUTE })) { base.ParameterDictionary.Add(Param.Name, Param); } } } } return(base.ParameterDictionary); }
public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pDiskName = new RuntimeDefinedParameter(); pDiskName.Name = "DiskName"; pDiskName.ParameterType = typeof(string); pDiskName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pDiskName.Attributes.Add(new AliasAttribute("Name")); pDiskName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("DiskName", pDiskName); return(dynamicParameters); }
protected override object GetChildItemsDynamicParameters(string path, bool recurse) { // We provide an "-unread" parameter so that the user can choose to only list // unread items (and folders and feeds with unread items) WriteVerbose("GetChildItemsDynamicParameters:path = " + path); ParameterAttribute unreadAttrib = new ParameterAttribute(); unreadAttrib.Mandatory = false; unreadAttrib.ValueFromPipeline = false; RuntimeDefinedParameter unreadParam = new RuntimeDefinedParameter(); unreadParam.IsSet = false; unreadParam.Name = "Unread"; unreadParam.ParameterType = typeof(SwitchParameter); unreadParam.Attributes.Add(unreadAttrib); RuntimeDefinedParameterDictionary dic = new RuntimeDefinedParameterDictionary(); dic.Add("Unread", unreadParam); return(dic); }
protected object CreateLogAnalyticExportThrottledRequestsDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pGroupByOperationName = new RuntimeDefinedParameter(); pGroupByOperationName.Name = "GroupByOperationName"; pGroupByOperationName.ParameterType = typeof(bool?); pGroupByOperationName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = false }); pGroupByOperationName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("GroupByOperationName", pGroupByOperationName); var pFromTime = new RuntimeDefinedParameter(); pFromTime.Name = "FromTime"; pFromTime.ParameterType = typeof(DateTime); pFromTime.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = false }); pFromTime.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("FromTime", pFromTime); var pGroupByThrottlePolicy = new RuntimeDefinedParameter(); pGroupByThrottlePolicy.Name = "GroupByThrottlePolicy"; pGroupByThrottlePolicy.ParameterType = typeof(bool?); pGroupByThrottlePolicy.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false }); pGroupByThrottlePolicy.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("GroupByThrottlePolicy", pGroupByThrottlePolicy); var pBlobContainerSasUri = new RuntimeDefinedParameter(); pBlobContainerSasUri.Name = "BlobContainerSasUri"; pBlobContainerSasUri.ParameterType = typeof(string); pBlobContainerSasUri.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = false }); pBlobContainerSasUri.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("BlobContainerSasUri", pBlobContainerSasUri); var pGroupByResourceName = new RuntimeDefinedParameter(); pGroupByResourceName.Name = "GroupByResourceName"; pGroupByResourceName.ParameterType = typeof(bool?); pGroupByResourceName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 5, Mandatory = false }); pGroupByResourceName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("GroupByResourceName", pGroupByResourceName); var pToTime = new RuntimeDefinedParameter(); pToTime.Name = "ToTime"; pToTime.ParameterType = typeof(DateTime); pToTime.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 6, Mandatory = false }); pToTime.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ToTime", pToTime); var pLocation = new RuntimeDefinedParameter(); pLocation.Name = "Location"; pLocation.ParameterType = typeof(string); pLocation.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 7, Mandatory = true }); pLocation.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Location", pLocation); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 8, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return(dynamicParameters); }
protected object CreateVirtualMachineCaptureDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMName = new RuntimeDefinedParameter(); pVMName.Name = "VMName"; pVMName.ParameterType = typeof(string); pVMName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMName", pVMName); var pVhdPrefix = new RuntimeDefinedParameter(); pVhdPrefix.Name = "VhdPrefix"; pVhdPrefix.ParameterType = typeof(string); pVhdPrefix.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false }); pVhdPrefix.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VhdPrefix", pVhdPrefix); var pOverwriteVhd = new RuntimeDefinedParameter(); pOverwriteVhd.Name = "OverwriteVhd"; pOverwriteVhd.ParameterType = typeof(bool); pOverwriteVhd.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = false }); pOverwriteVhd.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("OverwriteVhd", pOverwriteVhd); var pDestinationContainerName = new RuntimeDefinedParameter(); pDestinationContainerName.Name = "DestinationContainerName"; pDestinationContainerName.ParameterType = typeof(string); pDestinationContainerName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 5, Mandatory = false }); pDestinationContainerName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("DestinationContainerName", pDestinationContainerName); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 6, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return(dynamicParameters); }
protected object CreateVirtualMachineCaptureOSImageDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pServiceName = new RuntimeDefinedParameter(); pServiceName.Name = "ServiceName"; pServiceName.ParameterType = typeof(System.String); pServiceName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pServiceName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ServiceName", pServiceName); var pDeploymentName = new RuntimeDefinedParameter(); pDeploymentName.Name = "DeploymentName"; pDeploymentName.ParameterType = typeof(System.String); pDeploymentName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pDeploymentName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("DeploymentName", pDeploymentName); var pVirtualMachineName = new RuntimeDefinedParameter(); pVirtualMachineName.Name = "VirtualMachineName"; pVirtualMachineName.ParameterType = typeof(System.String); pVirtualMachineName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pVirtualMachineName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VirtualMachineName", pVirtualMachineName); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "VirtualMachineCaptureOSImageParameters"; pParameters.ParameterType = typeof(Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineCaptureOSImageParameters); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VirtualMachineCaptureOSImageParameters", pParameters); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 5, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return(dynamicParameters); }
protected override async Task ProcessRecordAsync() { try { var CollectionRuntime = new RuntimeDefinedParameter(); _staticStorage.TryGetValue("Collection", out CollectionRuntime); string Collection = ""; if (CollectionRuntime.Value != null && !string.IsNullOrEmpty(CollectionRuntime.Value.ToString())) { Collection = CollectionRuntime.Value.ToString(); } if (string.IsNullOrEmpty(Collection)) { Collection = "entities"; } string col = Collection; if (!string.IsNullOrEmpty(Query)) { var affectedrows = await global.webSocketClient.DeleteMany(col, Query); WriteVerbose("Removed " + affectedrows + " rows from " + col); return; } if (Objects != null && Objects.Count > 0) { var colls = new Dictionary <string, List <string> >(); foreach (PSObject obj in Objects) { col = Collection; if (obj.Properties["__pscollection"] != null && obj.Properties["__pscollection"].Value != null) { col = obj.Properties["__pscollection"].Value.ToString(); } if (!colls.ContainsKey(col)) { colls.Add(col, new List <string>()); } Id = obj.Properties["_id"].Value.ToString(); colls[col].Add(Id); } foreach (var kv in colls) { var affectedrows = await global.webSocketClient.DeleteMany(kv.Key, kv.Value.ToArray()); WriteVerbose("Removed " + affectedrows + " rows from " + col); } return; } if (!string.IsNullOrEmpty(json)) { JObject tmpObject = JObject.Parse(json); if (string.IsNullOrEmpty(col)) // If not overwriten by param, then check for old collection { if (tmpObject.ContainsKey("__pscollection")) { col = tmpObject.Value <string>("__pscollection"); } else { col = "entities"; } } Id = tmpObject.Value <string>("_id"); } if (string.IsNullOrEmpty(col)) { Id = null; WriteError(new ErrorRecord(new ArgumentException("Collection is mandatory when not using objects"), "", ErrorCategory.InvalidArgument, null)); return; } WriteVerbose("Removing " + Id + " from " + col); await global.webSocketClient.DeleteOne(col, Id); Id = null; } catch (Exception ex) { WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null)); Id = null; } }
protected object CreateDiskGrantAccessDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pDiskName = new RuntimeDefinedParameter(); pDiskName.Name = "DiskName"; pDiskName.ParameterType = typeof(string); pDiskName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pDiskName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("DiskName", pDiskName); var pAccess = new RuntimeDefinedParameter(); pAccess.Name = "Access"; pAccess.ParameterType = typeof(string); pAccess.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false }); pAccess.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Access", pAccess); var pDurationInSecond = new RuntimeDefinedParameter(); pDurationInSecond.Name = "DurationInSecond"; pDurationInSecond.ParameterType = typeof(int); pDurationInSecond.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = false }); pDurationInSecond.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("DurationInSecond", pDurationInSecond); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 5, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return(dynamicParameters); }
protected object CreateVirtualMachineScaleSetVMUpdateDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceId = new RuntimeDefinedParameter(); pInstanceId.Name = "InstanceId"; pInstanceId.ParameterType = typeof(string); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pInstanceId.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceId); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "VirtualMachineScaleSetVMUpdate"; pParameters.ParameterType = typeof(VirtualMachineScaleSetVM); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VirtualMachineScaleSetVMUpdate", pParameters); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 5, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return(dynamicParameters); }
protected override async Task ProcessRecordAsync() { try { var CollectionRuntime = new RuntimeDefinedParameter(); _staticStorage.TryGetValue("Collection", out CollectionRuntime); string Collection = "entities"; if (CollectionRuntime.Value != null && !string.IsNullOrEmpty(CollectionRuntime.Value.ToString())) { Collection = CollectionRuntime.Value.ToString(); } // if (Top == 0) Top = 100; JObject q = null; string json = ""; try { q = JObject.Parse(Query); json = q.ToString(); } catch (Exception) { } if (string.IsNullOrEmpty(json) && Query != null) { Query = Query.Trim(); if (!Query.StartsWith("{") && !Query.EndsWith("}")) { Query = "{" + Query + "}"; } q = JObject.Parse(Query); json = q.ToString(); } if (!string.IsNullOrEmpty(Type)) { if (q == null) { q = JObject.Parse("{}"); } q["_type"] = Type; json = q.ToString(); } var entities = await global.webSocketClient.Query <JObject>(Collection, json, Projection, Top, Skip, Orderby, QueryAs); // var results = new List<PSObject>(); int index = 0; foreach (var entity in entities) { if (entity.ContainsKey("name")) { WriteVerbose("Parsing " + entity.Value <string>("_id") + " " + entity.Value <string>("name")); } else { WriteVerbose("Parsing " + entity.Value <string>("_id")); } entity["__pscollection"] = Collection; var obj = entity.toPSObject(); //var display = new PSPropertySet("DefaultDisplayPropertySet", new[] { "name", "_type", "_createdby", "_created" }); //var mi = new PSMemberSet("PSStandardMembers", new[] { display }); //obj.Members.Add(mi); obj.TypeNames.Insert(0, "OpenRPA.PS.Entity"); if (Collection == "openrpa") { if (entity.Value <string>("_type") == "workflow") { obj.TypeNames.Insert(0, "OpenRPA.Workflow"); } if (entity.Value <string>("_type") == "project") { obj.TypeNames.Insert(0, "OpenRPA.Project"); } if (entity.Value <string>("_type") == "detector") { obj.TypeNames.Insert(0, "OpenRPA.Detector"); } if (entity.Value <string>("_type") == "unattendedclient") { obj.TypeNames.Insert(0, "OpenRPA.UnattendedClient"); } if (entity.Value <string>("_type") == "unattendedserver") { obj.TypeNames.Insert(0, "OpenRPA.UnattendedServer"); } } else if (Collection == "files") { obj.TypeNames.Insert(0, "OpenRPA.File"); } // results.Add(obj); WriteObject(obj); index++; if (index % 10 == 9) { await Task.Delay(1); } } // WriteObject(results, true); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null)); } }
private bool PrepareCommandElements(ExecutionContext context) { int num = 0; bool dotSource = this._commandAst.InvocationOperator == TokenKind.Dot; CommandProcessorBase base2 = null; string resolvedCommandName = null; bool flag2 = false; try { base2 = this.PrepareFromAst(context, out resolvedCommandName) ?? context.CreateCommand(resolvedCommandName, dotSource); } catch (RuntimeException exception) { CommandProcessorBase.CheckForSevereException(exception); if ((this._commandAst.IsInWorkflow() && (resolvedCommandName != null)) && CompletionCompleters.PseudoWorkflowCommands.Contains <string>(resolvedCommandName, StringComparer.OrdinalIgnoreCase)) { flag2 = true; } else { return(false); } } CommandProcessor commandProcessor = base2 as CommandProcessor; ScriptCommandProcessorBase base3 = base2 as ScriptCommandProcessorBase; bool flag3 = (commandProcessor != null) && commandProcessor.CommandInfo.ImplementsDynamicParameters; List <object> list = flag3 ? new List <object>(this._commandElements.Count) : null; if (((commandProcessor != null) || (base3 != null)) || flag2) { num++; while (num < this._commandElements.Count) { CommandParameterAst parameterAst = this._commandElements[num] as CommandParameterAst; if (parameterAst != null) { if (list != null) { list.Add(parameterAst.Extent.Text); } AstPair item = (parameterAst.Argument != null) ? new AstPair(parameterAst, parameterAst.Argument) : new AstPair(parameterAst); this._arguments.Add(item); } else { StringConstantExpressionAst ast2 = this._commandElements[num] as StringConstantExpressionAst; if ((ast2 == null) || !ast2.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { ExpressionAst argumentAst = this._commandElements[num] as ExpressionAst; if (argumentAst != null) { if (list != null) { list.Add(argumentAst.Extent.Text); } this._arguments.Add(new AstPair(null, argumentAst)); } } } num++; } } if (commandProcessor != null) { this._function = false; if (flag3) { ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, list.ToArray()); bool flag4 = false; bool flag5 = false; do { CommandProcessorBase currentCommandProcessor = context.CurrentCommandProcessor; try { context.CurrentCommandProcessor = commandProcessor; commandProcessor.SetCurrentScopeToExecutionScope(); if (!flag4) { commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(commandProcessor.arguments); } else { flag5 = true; commandProcessor.CmdletParameterBinderController.ClearUnboundArguments(); commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(new Collection <CommandParameterInternal>()); } } catch (ParameterBindingException exception2) { if ((exception2.ErrorId == "MissingArgument") || (exception2.ErrorId == "AmbiguousParameter")) { flag4 = true; } } catch (Exception exception3) { CommandProcessorBase.CheckForSevereException(exception3); } finally { context.CurrentCommandProcessor = currentCommandProcessor; commandProcessor.RestorePreviousScope(); } }while (flag4 && !flag5); } this._commandInfo = commandProcessor.CommandInfo; this._commandName = commandProcessor.CommandInfo.Name; this._bindableParameters = commandProcessor.CmdletParameterBinderController.BindableParameters; this._defaultParameterSetFlag = commandProcessor.CommandInfo.CommandMetadata.DefaultParameterSetFlag; } else if (base3 != null) { this._function = true; this._commandInfo = base3.CommandInfo; this._commandName = base3.CommandInfo.Name; this._bindableParameters = base3.ScriptParameterBinderController.BindableParameters; this._defaultParameterSetFlag = 0; } else if (!flag2) { return(false); } if (this._commandAst.IsInWorkflow()) { Type type = Type.GetType("Microsoft.PowerShell.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); if (type != null) { Dictionary <string, Type> dictionary = (Dictionary <string, Type>)type.GetMethod("GetActivityParameters").Invoke(null, new object[] { this._commandAst }); if (dictionary != null) { bool flag6 = dictionary.ContainsKey("PSComputerName") && !dictionary.ContainsKey("ComputerName"); List <MergedCompiledCommandParameter> source = new List <MergedCompiledCommandParameter>(); Collection <Attribute> attributes = new Collection <Attribute> { new ParameterAttribute() }; foreach (KeyValuePair <string, Type> pair2 in dictionary) { if (flag2 || !this._bindableParameters.BindableParameters.ContainsKey(pair2.Key)) { Type actualActivityParameterType = GetActualActivityParameterType(pair2.Value); RuntimeDefinedParameter runtimeDefinedParameter = new RuntimeDefinedParameter(pair2.Key, actualActivityParameterType, attributes); CompiledCommandParameter parameter = new CompiledCommandParameter(runtimeDefinedParameter, false) { IsInAllSets = true }; MergedCompiledCommandParameter parameter3 = new MergedCompiledCommandParameter(parameter, ParameterBinderAssociation.DeclaredFormalParameters); source.Add(parameter3); } } if (source.Any <MergedCompiledCommandParameter>()) { MergedCommandParameterMetadata metadata = new MergedCommandParameterMetadata(); if (!flag2) { metadata.ReplaceMetadata(this._bindableParameters); } foreach (MergedCompiledCommandParameter parameter5 in source) { metadata.BindableParameters.Add(parameter5.Parameter.Name, parameter5); } this._bindableParameters = metadata; } foreach (string str2 in ignoredWorkflowParameters) { if (this._bindableParameters.BindableParameters.ContainsKey(str2)) { this._bindableParameters.BindableParameters.Remove(str2); } } if (this._bindableParameters.BindableParameters.ContainsKey("ComputerName") && flag6) { this._bindableParameters.BindableParameters.Remove("ComputerName"); string key = (from aliasPair in this._bindableParameters.AliasedParameters where string.Equals("ComputerName", aliasPair.Value.Parameter.Name) select aliasPair.Key).FirstOrDefault <string>(); this._bindableParameters.AliasedParameters.Remove(key); } } } } this._unboundParameters.AddRange(this._bindableParameters.BindableParameters.Values); CommandBaseAst ast4 = null; PipelineAst parent = this._commandAst.Parent as PipelineAst; if (parent.PipelineElements.Count > 1) { foreach (CommandBaseAst ast6 in parent.PipelineElements) { if (ast6.GetHashCode() == this._commandAst.GetHashCode()) { this._isPipelineInputExpected = ast4 != null; if (this._isPipelineInputExpected) { this._pipelineInputType = typeof(object); } break; } ast4 = ast6; } } return(true); }
/// <summary> /// Adds http error action parameters to PowerShell. /// </summary> /// <param name="create">true if parameters added for create scenario and false for update scenario.</param> /// <returns>PowerShell parameters.</returns> internal RuntimeDefinedParameterDictionary AddHttpErrorActionParameters(bool create = true) { var errorActionMethodAttributes = new Collection <Attribute> { new ParameterAttribute { Mandatory = create ? true : false, HelpMessage = "The Method for Http and Https Action types (GET, PUT, POST, HEAD or DELETE).", }, new ValidateSetAttribute(Constants.HttpMethodGET, Constants.HttpMethodPUT, Constants.HttpMethodPOST, Constants.HttpMethodDELETE) { IgnoreCase = true, } }; var errorActionUriAttributes = new Collection <Attribute> { new ParameterAttribute { Mandatory = create ? true : false, HelpMessage = "The Uri for error job action.", }, new ValidateNotNullOrEmptyAttribute() }; var errorActionRequestBodyAttributes = new Collection <Attribute> { new ParameterAttribute { Mandatory = false, HelpMessage = "The Body for PUT and POST job actions.", }, new ValidateNotNullOrEmptyAttribute() }; var errorActionHeadersAttributes = new Collection <Attribute> { new ParameterAttribute { Mandatory = false, HelpMessage = "The header collection." }, new ValidateNotNullOrEmptyAttribute() }; var errorActionHttpAuthenticationTypeAttributes = new Collection <Attribute> { new ParameterAttribute { Mandatory = false, HelpMessage = "The Http Authentication type." }, new ValidateSetAttribute(Constants.HttpAuthenticationNone, Constants.HttpAuthenticationClientCertificate, Constants.HttpAuthenticationActiveDirectoryOAuth, Constants.HttpAuthenticationBasic) { IgnoreCase = true } }; this._errorActionMethod = new RuntimeDefinedParameter("ErrorActionMethod", typeof(string), errorActionMethodAttributes); this._errorActionUri = new RuntimeDefinedParameter("ErrorActionUri", typeof(Uri), errorActionUriAttributes); this._errorActionRequestBody = new RuntimeDefinedParameter("ErrorActionRequestBody", typeof(string), errorActionRequestBodyAttributes); this._errorActionHeaders = new RuntimeDefinedParameter("ErrorActionHeaders", typeof(Hashtable), errorActionHeadersAttributes); this._errorActionHttpAuthenticationType = new RuntimeDefinedParameter("ErrorActionHttpAuthenticationType", typeof(string), errorActionHttpAuthenticationTypeAttributes); var runtimeDefinedParameterDictionary = new RuntimeDefinedParameterDictionary(); runtimeDefinedParameterDictionary.Add("ErrorActionMethod", this._errorActionMethod); runtimeDefinedParameterDictionary.Add("ErrorActionUri", this._errorActionUri); runtimeDefinedParameterDictionary.Add("ErrorActionRequestBody", this._errorActionRequestBody); runtimeDefinedParameterDictionary.Add("ErrorActionHeaders", this._errorActionHeaders); runtimeDefinedParameterDictionary.Add("ErrorActionHttpAuthenticationType", this._errorActionHttpAuthenticationType); runtimeDefinedParameterDictionary.AddRange(this.AddHttpErrorActionClientCertificateAuthenticationTypeParameters()); runtimeDefinedParameterDictionary.AddRange(this.AddHttpErrorActionBasicAuthenticationTypeParameters()); runtimeDefinedParameterDictionary.AddRange(this.AddHttpErrorActionActiveDirectoryOAuthAuthenticationTypeParameters()); return(runtimeDefinedParameterDictionary); }
private bool PrepareCommandElements(ExecutionContext context) { int commandIndex = 0; bool dotSource = _commandAst.InvocationOperator == TokenKind.Dot; CommandProcessorBase processor = null; string commandName = null; bool psuedoWorkflowCommand = false; try { processor = PrepareFromAst(context, out commandName) ?? context.CreateCommand(commandName, dotSource); } catch (RuntimeException rte) { // Failed to create the CommandProcessor; CommandProcessorBase.CheckForSevereException(rte); if (_commandAst.IsInWorkflow() && commandName != null && CompletionCompleters.PseudoWorkflowCommands.Contains(commandName, StringComparer.OrdinalIgnoreCase)) { psuedoWorkflowCommand = true; } else { return false; } } var commandProcessor = processor as CommandProcessor; var scriptProcessor = processor as ScriptCommandProcessorBase; bool implementsDynamicParameters = commandProcessor != null && commandProcessor.CommandInfo.ImplementsDynamicParameters; var argumentsToGetDynamicParameters = implementsDynamicParameters ? new List<object>(_commandElements.Count) : null; if (commandProcessor != null || scriptProcessor != null || psuedoWorkflowCommand) { // Pre-processing the arguments -- command arguments for (commandIndex++; commandIndex < _commandElements.Count; commandIndex++) { var parameter = _commandElements[commandIndex] as CommandParameterAst; if (parameter != null) { if (argumentsToGetDynamicParameters != null) { argumentsToGetDynamicParameters.Add(parameter.Extent.Text); } AstPair parameterArg = parameter.Argument != null ? new AstPair(parameter) : new AstPair(parameter, (ExpressionAst)null); _arguments.Add(parameterArg); } else { var dash = _commandElements[commandIndex] as StringConstantExpressionAst; if (dash != null && dash.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { // "-" is represented by StringConstantExpressionAst. Most likely the user type a tab here, // and we don't want it be treated as an argument continue; } var expressionArgument = _commandElements[commandIndex] as ExpressionAst; if (expressionArgument != null) { if (argumentsToGetDynamicParameters != null) { argumentsToGetDynamicParameters.Add(expressionArgument.Extent.Text); } _arguments.Add(new AstPair(null, expressionArgument)); } } } } if (commandProcessor != null) { _function = false; if (implementsDynamicParameters) { ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, argumentsToGetDynamicParameters.ToArray()); bool retryWithNoArgs = false, alreadyRetried = false; do { CommandProcessorBase oldCurrentCommandProcessor = context.CurrentCommandProcessor; try { context.CurrentCommandProcessor = commandProcessor; commandProcessor.SetCurrentScopeToExecutionScope(); // Run method "BindCommandLineParametersNoValidation" to get all available parameters, including the dynamic // parameters (some of them, not necessarilly all. Since we don't do the actual binding, some dynamic parameters // might not be retrieved). if (!retryWithNoArgs) { // Win8 345299: First try with all unbounded arguments commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(commandProcessor.arguments); } else { // Win8 345299: If the first try ended with ParameterBindingException, try again with no arguments alreadyRetried = true; commandProcessor.CmdletParameterBinderController.ClearUnboundArguments(); commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(new Collection<CommandParameterInternal>()); } } catch (ParameterBindingException e) { // Catch the parameter binding exception thrown when Reparsing the argument. // "MissingArgument" - a single parameter is matched, but no argument is present // "AmbiguousParameter" - multiple parameters are matched // When such exceptions are caught, retry again without arguments, so as to get dynamic parameters // based on the current provider if (e.ErrorId == "MissingArgument" || e.ErrorId == "AmbiguousParameter") retryWithNoArgs = true; } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); } finally { context.CurrentCommandProcessor = oldCurrentCommandProcessor; commandProcessor.RestorePreviousScope(); } } while (retryWithNoArgs && !alreadyRetried); } // Get all bindable parameters and initialize the _unboundParameters _commandInfo = commandProcessor.CommandInfo; _commandName = commandProcessor.CommandInfo.Name; _bindableParameters = commandProcessor.CmdletParameterBinderController.BindableParameters; _defaultParameterSetFlag = commandProcessor.CommandInfo.CommandMetadata.DefaultParameterSetFlag; } else if (scriptProcessor != null) { _function = true; _commandInfo = scriptProcessor.CommandInfo; _commandName = scriptProcessor.CommandInfo.Name; _bindableParameters = scriptProcessor.ScriptParameterBinderController.BindableParameters; _defaultParameterSetFlag = 0; } else if (!psuedoWorkflowCommand) { // The command is not a function, cmdlet and script cmdlet return false; } if (_commandAst.IsInWorkflow()) { var converterType = Type.GetType(Utils.WorkflowType); if (converterType != null) { var activityParameters = (Dictionary<string, Type>)converterType.GetMethod("GetActivityParameters").Invoke(null, new object[] { _commandAst }); if (activityParameters != null) { bool needToRemoveReplacedProperty = activityParameters.ContainsKey("PSComputerName") && !activityParameters.ContainsKey("ComputerName"); var parametersToAdd = new List<MergedCompiledCommandParameter>(); var attrCollection = new Collection<Attribute> { new ParameterAttribute() }; foreach (var pair in activityParameters) { if (psuedoWorkflowCommand || !_bindableParameters.BindableParameters.ContainsKey(pair.Key)) { Type parameterType = GetActualActivityParameterType(pair.Value); var runtimeDefinedParameter = new RuntimeDefinedParameter(pair.Key, parameterType, attrCollection); var compiledCommandParameter = new CompiledCommandParameter(runtimeDefinedParameter, false) { IsInAllSets = true }; var mergedCompiledCommandParameter = new MergedCompiledCommandParameter(compiledCommandParameter, ParameterBinderAssociation.DeclaredFormalParameters); parametersToAdd.Add(mergedCompiledCommandParameter); } } if (parametersToAdd.Any()) { var mergedBindableParameters = new MergedCommandParameterMetadata(); if (!psuedoWorkflowCommand) { mergedBindableParameters.ReplaceMetadata(_bindableParameters); } foreach (var p in parametersToAdd) { mergedBindableParameters.BindableParameters.Add(p.Parameter.Name, p); } _bindableParameters = mergedBindableParameters; } // Remove common parameters that are supported by all commands, but not // by workflows bool fixedReadOnly = false; foreach (var ignored in _ignoredWorkflowParameters) { if (_bindableParameters.BindableParameters.ContainsKey(ignored)) { // However, some ignored parameters are explicitly implemented by // activities, so keep them. if (!activityParameters.ContainsKey(ignored)) { if (!fixedReadOnly) { _bindableParameters.ResetReadOnly(); fixedReadOnly = true; } _bindableParameters.BindableParameters.Remove(ignored); } } } if (_bindableParameters.BindableParameters.ContainsKey("ComputerName") && needToRemoveReplacedProperty) { if (!fixedReadOnly) { _bindableParameters.ResetReadOnly(); fixedReadOnly = true; } _bindableParameters.BindableParameters.Remove("ComputerName"); string aliasOfComputerName = (from aliasPair in _bindableParameters.AliasedParameters where String.Equals("ComputerName", aliasPair.Value.Parameter.Name) select aliasPair.Key).FirstOrDefault(); if (aliasOfComputerName != null) { _bindableParameters.AliasedParameters.Remove(aliasOfComputerName); } } } } } _unboundParameters.AddRange(_bindableParameters.BindableParameters.Values); // Pre-processing the arguments -- pipeline input // Check if there is pipeline input CommandBaseAst preCmdBaseAst = null; var pipe = _commandAst.Parent as PipelineAst; Diagnostics.Assert(pipe != null, "CommandAst should has a PipelineAst parent"); if (pipe.PipelineElements.Count > 1) { foreach (CommandBaseAst cmdBase in pipe.PipelineElements) { if (cmdBase.GetHashCode() == _commandAst.GetHashCode()) { _isPipelineInputExpected = preCmdBaseAst != null; if (_isPipelineInputExpected) _pipelineInputType = typeof(object); break; } preCmdBaseAst = cmdBase; } } return true; }
protected object CreateVirtualMachineDiskGetDataDiskDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pServiceName = new RuntimeDefinedParameter(); pServiceName.Name = "ServiceName"; pServiceName.ParameterType = typeof(System.String); pServiceName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pServiceName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ServiceName", pServiceName); var pDeploymentName = new RuntimeDefinedParameter(); pDeploymentName.Name = "DeploymentName"; pDeploymentName.ParameterType = typeof(System.String); pDeploymentName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pDeploymentName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("DeploymentName", pDeploymentName); var pRoleName = new RuntimeDefinedParameter(); pRoleName.Name = "RoleName"; pRoleName.ParameterType = typeof(System.String); pRoleName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pRoleName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("RoleName", pRoleName); var pLogicalUnitNumber = new RuntimeDefinedParameter(); pLogicalUnitNumber.Name = "LogicalUnitNumber"; pLogicalUnitNumber.ParameterType = typeof(System.Int32); pLogicalUnitNumber.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = true }); pLogicalUnitNumber.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("LogicalUnitNumber", pLogicalUnitNumber); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 5, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return(dynamicParameters); }
public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new AliasAttribute("Name")); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceId = new RuntimeDefinedParameter(); pInstanceId.Name = "InstanceId"; pInstanceId.ParameterType = typeof(string); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pInstanceId.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceId); var pReimage = new RuntimeDefinedParameter(); pReimage.Name = "Reimage"; pReimage.ParameterType = typeof(SwitchParameter); pReimage.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = true }); pReimage.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Reimage", pReimage); var pReimageAll = new RuntimeDefinedParameter(); pReimageAll.Name = "ReimageAll"; pReimageAll.ParameterType = typeof(SwitchParameter); pReimageAll.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 4, Mandatory = true }); pReimageAll.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ReimageAll", pReimageAll); return(dynamicParameters); }
/// <summary> /// Generate a runtime parameter with ValidateSet matching the current context /// </summary> /// <param name="name">The name of the parameter</param> /// <param name="runtimeParameter">The returned runtime parameter for context, with appropriate validate set</param> /// <returns>True if one or more contexts were found, otherwise false</returns> protected bool TryGetExistingContextNameParameter(string name, string parameterSetName, out RuntimeDefinedParameter runtimeParameter) { var result = false; var profile = DefaultProfile as AzureRmProfile; runtimeParameter = null; if (profile != null && profile.Contexts != null && profile.Contexts.Any()) { runtimeParameter = new RuntimeDefinedParameter( name, typeof(string), new Collection <Attribute>() { new ParameterAttribute { Position = 0, Mandatory = true, HelpMessage = "The name of the context", ParameterSetName = parameterSetName }, new ValidateSetAttribute(profile.Contexts.Keys.ToArray()) } ); result = true; } return(result); }
public object GetDynamicParameters() { try { callcount++; if (_Collections == null) { Initialize().Wait(5000); } if (global.webSocketClient == null || !global.webSocketClient.isConnected || global.webSocketClient.user == null) { return(new RuntimeDefinedParameterDictionary()); } RuntimeDefinedParameter targetnameparameter = null; RuntimeDefinedParameter workflownameparameter = null; if (_robots == null) { WriteStatus("Getting possible robots and roles"); _robots = global.webSocketClient.Query <apiuser>("users", "{\"$or\":[ {\"_type\": \"user\"}, {\"_type\": \"role\", \"rparole\": true} ]}", top: 2000).Result; } var TargetName = this.GetUnboundValue <string>("TargetName"); if (_staticStorage != null) { _staticStorage.TryGetValue("TargetName", out targetnameparameter); _staticStorage.TryGetValue("WorkflowName", out workflownameparameter); //WriteStatus(2, "targetname: " + targetnameparameter.Value + " workflowname: " + workflownameparameter.Value + " test: " + TargetName + " "); //WriteStatus(1, "targetname: " + targetnameparameter.IsSet + " workflowname: " + workflownameparameter.IsSet + " "); } else { var robotnames = _robots.Select(x => x.name).ToArray(); var targetnameattr = new Collection <Attribute>() { new ParameterAttribute() { HelpMessage = "Targer username or group name", Position = 1 }, new ValidateSetAttribute(robotnames) }; targetnameparameter = new RuntimeDefinedParameter("TargetName", typeof(string), targetnameattr); var runtimeDefinedParameterDictionary = new RuntimeDefinedParameterDictionary(); runtimeDefinedParameterDictionary.Add("TargetName", targetnameparameter); _staticStorage = runtimeDefinedParameterDictionary; } apiuser robot = null; string targetid = TargetId; if (targetnameparameter.Value != null) { TargetName = targetnameparameter.Value.ToString(); } if (!string.IsNullOrEmpty(TargetName)) { robot = _robots.Where(x => x.name == TargetName).FirstOrDefault(); if (robot != null) { targetid = robot._id; } } else if (!string.IsNullOrEmpty(targetid)) { robot = _robots.Where(x => x._id == targetid).FirstOrDefault(); } if ((_workflows == null || lasttargetid != targetid) && robot != null) { WriteStatus("Getting possible workflows for " + robot.name); _workflows = global.webSocketClient.Query <workflow>("openrpa", "{_type: 'workflow'}", projection: "{\"projectandname\": 1}", queryas: targetid, top: 2000).Result; lasttargetid = targetid; } int wflen = 0; if (_workflows != null) { wflen = _workflows.Length; } if (robot != null) { WriteStatus("(" + callcount + ") robots: " + _robots.Length + " workflows: " + wflen + " for " + robot.name); } else { WriteStatus("(" + callcount + ") robots: " + _robots.Length + " workflows: " + wflen); } if (workflownameparameter == null) { var workflownameattr = new Collection <Attribute>() { new ParameterAttribute() { HelpMessage = "Workflow name", Position = 2 } }; workflownameparameter = new RuntimeDefinedParameter("WorkflowName", typeof(string), workflownameattr); _staticStorage.Add("WorkflowName", workflownameparameter); } if (workflownameparameter != null) { ValidateSetAttribute wfname = (ValidateSetAttribute)workflownameparameter.Attributes.Where(x => x.GetType() == typeof(ValidateSetAttribute)).FirstOrDefault(); if (wfname != null) { workflownameparameter.Attributes.Remove(wfname); } if (_workflows != null && _workflows.Length > 0) { var workflownames = _workflows.Select(x => x.ProjectAndName).ToArray(); wfname = new ValidateSetAttribute(workflownames); workflownameparameter.Attributes.Add(wfname); } } return(_staticStorage); } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(ex.Message); throw; } }
protected object CreateDeploymentListEventsDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pServiceName = new RuntimeDefinedParameter(); pServiceName.Name = "ServiceName"; pServiceName.ParameterType = typeof(System.String); pServiceName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pServiceName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ServiceName", pServiceName); var pDeploymentName = new RuntimeDefinedParameter(); pDeploymentName.Name = "DeploymentName"; pDeploymentName.ParameterType = typeof(System.String); pDeploymentName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pDeploymentName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("DeploymentName", pDeploymentName); var pStartTime = new RuntimeDefinedParameter(); pStartTime.Name = "StartTime"; pStartTime.ParameterType = typeof(System.DateTime); pStartTime.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pStartTime.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("StartTime", pStartTime); var pEndTime = new RuntimeDefinedParameter(); pEndTime.Name = "EndTime"; pEndTime.ParameterType = typeof(System.DateTime); pEndTime.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = true }); pEndTime.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("EndTime", pEndTime); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 5, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return(dynamicParameters); }
private static RuntimeDefinedParameter GetRuntimeDefinedParameter(ParameterAst parameterAst, ref bool customParameterSet, ref bool usesCmdletBinding) { List<Attribute> attributes = new List<Attribute>(); bool hasParameterAttribute = false; for (int index = 0; index < parameterAst.Attributes.Count; index++) { var attributeAst = parameterAst.Attributes[index]; var attribute = attributeAst.GetAttribute(); attributes.Add(attribute); var parameterAttribute = attribute as ParameterAttribute; if (parameterAttribute != null) { hasParameterAttribute = true; usesCmdletBinding = true; if (parameterAttribute.Position != int.MinValue || !parameterAttribute.ParameterSetName.Equals(ParameterAttribute.AllParameterSets, StringComparison.OrdinalIgnoreCase)) { customParameterSet = true; } } } attributes.Reverse(); if (!hasParameterAttribute) { attributes.Insert(0, new ParameterAttribute()); } var result = new RuntimeDefinedParameter(parameterAst.Name.VariablePath.UserPath, parameterAst.StaticType, new Collection<Attribute>(attributes.ToArray())); if (parameterAst.DefaultValue != null) { object constantValue; if (IsConstantValueVisitor.IsConstant(parameterAst.DefaultValue, out constantValue)) { result.Value = constantValue; } else { // Expression isn't constant, create a wrapper that holds the ast, and if necessary, // will cache a delegate to evaluate the default value. result.Value = new DefaultValueExpressionWrapper { Expression = parameterAst.DefaultValue }; } } else { object defaultValue; if (TryGetDefaultParameterValue(parameterAst.StaticType, out defaultValue) && defaultValue != null) { // Skip setting the value when defaultValue is null because if we do call the setter, // we'll try converting null to the parameter, which we might not want, e.g. if the parameter is [ref]. result.Value = defaultValue; } } return result; }
protected override async Task ProcessRecordAsync() { try { RuntimeDefinedParameter targetnameparameter = null; RuntimeDefinedParameter workflownameparameter = null; if (_staticStorage != null) { _staticStorage.TryGetValue("TargetName", out targetnameparameter); _staticStorage.TryGetValue("WorkflowName", out workflownameparameter); } apiuser robot = null; string targetid = TargetId; workflow workflow; string workflowid = WorkflowId; if (targetnameparameter != null && targetnameparameter.Value != null) { targetid = targetnameparameter.Value.ToString(); } if (!string.IsNullOrEmpty(targetid)) { robot = (_robots == null?null: _robots.Where(x => x.name == targetid).FirstOrDefault()); if (robot != null) { targetid = robot._id; } } if (_Collections == null) { Initialize().Wait(); } if (_workflows == null && robot != null) { _workflows = await global.webSocketClient.Query <workflow>("openrpa", "{_type: 'workflow'}", projection : "{\"projectandname\": 1}", queryas : robot._id, top : 2000); } if (workflownameparameter != null && workflownameparameter.Value != null) { workflow = _workflows.Where(x => x.ProjectAndName == workflownameparameter.Value.ToString()).FirstOrDefault(); if (workflow != null) { workflowid = workflow._id; } } if (string.IsNullOrEmpty(targetid)) { WriteError(new ErrorRecord(new Exception("Missing robot name or robot id"), "", ErrorCategory.NotSpecified, null)); return; } robot = (_robots == null ? null: _robots.Where(x => x._id == targetid).FirstOrDefault()); if (string.IsNullOrEmpty(workflowid)) { WriteError(new ErrorRecord(new Exception("Missing workflow name or workflow id"), "", ErrorCategory.NotSpecified, null)); return; } _staticStorage = null; callcount = 0; workflow = (_workflows == null?null : _workflows.Where(x => x._id == workflowid).FirstOrDefault()); if (Object != null) { json = Object.toJson(); } if (string.IsNullOrEmpty(json)) { json = "{}"; } await RegisterQueue(); JObject tmpObject = JObject.Parse(json); correlationId = Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", ""); if (global.webSocketClient != null) { global.webSocketClient.OnQueueMessage += WebSocketClient_OnQueueMessage; } IDictionary <string, object> _robotcommand = new System.Dynamic.ExpandoObject(); _robotcommand["workflowid"] = workflowid; _robotcommand["command"] = "invoke"; _robotcommand.Add("data", tmpObject); if (robot != null) { WriteProgress(new ProgressRecord(0, "Invoking", "Invoking " + workflow.ProjectAndName + " on " + robot.name + "(" + robot.username + ")")); } if (robot == null) { WriteProgress(new ProgressRecord(0, "Invoking", "Invoking " + workflowid + " on " + targetid)); } var result = await global.webSocketClient.QueueMessage(targetid, _robotcommand, psqueue, correlationId); workItemsWaiting.WaitOne(); WriteProgress(new ProgressRecord(0, "Invoking", "completed") { RecordType = ProgressRecordType.Completed }); if (command.command == "invokefailed" || command.command == "invokeaborted") { var _ex = new Exception("Invoke failed"); if (command.data != null && !string.IsNullOrEmpty(command.data.ToString())) { try { _ex = Newtonsoft.Json.JsonConvert.DeserializeObject <Exception>(command.data.ToString()); } catch (Exception) { } } WriteError(new ErrorRecord(_ex, "", ErrorCategory.NotSpecified, null)); return; } if (command.data != null && !string.IsNullOrEmpty(command.data.ToString())) { var payload = JObject.Parse(command.data.ToString()); var _result = payload.toPSObject(); WriteObject(_result); } } catch (Exception ex) { WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null)); WriteProgress(new ProgressRecord(0, "Invoking", "completed") { RecordType = ProgressRecordType.Completed }); } }
protected override async Task ProcessRecordAsync() { try { var CollectionRuntime = new RuntimeDefinedParameter(); _staticStorage.TryGetValue("Collection", out CollectionRuntime); string Collection = ""; if (CollectionRuntime.Value != null && !string.IsNullOrEmpty(CollectionRuntime.Value.ToString())) { Collection = CollectionRuntime.Value.ToString(); } JObject obj = null; if (Object != null) { json = Object.toJson(); } JObject tmpObject = JObject.Parse(json); string col = Collection; if (string.IsNullOrEmpty(col)) // If not overwriten by param, then check for old collection { if (tmpObject.ContainsKey("__pscollection")) { col = tmpObject.Value <string>("__pscollection"); tmpObject.Remove("__pscollection"); } else { col = "entities"; } } else { if (tmpObject.ContainsKey("__pscollection")) { tmpObject.Remove("__pscollection"); } } if (!string.IsNullOrEmpty(Type)) { tmpObject["_type"] = Type; } if (!SkipLowercaseName.IsPresent) { bool loopAgain = true; while (loopAgain) { loopAgain = false; foreach (var v in tmpObject) { if (v.Key.ToLower() == "name" && v.Key != "name") { tmpObject["name"] = tmpObject[v.Key]; tmpObject.Remove(v.Key); loopAgain = true; break; } } } } if (MyInvocation.InvocationName == "Add-Entity") { if (tmpObject.ContainsKey("_id")) { tmpObject.Remove("_id"); } } if (UniqueKeys != null && UniqueKeys.Length > 0) { string uniqeness = string.Join(",", UniqueKeys); obj = await global.webSocketClient.InsertOrUpdateOne(col, 1, false, uniqeness, tmpObject); } else { if (tmpObject.ContainsKey("_id")) { obj = await global.webSocketClient.UpdateOne(col, 1, false, tmpObject); } else { if (MyInvocation.InvocationName == "Add-Entity") { obj = await global.webSocketClient.InsertOne(col, 1, false, tmpObject); } else { WriteError(new ErrorRecord(new Exception("Missing _id and UniqueKeys, either use Add-Entity or set UniqueKeys"), "", ErrorCategory.NotSpecified, null)); return; } } } var _obj = obj.toPSObject(); _obj.TypeNames.Insert(0, "OpenRPA.PS.Entity"); if (Collection == "openrpa") { if (obj.Value <string>("_type") == "workflow") { _obj.TypeNames.Insert(0, "OpenRPA.Workflow"); } if (obj.Value <string>("_type") == "project") { _obj.TypeNames.Insert(0, "OpenRPA.Project"); } if (obj.Value <string>("_type") == "detector") { _obj.TypeNames.Insert(0, "OpenRPA.Detector"); } if (obj.Value <string>("_type") == "unattendedclient") { _obj.TypeNames.Insert(0, "OpenRPA.UnattendedClient"); } if (obj.Value <string>("_type") == "unattendedserver") { _obj.TypeNames.Insert(0, "OpenRPA.UnattendedServer"); } } WriteObject(_obj); await Task.Delay(1); } catch (Exception ex) { WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null)); } }
protected override async Task ProcessRecordAsync() { try { var WorkflowRuntime = new RuntimeDefinedParameter(); string WorkflowName = ""; if (_staticStorage != null) { _staticStorage.TryGetValue("Workflow", out WorkflowRuntime); if (WorkflowRuntime.Value != null && !string.IsNullOrEmpty(WorkflowRuntime.Value.ToString())) { WorkflowName = WorkflowRuntime.Value.ToString(); } } var workflow = (_workflows == null ? null : _workflows.Where(x => x.name == WorkflowName).FirstOrDefault()); if ((workflow == null || string.IsNullOrEmpty(WorkflowName)) && string.IsNullOrEmpty(TargetQueue)) { WriteError(new ErrorRecord(new Exception("Missing workflow name or workflow not found"), "", ErrorCategory.NotSpecified, null)); return; } if (workflow != null) { TargetQueue = workflow.queue; } if (Object != null) { json = Object.toJson(); } if (string.IsNullOrEmpty(json)) { json = "{}"; } await RegisterQueue(); JObject tmpObject = JObject.Parse(json); correlationId = Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", ""); if (global.webSocketClient != null) { global.webSocketClient.OnQueueMessage += WebSocketClient_OnQueueMessage; } if (workflow != null) { WriteProgress(new ProgressRecord(0, "Invoking", "Invoking " + workflow.name)); } if (workflow == null) { WriteProgress(new ProgressRecord(0, "Invoking", "Invoking " + TargetQueue)); } var result = await global.webSocketClient.QueueMessage(TargetQueue, tmpObject, psqueue, correlationId); workItemsWaiting.WaitOne(); WriteProgress(new ProgressRecord(0, "Invoking", "completed") { RecordType = ProgressRecordType.Completed }); JObject payload = msg; if (msg.ContainsKey("payload")) { payload = msg.Value <JObject>("payload"); } if (state == "failed") { var message = "Invoke OpenFlow Workflow failed"; if (msg.ContainsKey("error")) { message = msg["error"].ToString(); } if (msg.ContainsKey("_error")) { message = msg["_error"].ToString(); } if (payload.ContainsKey("error")) { message = payload["error"].ToString(); } if (payload.ContainsKey("_error")) { message = payload["_error"].ToString(); } if (string.IsNullOrEmpty(message)) { message = "Invoke OpenFlow Workflow failed"; } WriteError(new ErrorRecord(new Exception(message), "", ErrorCategory.NotSpecified, null)); return; } if (payload != null) { var _result = payload.toPSObject(); WriteObject(_result); } } catch (Exception ex) { WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null)); WriteProgress(new ProgressRecord(0, "Invoking", "completed") { RecordType = ProgressRecordType.Completed }); } }
/// <summary> /// Creates a new instance. /// </summary> /// <param name="cmdletType">The type of the cmdlet the parameter belongs to.</param> /// <param name="runtimeDefinedParameter">The dynamic runtime parameter member of the cmdlet.</param> public RuntimeParameter(Type cmdletType, RuntimeDefinedParameter runtimeDefinedParameter) : base(cmdletType, runtimeDefinedParameter?.Attributes.OfType <ParameterAttribute>()) { RuntimeDefinedParameter = runtimeDefinedParameter ?? throw new ArgumentNullException(nameof(runtimeDefinedParameter)); }
/// <summary> /// Generate a runtime parameter with ValidateSet matching the current context /// </summary> /// <param name="name">The name of the parameter</param> /// <param name="runtimeParameter">The returned runtime parameter for context, with appropriate validate set</param> /// <returns>True if one or more contexts were found, otherwise false</returns> public static bool TryGetProvideServiceParameter(string name, string parameterSetName, out RuntimeDefinedParameter runtimeParameter) { var result = false; runtimeParameter = null; if (_configurations != null && _configurations.Values != null) { var ObjArray = _configurations.Values.ToArray(); var ProvideTypeList = ObjArray.Select(c => c.Type).ToArray(); runtimeParameter = new RuntimeDefinedParameter( name, typeof(string), new Collection <Attribute>() { new ParameterAttribute { Mandatory = false, ValueFromPipeline = true, HelpMessage = "The private link resource type.", ParameterSetName = parameterSetName }, new ValidateSetAttribute(ProvideTypeList) } ); result = true; } return(result); }
public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 1, Mandatory = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 2, Mandatory = true, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceIds = new RuntimeDefinedParameter(); pInstanceIds.Name = "InstanceId"; pInstanceIds.ParameterType = typeof(string[]); pInstanceIds.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false, ValueFromPipeline = false }); pInstanceIds.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 3, Mandatory = false, ValueFromPipeline = false }); pInstanceIds.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceIds); var pStayProvisioned = new RuntimeDefinedParameter(); pStayProvisioned.Name = "StayProvisioned"; pStayProvisioned.ParameterType = typeof(SwitchParameter); pStayProvisioned.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 4, Mandatory = true }); pStayProvisioned.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParametersForFriendMethod", Position = 5, Mandatory = true }); pStayProvisioned.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("StayProvisioned", pStayProvisioned); return(dynamicParameters); }