/// <summary> /// Converts a <see cref="JObject"/> to a <see cref="PSObject"/> /// </summary> /// <param name="jtoken">The <see cref="JObject"/></param> /// <param name="objectType">The type of the object.</param> internal static PSObject ToPsObject(this JToken jtoken, string objectType = null) { if (jtoken == null) { return null; } if (jtoken.Type != JTokenType.Object) { return new PSObject(JTokenExtensions.ConvertPropertyValueForPsObject(propertyValue: jtoken)); } var jobject = (JObject)jtoken; var psObject = new PSObject(); if (!string.IsNullOrWhiteSpace(objectType)) { psObject.TypeNames.Add(objectType); } foreach (var property in jobject.Properties()) { psObject.Properties.Add(new PSNoteProperty( name: property.Name, value: JTokenExtensions.ConvertPropertyValueForPsObject(propertyValue: property.Value))); } return psObject; }
private static void ShowHelpWindow(PSObject helpObj, PSCmdlet cmdlet) { Window ownerWindow = ShowCommandHelper.GetHostWindow(cmdlet); if (ownerWindow != null) { ownerWindow.Dispatcher.Invoke( new SendOrPostCallback( delegate(object ignored) { HelpWindow helpWindow = new HelpWindow(helpObj); helpWindow.Owner = ownerWindow; helpWindow.Show(); helpWindow.Closed += new EventHandler(delegate(object sender, EventArgs e) { ownerWindow.Focus(); }); }), String.Empty); return; } Thread guiThread = new Thread( (ThreadStart)delegate { HelpWindow helpWindow = new HelpWindow(helpObj); helpWindow.ShowDialog(); }); guiThread.SetApartmentState(ApartmentState.STA); guiThread.Start(); }
protected virtual PSObject SetVirtualMachineState(PSObject vm, string state) { PowerShell.Commands.Clear(); PowerShell.AddCommand(string.Format("{0}-WAPackVM", state)).AddParameter("VM", vm); var updatedVm = PowerShell.InvokeAndAssertForNoErrors(); return updatedVm[0]; }
private WideControlEntryDefinition GetActiveWideControlEntryDefinition(WideControlBody wideBody, PSObject so) { ConsolidatedString internalTypeNames = so.InternalTypeNames; TypeMatch match = new TypeMatch(base.expressionFactory, base.dataBaseInfo.db, internalTypeNames); foreach (WideControlEntryDefinition definition in wideBody.optionalEntryList) { if (match.PerfectMatch(new TypeMatchItem(definition, definition.appliesTo))) { return definition; } } if (match.BestMatch != null) { return (match.BestMatch as WideControlEntryDefinition); } Collection<string> typeNames = Deserializer.MaskDeserializationPrefix(internalTypeNames); if (typeNames != null) { match = new TypeMatch(base.expressionFactory, base.dataBaseInfo.db, typeNames); foreach (WideControlEntryDefinition definition2 in wideBody.optionalEntryList) { if (match.PerfectMatch(new TypeMatchItem(definition2, definition2.appliesTo))) { return definition2; } } if (match.BestMatch != null) { return (match.BestMatch as WideControlEntryDefinition); } } return wideBody.defaultEntryDefinition; }
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { base.Deserialize(so, deserializer); this.leftIndentation = deserializer.DeserializeIntMemberVariable(so, "leftIndentation"); this.rightIndentation = deserializer.DeserializeIntMemberVariable(so, "rightIndentation"); this.firstLine = deserializer.DeserializeIntMemberVariable(so, "firstLine"); }
private static void EncodeAndAddReturnValue(PSObject psObject, object returnValue) { if (returnValue != null) { RemoteHostEncoder.EncodeAndAddAsProperty(psObject, "mr", returnValue); } }
protected override void ProcessRecord() { base.ProcessRecord(); string Filter = "(&(objectCategory=group)(name=" + Name + "))"; string Scope = "Subtree"; string[] Properties = null; SearchResultCollection AdGroupObject = Utilities.Functions.QueryAD(Path, Filter, Scope, Properties); foreach (SearchResult Group in AdGroupObject) { foreach (string Member in Group.Properties["member"]) { foreach (SearchResult AdObject in (Utilities.Functions.QueryAD("LDAP://" + Member, "", "Base", null))) { WriteVerbose("Create PowerShell object to hold return values"); PSObject objReturn = new PSObject(); WriteVerbose("Add AdObject.Properties to PowerShell object"); foreach (string AdProperty in AdObject.Properties.PropertyNames) { WriteDebug("Add property : " + AdProperty); objReturn.Properties.Add(new PSNoteProperty(AdProperty, (AdObject.Properties[AdProperty])[0])); } WriteObject(objReturn); } } } }
internal static List<MshResolvedExpressionParameterAssociation> ExpandAll(PSObject target) { List<string> propertyNamesFromView = GetPropertyNamesFromView(target, PSMemberViewTypes.Adapted); List<string> list2 = GetPropertyNamesFromView(target, PSMemberViewTypes.Base); List<string> collection = GetPropertyNamesFromView(target, PSMemberViewTypes.Extended); List<string> list4 = new List<string>(); if (propertyNamesFromView.Count != 0) { list4 = propertyNamesFromView; } else { list4 = list2; } list4.AddRange(collection); Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); List<MshResolvedExpressionParameterAssociation> list5 = new List<MshResolvedExpressionParameterAssociation>(); foreach (string str in list4) { if (!dictionary.ContainsKey(str)) { dictionary.Add(str, null); MshExpression expression = new MshExpression(str, true); list5.Add(new MshResolvedExpressionParameterAssociation(null, expression)); } } return list5; }
public Collection<FormatData> Process(PSObject psobj) { // unroll one level. But more than LanguagePrimitives would unroll! var enumerator = LanguagePrimitives.GetEnumerator(psobj); if (enumerator == null) { var baseObj = PSObject.Unwrap(psobj); var enumerable = baseObj as IEnumerable; if (!(baseObj is string) && enumerable != null) { enumerator = enumerable.GetEnumerator(); } } if (enumerator == null) { return ProcessObject(psobj); } var results = new List<FormatData>(); while (enumerator.MoveNext()) { var curPSobj = PSObject.AsPSObject(enumerator.Current); results.AddRange(ProcessObject(curPSobj)); } return new Collection<FormatData>(results); }
public DscResourceClass(string name, string module, int index) { Name = name; Module = module; Index = index; _dscResourceItem = DscResourceAddOn.allDscResources[index - 1];//-1 since the output index is 1 more than the 0 indexed array }
public IEnumerable<String> ProcessRecord(PSObject record) { if (record == null) { yield break; } if (_raw) { yield return record.ToString(); } else { if (_pipeline == null) { _pipeline = CreatePipeline(); _pipeline.InvokeAsync(); } _pipeline.Input.Write(record); foreach (PSObject result in _pipeline.Output.NonBlockingRead()) { yield return result.ToString(); } } }
public PSObjectProxy(PSObject target) { if (target == null) throw new ArgumentNullException("target"); m_target = target; }
internal static void EnsurePropertyInfoPathExists(PSObject psObject, string[] path) { if (path.Length > 0) { for (int i = 0; i < path.Length; i++) { string name = path[i]; PSPropertyInfo member = psObject.Properties[name]; if (member == null) { object obj2 = (i < (path.Length - 1)) ? new PSObject() : null; member = new PSNoteProperty(name, obj2); psObject.Properties.Add(member); } if (i == (path.Length - 1)) { return; } if ((member.Value == null) || !(member.Value is PSObject)) { member.Value = new PSObject(); } psObject = (PSObject) member.Value; } } }
internal static void ToPSObjectForRemoting(CommandInfo commandInfo, PSObject psObject) { RemotingEncoder.ValueGetterDelegate<CommandTypes> valueGetter = null; RemotingEncoder.ValueGetterDelegate<string> delegate3 = null; RemotingEncoder.ValueGetterDelegate<string> delegate4 = null; RemotingEncoder.ValueGetterDelegate<SessionStateEntryVisibility> delegate5 = null; if (commandInfo != null) { if (valueGetter == null) { valueGetter = () => commandInfo.CommandType; } RemotingEncoder.AddNoteProperty<CommandTypes>(psObject, "CommandInfo_CommandType", valueGetter); if (delegate3 == null) { delegate3 = () => commandInfo.Definition; } RemotingEncoder.AddNoteProperty<string>(psObject, "CommandInfo_Definition", delegate3); if (delegate4 == null) { delegate4 = () => commandInfo.Name; } RemotingEncoder.AddNoteProperty<string>(psObject, "CommandInfo_Name", delegate4); if (delegate5 == null) { delegate5 = () => commandInfo.Visibility; } RemotingEncoder.AddNoteProperty<SessionStateEntryVisibility>(psObject, "CommandInfo_Visibility", delegate5); } }
//todo protected override void ProcessRecord() { foreach (String _path in Path) { StreamReader _file = new StreamReader(_path); PSObject _obj = new PSObject(); if (_file.Peek() == '#') { String _line = _file.ReadLine(); if (_line.StartsWith("#TYPE")) { _obj.TypeNames.Add(_line.Substring(5).Trim()); } } // Hold the names of the properties, the capacity is pretty arbitrary //List<String> _names = new List<String>(16); //bool inValues = false; while (!_file.EndOfStream) { char _ch = (char)_file.Read(); } /* if ((_ch == ',') { _obj.Properties.Add(new PSNoteProperty()); } */ } }
internal static List<MshResolvedExpressionParameterAssociation> SetupActiveProperties(List<MshParameter> rawMshParameterList, PSObject target, MshExpressionFactory expressionFactory) { // check if we received properties from the command line if (rawMshParameterList != null && rawMshParameterList.Count > 0) { return AssociationManager.ExpandParameters(rawMshParameterList, target); } // we did not get any properties: //try to get properties from the default property set of the object List<MshResolvedExpressionParameterAssociation> activeAssociationList = AssociationManager.ExpandDefaultPropertySet(target, expressionFactory); if (activeAssociationList.Count > 0) { // we got a valid set of properties from the default property set..add computername for // remoteobjects (if available) if (PSObjectHelper.ShouldShowComputerNameProperty(target)) { activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, new MshExpression(RemotingConstants.ComputerNameNoteProperty))); } return activeAssociationList; } // we failed to get anything from the default property set // just get all the properties activeAssociationList = AssociationManager.ExpandAll(target); // Remove PSComputerName and PSShowComputerName from the display as needed. AssociationManager.HandleComputerNameProperties(target, activeAssociationList); return activeAssociationList; }
protected override void ProcessRecord() { base.ProcessRecord(); if (Globals.authToken != null) { _serverProxy = new ServerCommandProxy(Globals.ComputerName, Globals.Port, Globals.authToken); try { _serverProxy.AddAdminAccessUser(UserName); PSObject returnAddPcutAdminAccessUser = new PSObject(); returnAddPcutAdminAccessUser.Properties.Add(new PSNoteProperty("Username", UserName)); returnAddPcutAdminAccessUser.Properties.Add(new PSNoteProperty("AdminAccess", true)); WriteObject(returnAddPcutAdminAccessUser); } catch (XmlRpcFaultException fex) { ErrorRecord errRecord = new ErrorRecord(new Exception(fex.Message, fex.InnerException), fex.FaultString, ErrorCategory.NotSpecified, fex); WriteError(errRecord); } } else { WriteObject("Please run Connect-PcutServer in order to establish connection."); } }
public virtual ErrorFormatEntryData GenerateErrorFormatEntry(PSObject errorData) { ErrorRecord errorRecord; if (errorData.BaseObject is ErrorRecord) { errorRecord = (ErrorRecord)errorData.BaseObject; } else if (errorData.BaseObject is IContainsErrorRecord) { errorRecord = ((IContainsErrorRecord)errorData).ErrorRecord; } else if (errorData.BaseObject is Exception) { errorRecord = new ErrorRecord((Exception)errorData.BaseObject, "Exception", ErrorCategory.NotSpecified, null); } else { var msg = "Cannot generate ErrorFormatEntry from non-error. This is a bug, please report this issue!"; throw new NotImplementedException(msg); } var message = errorRecord.Exception == null ? "Unknown Error" : errorRecord.Exception.Message; var entry = new ErrorFormatEntryData(Shape, message, errorRecord.CategoryInfo.ToString(), errorRecord.FullyQualifiedErrorId); entry.WriteToErrorStream = errorData.WriteToErrorStream; return entry; }
/// <summary> /// compute the string value of the grouping property /// </summary> /// <param name="so">object to use to compute the property value</param> /// <returns>true if there was an update</returns> internal bool UpdateGroupingKeyValue(PSObject so) { if (_groupingKeyExpression == null) return false; List<MshExpressionResult> results = _groupingKeyExpression.GetValues(so); // if we have more that one match, we have to select the first one if (results.Count > 0 && results[0].Exception == null) { // no exception got thrown, so we can update object newValue = results[0].Result; object oldValue = _currentGroupingKeyPropertyValue; _currentGroupingKeyPropertyValue = newValue; // now do the comparison bool update = !(IsEqual(_currentGroupingKeyPropertyValue, oldValue) || IsEqual(oldValue, _currentGroupingKeyPropertyValue)); if (update && _label == null) { _groupingKeyDisplayName = results[0].ResolvedExpression.ToString(); } return update; } // we had no matches or we could not get the value: // NOTICE: we need to do this to avoid starting a new group every time // there is a failure to read the grouping property. // For example, for AD, there are objects that throw when trying // to read the "distinguishedName" property (used by the brokered property "ParentPath) return false; }
internal PSEventArgs(string computerName, Guid runspaceId, int eventIdentifier, string sourceIdentifier, object sender, object[] originalArgs, PSObject additionalData) { if (originalArgs != null) { foreach (object obj2 in originalArgs) { EventArgs args = obj2 as EventArgs; if (args != null) { this.sourceEventArgs = args; break; } if (ForwardedEventArgs.IsRemoteSourceEventArgs(obj2)) { this.sourceEventArgs = new ForwardedEventArgs((PSObject) obj2); break; } } } this.computerName = computerName; this.runspaceId = runspaceId; this.eventIdentifier = eventIdentifier; this.sender = sender; this.sourceArgs = originalArgs; this.sourceIdentifier = sourceIdentifier; this.timeGenerated = DateTime.Now; this.data = additionalData; this.forwardEvent = false; }
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { base.Deserialize(so, deserializer); this.label = deserializer.DeserializeStringMemberVariable(so, "label"); this.propertyName = deserializer.DeserializeStringMemberVariable(so, "propertyName"); this.formatPropertyField = (FormatPropertyField) deserializer.DeserializeMandatoryMemberObject(so, "formatPropertyField"); }
public ExecutableNodeFactory(Executable executable,Executables collection) { _collection = collection; _executable = (DtsContainer)executable; _host = _executable as TaskHost; _seq = _executable as Sequence; _foreachloop = _executable as ForEachLoop; _forloop = _executable as ForLoop; _psExecutable = PSObject.AsPSObject(_executable); if (null != _host) { _psExecutable.Properties.Add( new PSNoteProperty( "IsTaskHost", true )); _mainPipe = _host.InnerObject as MainPipe; } if (null != _mainPipe) { _psExecutable.Properties.Add(new PSNoteProperty("IsDataFlow", true)); } if (null != _seq) { _psExecutable.Properties.Add(new PSNoteProperty("IsSequence", true)); } if (null != _foreachloop) { _psExecutable.Properties.Add(new PSNoteProperty("IsForEachLoop", true)); } if (null != _forloop) { _psExecutable.Properties.Add(new PSNoteProperty("IsForLoop", true)); } }
private PSObject BuildHostLevelPSObjectArrayList(object objSessionObject, string uri, bool IsWsManLevel) { PSObject obj2 = new PSObject(); if (IsWsManLevel) { foreach (string str in WSManHelper.GetSessionObjCache().Keys) { obj2.Properties.Add(new PSNoteProperty(str, "Container")); } return obj2; } if (objSessionObject != null) { foreach (XmlNode node in this.GetResourceValue(objSessionObject, uri, null).ChildNodes) { foreach (XmlNode node2 in node.ChildNodes) { if ((node2.ChildNodes.Count == 0) || node2.FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) { obj2.Properties.Add(new PSNoteProperty(node2.LocalName, node2.InnerText)); } } } } foreach (string str2 in WinRmRootConfigs) { obj2.Properties.Add(new PSNoteProperty(str2, "Container")); } return obj2; }
private Object ConvertToReturnObject(object currentObject) { List<Object> currentAsArray = currentObject as List<Object>; if(currentAsArray != null) { PSObject[] result = new PSObject[currentAsArray.Count]; for(int currentIndex = 0; currentIndex < currentAsArray.Count; currentIndex++) { result[currentIndex] = (PSObject) ConvertToReturnObject(currentAsArray[currentIndex]); } return result; } OrderedDictionary currentAsDictionary = currentObject as OrderedDictionary; if (currentAsDictionary != null) { PSObject result = new PSObject(); foreach (string key in currentAsDictionary.Keys) { result.Properties.Add(new PSNoteProperty(key, ConvertToReturnObject(currentAsDictionary[key]))); } return result; } return currentObject; }
int Compare(PSObject x, PSObject y) { if (Descending.ToBool()) { var temp = x; x = y; y = temp; } if (this.Property == null) { return LanguagePrimitives.Compare(x, y); } foreach (var property in this.Property) { var xPropertyValue = x.BaseObject.GetType().GetProperty(property.ToString(), BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase).GetValue(x.BaseObject, null); var yPropertyValue = y.BaseObject.GetType().GetProperty(property.ToString(), BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase).GetValue(y.BaseObject, null); var result = LanguagePrimitives.Compare(xPropertyValue, yPropertyValue); if (result != 0) return result; } return 0; }
/// <summary> /// A function which returns a Stream object which encapsulates an IStream interface /// This makes it much easier to get the file contents in managed code / powershell /// </summary> /// <param name="parentObject">This will be the PSObject that encapsulates a IFsrmPropertyBag</param> /// <returns>A stream which wraps the parentObject's IStream</returns> public static StreamWrapperForIStream GetStream(PSObject parentObject) { IFsrmPropertyBag propertyBag = (IFsrmPropertyBag)parentObject.BaseObject; IStream istream = (IStream)propertyBag.GetFileStreamInterface(_FsrmFileStreamingMode.FsrmFileStreamingMode_Read, _FsrmFileStreamingInterfaceType.FsrmFileStreamingInterfaceType_IStream ); return new StreamWrapperForIStream(istream); }
public void ConvertToCanPackAsPSObjectArray() { var result = LanguagePrimitives.ConvertTo(3, typeof(PSObject[])); var expected = new PSObject[] { PSObject.AsPSObject(3) }; Assert.AreEqual(expected.GetType(), result.GetType()); Assert.AreEqual(expected, result); }
/// <summary> /// Converts a <see cref="JObject"/> to a <see cref="PSObject"/> /// </summary> /// <param name="jtoken">The <see cref="JObject"/></param> /// <param name="objectFormat">The <see cref="ResourceObjectFormat"/></param> /// <param name="objectType">The type of the object.</param> internal static PSObject ToPsObject(this JToken jtoken, ResourceObjectFormat objectFormat, string objectType = null) { if (jtoken == null) { return null; } if (jtoken.Type != JTokenType.Object) { return new PSObject(JTokenExtensions.ConvertPropertyValueForPsObject(propertyValue: jtoken, objectFormat: objectFormat)); } var jobject = (JObject)jtoken; var psObject = new PSObject(); if (jobject.CanConvertTo<Resource<JToken>>()) { return jobject.ToResource().ToPsObject(objectFormat); } if (!string.IsNullOrWhiteSpace(objectType)) { psObject.TypeNames.Add(objectType); } foreach (var property in jobject.Properties()) { psObject.Properties.Add(new PSNoteProperty( name: JTokenExtensions.ConvertToPascalCase(propertyName: property.Name), value: JTokenExtensions.ConvertPropertyValueForPsObject(propertyValue: property.Value, objectFormat: objectFormat))); } return psObject; }
private void AddProperties(PSObject psobj) { foreach (var keyObj in Property.Keys) { var key = keyObj.ToString(); // should be a string anyway var member = psobj.Members[key]; if (member == null) { if (psobj.BaseObject is PSCustomObject) { var noteProperty = new PSNoteProperty(key, Property[key]); AddMemberToCollection(psobj.Properties, noteProperty, false); AddMemberToCollection(psobj.Members, noteProperty, false); } else { var msg = String.Format("A member with the name {0} doesn't exist", key); WriteError(new PSInvalidOperationException(msg).ErrorRecord); } } else if (member is PSMethodInfo) { var method = member as PSMethodInfo; method.Invoke(Property[key]); } else if (member is PSPropertyInfo) { var psproperty = member as PSPropertyInfo; psproperty.Value = Property[key]; } } }
/// <summary> /// Let the view prepare itself for RemoteObjects. This will add "ComputerName" to the /// table columns. /// </summary> /// <param name="so"></param> internal override void PrepareForRemoteObjects(PSObject so) { Diagnostics.Assert(null != so, "so cannot be null"); // make sure computername property exists. Diagnostics.Assert(null != so.Properties[RemotingConstants.ComputerNameNoteProperty], "PrepareForRemoteObjects cannot be called when the object does not contain ComputerName property."); if ((dataBaseInfo != null) && (dataBaseInfo.view != null) && (dataBaseInfo.view.mainControl != null)) { // dont change the original format definition in the database..just make a copy and work // with the copy _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl.Copy(); TableRowItemDefinition cnRowDefinition = new TableRowItemDefinition(); PropertyTokenBase propToken = new FieldPropertyToken(); propToken.expression = new ExpressionToken(RemotingConstants.ComputerNameNoteProperty, false); cnRowDefinition.formatTokenList.Add(propToken); _tableBody.defaultDefinition.rowItemDefinitionList.Add(cnRowDefinition); // add header only if there are other header definitions if (_tableBody.header.columnHeaderDefinitionList.Count > 0) { TableColumnHeaderDefinition cnHeaderDefinition = new TableColumnHeaderDefinition(); cnHeaderDefinition.label = new TextToken(); cnHeaderDefinition.label.text = RemotingConstants.ComputerNameNoteProperty; _tableBody.header.columnHeaderDefinitionList.Add(cnHeaderDefinition); } } }
/// <summary> /// This is implementation for Get cmdlet: all instances, single instance, Get on associations /// </summary> /// <param name="query"></param> public override void ProcessRecord(QueryBuilder query) { ODataQueryBuilder odataQuery = query as ODataQueryBuilder; if (!this.PassInnerException.IsPresent) { string passInnerExceptionKey = "PassInnerException"; if (PrivateData.ContainsKey(passInnerExceptionKey)) { string PassInnerExceptionValue = PrivateData[passInnerExceptionKey]; this.PassInnerException = PassInnerExceptionValue.Equals("True", StringComparison.OrdinalIgnoreCase); } } string parentTypeName = this.Cmdlet.ParameterSetName; string privateDataEntryName = "NavigationLink" + parentTypeName; if (PrivateData.ContainsKey(privateDataEntryName)) { string parent = PrivateData[privateDataEntryName]; string[] parentParts = parent.Split('|'); string parentPropertyName = parentParts[2]; System.Management.Automation.PSObject[] argumentObjects = (System.Management.Automation.PSObject[]) this.Cmdlet.MyInvocation.BoundParameters[parentTypeName]; foreach (System.Management.Automation.PSObject parentObject in argumentObjects) { bool isCollection = parentParts[parentParts.Length - 1].Equals("Collection", StringComparison.OrdinalIgnoreCase); if (isCollection) { object[] parentPropertyObjectArray = (object[])parentObject.Properties[parentPropertyName].Value; foreach (System.Management.Automation.PSObject parentPropertyObject in parentPropertyObjectArray) { string odataId = (string)parentPropertyObject.Properties["@odata.id"].Value; string hostUri = GetCustomUriHelper(this.ClassName, this.ConnectionUri, odataQuery.Keys); UriBuilder uriBuilder = new UriBuilder(hostUri); uriBuilder.Path = odataId; GetCmdlet(this.Cmdlet, uriBuilder.Uri, true, odataQuery); } } else { System.Management.Automation.PSObject parentPropertyObject = (System.Management.Automation.PSObject)parentObject.Properties[parentPropertyName].Value; string odataId = (string)parentPropertyObject.Properties["@odata.id"].Value; string hostUri = GetCustomUriHelper(this.ClassName, this.ConnectionUri, odataQuery.Keys); UriBuilder uriBuilder = new UriBuilder(hostUri); uriBuilder.Path = odataId; GetCmdlet(this.Cmdlet, uriBuilder.Uri, true, odataQuery); } } } else { base.ProcessRecord(query); } }
protected override Uri BuildODataUri(string uri, Dictionary <string, string> queryParameters) { System.Management.Automation.PSObject argumentObjects = (System.Management.Automation.PSObject) this.Cmdlet.MyInvocation.BoundParameters["Value"]; System.Management.Automation.PSObject parentPropertyObject = argumentObjects; string odataId = (string)parentPropertyObject.Properties["@odata.id"].Value; string hostUri = GetCustomUriHelper(this.ClassName, this.ConnectionUri, null); UriBuilder uriBuilder = new UriBuilder(hostUri); uriBuilder.Path = odataId; return(uriBuilder.Uri); }
private bool HandleParseError(SMA.PSObject result, string describe) { string value = string.Format("Error in {0}", File); if (describe.Contains(value)) { string errorStackTrace = result.Properties["StackTrace"].Value as string; string errorMessage = result.Properties["FailureMessage"].Value as string; foreach (TestCase testCase in TestCases) { TestResult testResult = new TestResult(testCase); testResult.Outcome = TestOutcome.Failed; testResult.ErrorMessage = errorMessage; testResult.ErrorStackTrace = errorStackTrace; TestResults.Add(testResult); } return(false); } return(true); }
public override Dictionary <string, PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection <FieldDescription> descriptions) { this.Write(caption + "\n" + message + " "); Dictionary <string, PSObject> results = new Dictionary <string, PSObject>(); foreach (FieldDescription fd in descriptions) { string[] label = GetHotkeyAndLabel(fd.Label); this.WriteLine(label[1]); string data = this.ReadLine(); if (data == null) { return(null); } results[fd.Name] = PSObject.AsPSObject(data); } return(results); }
public void ProcessTestResults(Array results) { TestResults = new List <TestResult>(); foreach (object obj in results) { SMA.PSObject psobject = (SMA.PSObject)obj; string describe = psobject.Properties["Describe"].Value as string; if (!HandleParseError(psobject, describe)) { break; } string context = psobject.Properties["Context"].Value as string; string name = psobject.Properties["Name"].Value as string; if (string.IsNullOrEmpty(context)) { context = "No Context"; } TestCase testCase = TestCases.FirstOrDefault(m => m.FullyQualifiedName == $"{describe}.{context}.{name}"); if (testCase != null) { TestResult testResult = new TestResult(testCase); testResult.Outcome = GetOutcome(psobject.Properties["Result"].Value as string); string errorStackTrace = psobject.Properties["StackTrace"].Value as string; string errorMessage = psobject.Properties["FailureMessage"].Value as string; testResult.ErrorStackTrace = errorStackTrace; testResult.ErrorMessage = errorMessage; TestResults.Add(testResult); } } }
/// <summary> /// /// </summary> /// <param name="record"></param> public DebugRecord(PSObject record) : base(record) { }
/// <summary> /// Convert an listItem node into an PSObject with property "tag" and "text" /// </summary> /// <param name="xmlNode"></param> /// <param name="ordered"></param> /// <param name="index"></param> /// <returns></returns> private PSObject GetListItemPSObject(XmlNode xmlNode, bool ordered, ref int index) { if (xmlNode == null) { return(null); } if (!xmlNode.LocalName.Equals("listItem", StringComparison.OrdinalIgnoreCase)) { return(null); } string text = string.Empty; if (xmlNode.ChildNodes.Count > 1) { WriteMamlInvalidChildNodeCountError(xmlNode, "para", 1); } foreach (XmlNode childNode in xmlNode.ChildNodes) { if (childNode.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) { text = childNode.InnerText.Trim(); continue; } WriteMamlInvalidChildNodeError(xmlNode, childNode); } string tag = string.Empty; if (ordered) { tag = index.ToString("d2", CultureInfo.CurrentCulture); tag += ". "; index++; } else { tag = "* "; } PSObject mshObject = new PSObject(); mshObject.Properties.Add(new PSNoteProperty("Text", text)); mshObject.Properties.Add(new PSNoteProperty("Tag", tag)); mshObject.TypeNames.Clear(); if (ordered) { mshObject.TypeNames.Add("MamlOrderedListTextItem"); } else { mshObject.TypeNames.Add("MamlUnorderedListTextItem"); } mshObject.TypeNames.Add("MamlTextItem"); return(mshObject); }
/// <summary> /// Get a Hashtable object out of a PowerShell data file (.psd1) /// </summary> /// <param name="parameterName"> /// Name of the parameter that takes the specified .psd1 file as a value /// </param> /// <param name="psDataFilePath"> /// Path to the powershell data file /// </param> /// <param name="context"> /// ExecutionContext to use /// </param> /// <param name="allowedCommands"> /// Set of command names that are allowed to use in the .psd1 file /// </param> /// <param name="allowedVariables"> /// Set of variable names that are allowed to use in the .psd1 file /// </param> /// <param name="allowEnvironmentVariables"> /// If true, allow to use environment variables in the .psd1 file /// </param> /// <param name="skipPathValidation"> /// If true, caller guarantees the path is valid /// </param> /// <returns></returns> internal static Hashtable EvaluatePowerShellDataFile( string parameterName, string psDataFilePath, ExecutionContext context, IEnumerable <string> allowedCommands, IEnumerable <string> allowedVariables, bool allowEnvironmentVariables, bool skipPathValidation) { if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException("parameterName"); } if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException("psDataFilePath"); } if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } string resolvedPath; if (skipPathValidation) { resolvedPath = psDataFilePath; } else { #region "ValidatePowerShellDataFilePath" bool isPathValid = true; // File extension needs to be .psd1 string pathExt = Path.GetExtension(psDataFilePath); if (string.IsNullOrEmpty(pathExt) || !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } ProviderInfo provider; var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider); // ConfigPath should be resolved as FileSystem provider if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } // ConfigPath should be resolved to a single path if (resolvedPaths.Count != 1) { isPathValid = false; } if (!isPathValid) { throw PSTraceSource.NewArgumentException( parameterName, ParserStrings.CannotResolvePowerShellDataFilePath, psDataFilePath); } resolvedPath = resolvedPaths[0]; #endregion "ValidatePowerShellDataFilePath" } #region "LoadAndEvaluatePowerShellDataFile" object evaluationResult; try { // Create the scriptInfo for the .psd1 file string dataFileName = Path.GetFileName(resolvedPath); var dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context); ScriptBlock scriptBlock = dataFileScriptInfo.ScriptBlock; // Validate the scriptblock scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables); // Evaluate the scriptblock object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); try { // Set the $PSScriptRoot before the evaluation context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath)); evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs()); } finally { context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot); } } catch (RuntimeException ex) { throw PSTraceSource.NewInvalidOperationException( ex, ParserStrings.CannotLoadPowerShellDataFile, psDataFilePath, ex.Message); } var retResult = evaluationResult as Hashtable; if (retResult == null) { throw PSTraceSource.NewInvalidOperationException( ParserStrings.InvalidPowerShellDataFile, psDataFilePath); } #endregion "LoadAndEvaluatePowerShellDataFile" return(retResult); }
/// <summary> /// Initializes a new instance of the <see cref="PSObjectTypeDescriptor"/> that provides /// property information about <paramref name="instance"/>. /// </summary> /// <param name="instance">The <see cref="PSObject"/> this class retrieves property information from.</param> public PSObjectTypeDescriptor(PSObject instance) { Instance = instance; }
public PSEventHandler(PSEventManager eventManager, object sender, string sourceIdentifier, PSObject extraData) { this.eventManager = eventManager; this.sender = sender; this.sourceIdentifier = sourceIdentifier; this.extraData = extraData; }
/// <summary> /// Binds the specified parameters to the native command. /// </summary> /// <param name="parameters"> /// The parameters to bind. /// </param> /// <param name="outputRedirected"> /// true if minishell output is redirected. /// </param> /// <param name="hostName"> /// name of the calling host. /// </param> /// <remarks> /// For any parameters that do not have a name, they are added to the command /// line arguments for the command /// </remarks> internal Collection <CommandParameterInternal> BindParameters(Collection <CommandParameterInternal> parameters, bool outputRedirected, string hostName) { MinishellParameters seen = 0; string inputFormat = null; string outputFormat = null; for (int i = 0; i < parameters.Count; i++) { var parameter = parameters[i]; if (parameter.ParameterNameSpecified) { var parameterName = parameter.ParameterName; if (CommandParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase)) { HandleSeenParameter(ref seen, MinishellParameters.Command, CommandParameter); // Value must be specified for -Command parameter. if (i + 1 >= parameters.Count) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter, typeof(ScriptBlock), null, NativeCP.NoValueForCommandParameter, "NoValueForCommandParameter"); } i += 1; // Value of -Command parameter must be scriptblock var scriptBlockArgument = parameters[i]; var argumentValue = PSObject.Base(scriptBlockArgument.ArgumentValue); if (!scriptBlockArgument.ArgumentSpecified || !(argumentValue is ScriptBlock)) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter, typeof(ScriptBlock), argumentValue.GetType(), NativeCP.IncorrectValueForCommandParameter, "IncorrectValueForCommandParameter"); } // Replace the parameters with -EncodedCommand <base64 encoded scriptblock> parameters[i - 1] = CommandParameterInternal.CreateParameter(EncodedCommandParameter, "-" + EncodedCommandParameter, parameter.ParameterAst); string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString()); parameters[i] = CommandParameterInternal.CreateArgument(encodedScript, scriptBlockArgument.ArgumentAst); } else if (InputFormatParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase)) { HandleSeenParameter(ref seen, MinishellParameters.InputFormat, InputFormatParameter); // Value for -Inputformat must be specified if (i + 1 >= parameters.Count) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, InputFormatParameter, typeof(string), null, NativeCP.NoValueForInputFormatParameter, "NoValueForInputFormatParameter"); } // Update the argument (partial arguments are allowed) i += 1; var inputFormatArg = parameters[i]; inputFormat = ProcessFormatParameterValue(InputFormatParameter, inputFormatArg.ArgumentValue); parameters[i - 1] = CommandParameterInternal.CreateParameter(InputFormatParameter, "-" + InputFormatParameter, parameter.ParameterAst); parameters[i] = CommandParameterInternal.CreateArgument(inputFormat, inputFormatArg.ArgumentAst); } else if (OutputFormatParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase)) { HandleSeenParameter(ref seen, MinishellParameters.OutputFormat, OutputFormatParameter); // Value for -Inputformat must be specified if (i + 1 >= parameters.Count) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, OutputFormatParameter, typeof(string), null, NativeCP.NoValueForOutputFormatParameter, "NoValueForInputFormatParameter"); } // Update the argument (partial arguments are allowed) i += 1; var outputFormatArg = parameters[i]; outputFormat = ProcessFormatParameterValue(OutputFormatParameter, outputFormatArg.ArgumentValue); parameters[i - 1] = CommandParameterInternal.CreateParameter(OutputFormatParameter, "-" + OutputFormatParameter, parameter.ParameterAst); parameters[i] = CommandParameterInternal.CreateArgument(outputFormat, outputFormatArg.ArgumentAst); } else if (ArgsParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase)) { HandleSeenParameter(ref seen, MinishellParameters.Arguments, ArgsParameter); // Value for -Args parameter must be specified if (i + 1 >= parameters.Count) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, ArgsParameter, typeof(string), null, NativeCP.NoValuesSpecifiedForArgs, "NoValuesSpecifiedForArgs"); } // Get the encoded value for -args parameter i += 1; var argsArg = parameters[i]; var encodedArgs = ConvertArgsValueToEncodedString(argsArg.ArgumentValue); parameters[i - 1] = CommandParameterInternal.CreateParameter(EncodedArgsParameter, "-" + EncodedArgsParameter, parameter.ParameterAst); // NOTE: do not pass the ArgumentAst; it will fail validation in BindParameters if there // are multiple arguments (array) but encodedArgs is an encoded string. parameters[i] = CommandParameterInternal.CreateArgument(encodedArgs); } } else { // -Command is positional parameter. Bind first scriptblock to it, others are errors. var scriptBlockArgument = parameters[i]; var argumentValue = PSObject.Base(scriptBlockArgument.ArgumentValue); if (argumentValue is ScriptBlock) { HandleSeenParameter(ref seen, MinishellParameters.Command, CommandParameter); // Replace the argument with -EncodedCommand <base64 encoded scriptblock> string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString()); parameters[i] = CommandParameterInternal.CreateParameterWithArgument( parameter.ArgumentAst, EncodedCommandParameter, "-" + EncodedCommandParameter, parameter.ArgumentAst, encodedScript, spaceAfterParameter: true); } } } // Add InputFormat and OutputFormat parameter if not specified if (inputFormat == null) { // For minishell default input format is xml parameters.Add(CommandParameterInternal.CreateParameter(InputFormatParameter, "-" + InputFormatParameter)); parameters.Add(CommandParameterInternal.CreateArgument(XmlFormatValue)); inputFormat = XmlFormatValue; } if (outputFormat == null) { // If output is redirected, output format should be xml outputFormat = outputRedirected ? XmlFormatValue : TextFormatValue; parameters.Add(CommandParameterInternal.CreateParameter(OutputFormatParameter, "-" + OutputFormatParameter)); parameters.Add(CommandParameterInternal.CreateArgument(outputFormat)); } // Set the output and input format class variable InputFormat = XmlFormatValue.StartsWith(inputFormat, StringComparison.OrdinalIgnoreCase) ? NativeCommandIOFormat.Xml : NativeCommandIOFormat.Text; OutputFormat = XmlFormatValue.StartsWith(outputFormat, StringComparison.OrdinalIgnoreCase) ? NativeCommandIOFormat.Xml : NativeCommandIOFormat.Text; // Note if a minishell is invoked from a non-console host, we need to // pass -nonInteractive flag. Our console host's name is "ConsoleHost". // Correct check would be see if current host has access to console and // pass noninteractive flag if doesn't. if (string.IsNullOrEmpty(hostName) || !hostName.Equals("ConsoleHost", StringComparison.OrdinalIgnoreCase)) { NonInteractive = true; parameters.Insert(0, CommandParameterInternal.CreateParameter(NonInteractiveParameter, "-" + NonInteractiveParameter)); } ((NativeCommandParameterBinder)DefaultParameterBinder).BindParameters(parameters); Diagnostics.Assert(s_emptyReturnCollection.Count == 0, "This list shouldn't be used for anything as it's shared."); return(s_emptyReturnCollection); }
/// <summary> /// Reads the information the PSObject /// and returns true if this object should be serialized as string. /// </summary> /// <param name="source">PSObject to be serialized.</param> /// <returns>True if the object needs to be serialized as a string.</returns> private static bool SerializeAsString(PSObject source) { return(source.GetSerializationMethod(null) == SerializationMethod.String); }
private bool HandleKnownContainerTypes(object source, string property, int depth) { Dbg.Assert(source != null, "caller should validate the parameter"); ContainerType ct = ContainerType.None; PSObject mshSource = source as PSObject; IEnumerable enumerable = null; IDictionary dictionary = null; // If passed in object is PSObject with no baseobject, return false. if (mshSource != null && mshSource.ImmediateBaseObjectIsEmpty) { return(false); } // Check if source (or baseobject in mshSource) is known container type GetKnownContainerTypeInfo(mshSource != null ? mshSource.ImmediateBaseObject : source, out ct, out dictionary, out enumerable); if (ct == ContainerType.None) { return(false); } WriteStartOfPSObject(mshSource ?? PSObject.AsPSObject(source), property, true); switch (ct) { case ContainerType.Dictionary: { WriteDictionary(dictionary, depth); } break; case ContainerType.Stack: case ContainerType.Queue: case ContainerType.List: case ContainerType.Enumerable: { WriteEnumerable(enumerable, depth); } break; default: { Dbg.Assert(false, "All containers should be handled in the switch"); } break; } // An object which is original enumerable becomes an PSObject // with arraylist on deserialization. So on roundtrip it will show up // as List. // We serialize properties of enumerable and on deserialization mark the object // as Deserialized. So if object is marked deserialized, we should write properties. // Note: we do not serialize the properties of IEnumerable if depth is zero. if (depth != 0 && (ct == ContainerType.Enumerable || (mshSource != null && mshSource.IsDeserialized))) { // Note:Depth is the depth for serialization of baseObject. // Depth for serialization of each property is one less. WritePSObjectProperties(PSObject.AsPSObject(source), depth); } // If source is PSObject, serialize notes if (mshSource != null) { // Serialize instanceMembers PSMemberInfoCollection <PSMemberInfo> instanceMembers = mshSource.InstanceMembers; if (instanceMembers != null) { WriteMemberInfoCollection(instanceMembers, depth, true); } } _writer.WriteEndElement(); return(true); }
/// <summary> /// Creates an InformationalRecord from an instance serialized as a PSObject by ToPSObjectForRemoting. /// </summary> internal InvocationInfo(PSObject psObject) { CommandOrigin = (CommandOrigin)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_CommandOrigin"); ExpectingInput = (bool)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ExpectingInput"); _invocationName = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_InvocationName"); HistoryId = (long)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_HistoryId"); PipelineLength = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelineLength"); PipelinePosition = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelinePosition"); string scriptName = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptName"); int scriptLineNumber = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptLineNumber"); int offsetInLine = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_OffsetInLine"); string line = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_Line"); var scriptPosition = new ScriptPosition(scriptName, scriptLineNumber, offsetInLine, line); ScriptPosition scriptEndPosition; if (!string.IsNullOrEmpty(line)) { int endColumn = line.Length + 1; scriptEndPosition = new ScriptPosition(scriptName, scriptLineNumber, endColumn, line); } else { scriptEndPosition = scriptPosition; } _scriptPosition = new ScriptExtent(scriptPosition, scriptEndPosition); MyCommand = RemoteCommandInfo.FromPSObjectForRemoting(psObject); // // Arrays are de-serialized as ArrayList so we need to convert the deserialized // object into an int[] before assigning to pipelineIterationInfo. // var list = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_PipelineIterationInfo"); if (list != null) { PipelineIterationInfo = (int[])list.ToArray(typeof(int)); } else { PipelineIterationInfo = Array.Empty <int>(); } // // Dictionaries are de-serialized as Hashtables so we need to convert the deserialized object into a dictionary // before assigning to CommandLineParameters. // Hashtable hashtable = (Hashtable)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_BoundParameters"); Dictionary <string, object> dictionary = new Dictionary <string, object>(); if (hashtable != null) { foreach (DictionaryEntry entry in hashtable) { dictionary.Add((string)entry.Key, entry.Value); } } _boundParameters = dictionary; // // The unbound parameters are de-serialized as an ArrayList, which we need to convert to a List // var unboundArguments = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_UnboundArguments"); _unboundArguments = new List <object>(); if (unboundArguments != null) { foreach (object o in unboundArguments) { _unboundArguments.Add(o); } } object value = SerializationUtilities.GetPropertyValue(psObject, "SerializeExtent"); bool serializeExtent = false; if (value != null) { serializeExtent = (bool)value; } if (serializeExtent) { DisplayScriptPosition = ScriptExtent.FromPSObjectForRemoting(psObject); } }
/// <summary> /// Send the output data to the client /// </summary> /// <param name="data">data to send</param> internal void SendOutputDataToClient(PSObject data) { SendDataAsync(RemotingEncoder.GeneratePowerShellOutput(data, _clientPowerShellId, _clientRunspacePoolId)); }
/// <summary> /// /// </summary> /// <param name="record"></param> public WarningRecord(PSObject record) : base(record) { }
/// <summary> /// /// </summary> /// <param name="record"></param> public VerboseRecord(PSObject record) : base(record) { }
public static Collection <string> PSTypeNames(PSObject o) { return(o.TypeNames); }
/// <summary> /// Constructor for Fully qualified warning Id. /// </summary> /// <param name="fullyQualifiedWarningId">Fully qualified warning Id</param> /// <param name="record">Warning serialized object</param> public WarningRecord(string fullyQualifiedWarningId, PSObject record) : base(record) { _fullyQualifiedWarningId = fullyQualifiedWarningId; }