protected override void ProcessRecord() { base.ProcessRecord(); if (Globals.authToken != null) { _serverProxy = new ServerCommandProxy(Globals.ComputerName, Globals.Port, Globals.authToken); try { int TotalUsers; TotalUsers = _serverProxy.GetTotalUsers(); PSObject returnTotalusers = new PSObject(); PSNoteProperty propertyTotalUsers = new PSNoteProperty("TotalUsers", TotalUsers); PSNoteProperty propertyComputerName = new PSNoteProperty("Server", Globals.ComputerName); returnTotalusers.Properties.Add(propertyTotalUsers); returnTotalusers.Properties.Add(propertyComputerName); WriteObject(returnTotalusers); } 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."); } }
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]; } } }
protected override void ProcessRecord() { base.ProcessRecord(); if (Globals.authToken != null) { _serverProxy = new ServerCommandProxy(Globals.ComputerName, Globals.Port, Globals.authToken); try { _serverProxy.RenameUserAccount(currentUserName, newUserName); if (_serverProxy.UserExists(newUserName)) { PSObject objNewUser = new PSObject(); PSNoteProperty noteProp = new PSNoteProperty("NewUsername", newUserName); objNewUser.Properties.Add(noteProp); WriteObject(objNewUser); } } 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."); } }
internal static void Dispatch(BaseClientTransportManager transportManager, PSHost clientHost, PSDataCollectionStream <ErrorRecord> errorStream, ObjectStream methodExecutorStream, bool isMethodExecutorStreamEnabled, RemoteRunspacePoolInternal runspacePool, Guid clientPowerShellId, System.Management.Automation.Remoting.RemoteHostCall remoteHostCall) { ClientMethodExecutor executor = new ClientMethodExecutor(transportManager, clientHost, runspacePool.InstanceId, clientPowerShellId, remoteHostCall); if (clientPowerShellId == Guid.Empty) { executor.Execute(errorStream); } else { bool flag = false; if (clientHost != null) { PSObject privateData = clientHost.PrivateData; if (privateData != null) { PSNoteProperty property = privateData.Properties["AllowSetShouldExitFromRemote"] as PSNoteProperty; flag = ((property != null) && (property.Value is bool)) ? ((bool)property.Value) : false; } } if ((remoteHostCall.IsSetShouldExit && isMethodExecutorStreamEnabled) && !flag) { runspacePool.Close(); } else if (isMethodExecutorStreamEnabled) { methodExecutorStream.Write(executor); } else { executor.Execute(errorStream); } } }
protected override void ProcessRecord() { if (ParameterSetName.Equals("MemberSet")) { switch (MemberType) { case PSMemberTypes.NoteProperty: var member = new PSNoteProperty(Name, Value); AddMemberToCollection(InputObject.Properties, member, Force.IsPresent); AddMemberToCollection(InputObject.Members, member, Force.IsPresent); break; default: var msg = String.Format("The member type '{0}' is currently not supported", MemberType.ToString()); throw new NotImplementedException(msg); } } else { var msg = String.Format("The parameter set '{0}' is currently not supported", ParameterSetName); throw new NotImplementedException(msg); } if (PassThru.IsPresent) { WriteObject(InputObject); } }
public void WhenCommandFailsToRunValidationResultIsUnavailable() { // Prepare string aValidOSVersion = "valid_os_version"; List <string> validOsVersions = new List <string>() { aValidOSVersion }; IConfiguration configuration = MockFactory.ConfigurationWithValidOSVersions(validOsVersions); var powershellCommandRunnerMockFactory = new Moq.Mock <IPowershellCommandRunner>(); powershellCommandRunnerMockFactory.Setup(powershellCommandRunner => powershellCommandRunner.AddScript(It.IsAny <string>())).Verifiable(); PSObject getCimInstanceResult = new PSObject(); string anInvalidOSVersion = "invalid_os_version"; PSMemberInfo versionMember = new PSNoteProperty("version", anInvalidOSVersion); getCimInstanceResult.Members.Add(versionMember); Collection <PSObject> commandResults = new Collection <PSObject> { getCimInstanceResult }; powershellCommandRunnerMockFactory.Setup(powershellCommandRunner => powershellCommandRunner.Invoke()).Throws(new Exception()); // Exercise OSVersionValidation osVersionValidation = new OSVersionValidation(configuration); IValidationResult validationResult = osVersionValidation.ValidateUsing(powershellCommandRunnerMockFactory.Object); // Verify Assert.StrictEqual <Result>(Result.Unavailable, validationResult.Result); }
/// <summary> /// Resets the internal user interface and yields the results to the pipeline. /// </summary> protected override void EndProcessing() { Installer.SetInternalUI(this.previousInternalUI); var drives = this.SessionState.Drive.GetAllForProvider("FileSystem"); if (null != drives) { // Only show psdrives that map to their logical drive letters. foreach (var drive in drives.Where(d => null != d.Root && d.Root.StartsWith(d.Name, StringComparison.OrdinalIgnoreCase))) { var spaceRequirements = this.spaceRequirements.Get(drive.Name); var spaceRequired = spaceRequirements.SpaceRequired; var temporarySpaceRequired = spaceRequirements.TemporarySpaceRequired; var obj = PSObject.AsPSObject(drive); obj.TypeNames.Insert(0, "System.Management.Automation.PSDriveInfo#MSISpaceRequired"); var property = new PSNoteProperty("MSISpaceRequired", spaceRequired); obj.Properties.Add(property, true); property = new PSNoteProperty("MSITemporarySpaceRequired", temporarySpaceRequired); obj.Properties.Add(property, true); base.WriteObject(obj); } } base.EndProcessing(); }
/// <summary> /// Resets the internal user interface and yields the results to the pipeline. /// </summary> protected override void EndProcessing() { Installer.SetInternalUI(this.previousInternalUI); var drives = this.SessionState.Drive.GetAllForProvider("FileSystem"); if (null != drives) { foreach (var drive in drives) { var spaceRequirements = this.spaceRequirements.Get(drive.Name); var spaceRequired = spaceRequirements.SpaceRequired; var temporarySpaceRequired = spaceRequirements.TemporarySpaceRequired; var obj = PSObject.AsPSObject(drive); obj.TypeNames.Insert(0, "System.Management.Automation.PSDriveInfo#MSISpaceRequired"); var property = new PSNoteProperty("MSISpaceRequired", spaceRequired); obj.Properties.Add(property, true); property = new PSNoteProperty("MSITemporarySpaceRequired", temporarySpaceRequired); obj.Properties.Add(property, true); base.WriteObject(obj); } } base.EndProcessing(); }
void outputCollection_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection <PSObject> collection = sender as PSDataCollection <PSObject>; lastOutput = collection[e.Index]; PSObject psObj = new PSObject(lastOutput); PSPropertyInfo propInfo = new PSNoteProperty("TimeStamp", DateTime.Now); psObj.Properties.Add(new PSNoteProperty("Stream", "Output")); psObj.Properties.Add(propInfo); timeStampedOutput.Add(psObj); if (Dispatcher != null) { RunOnUIThread( new DispatcherOperationCallback( delegate { NotifyOutputChanged(); return(null); }), true); } else { NotifyOutputChanged(); } }
/// <summary> /// Process the 'NotePropertyMultiMemberSet' parameter set. /// </summary> private void ProcessNotePropertyMultiMemberSet() { bool result = false; foreach (DictionaryEntry prop in _property) { string noteName = PSObject.ToStringParser(this.Context, prop.Key); object noteValue = prop.Value; if (string.IsNullOrEmpty(noteName)) { WriteError(NewError("NotePropertyNameShouldNotBeNull", "NotePropertyNameShouldNotBeNull", noteName)); continue; } PSMemberInfo member = new PSNoteProperty(noteName, noteValue); if (AddMemberToTarget(member) && !result) { result = true; } } if (result && _typeName != null) { UpdateTypeNames(); } if (result && _passThru) { WriteObject(_inputObject); } }
private static PSObject GetParameterHelpObject(string description) { PSObject paramHelp = new PSObject(); PSObject[] descDetails = new PSObject[1]; descDetails[0] = new PSObject(); descDetails[0].Members.Add(new PSNoteProperty("Text", description)); var np = new PSNoteProperty("name", "System.Datetime"); np.Value = "System.Datetime"; var typeName = new PSObject(np); paramHelp.Members.Add(new PSNoteProperty("Description", descDetails)); paramHelp.Members.Add(new PSNoteProperty("Name", "Date")); paramHelp.Members.Add(new PSNoteProperty("type", typeName)); paramHelp.Members.Add(new PSNoteProperty("required", "false")); paramHelp.Members.Add(new PSNoteProperty("position", "0")); paramHelp.Members.Add(new PSNoteProperty("defaultValue", "None")); paramHelp.Members.Add(new PSNoteProperty("pipelineInput", "True (ByPropertyName, ByValue)")); paramHelp.Members.Add(new PSNoteProperty("globbing", "false")); return(paramHelp); }
private void ProcessNotePropertyMultiMemberSet() { bool flag = false; foreach (DictionaryEntry entry in this._property) { string str = PSObject.ToStringParser(base.Context, entry.Key); object obj2 = entry.Value; if (string.IsNullOrEmpty(str)) { base.WriteError(this.NewError("NotePropertyNameShouldNotBeNull", "NotePropertyNameShouldNotBeNull", str, new object[0])); } else { PSMemberInfo member = new PSNoteProperty(str, obj2); if (this.AddMemberToTarget(member) && !flag) { flag = true; } } } if (flag && (this.typeName != null)) { this.UpdateTypeNames(); } if (flag && this.passThru) { base.WriteObject(this.inputObject); } }
private static void _MarkPropertyHidden(PSNoteProperty prop) { // We don't want the view definition stuff that we tack on to show up // anywhere, so we'll mark it hidden. Unfortunately this requires some // reflection. // // There is a property, but it does not have a setter in v3/v4, so we try for // a field first, and if we can't find that, try the property for v5. Type t = prop.GetType(); FieldInfo fi = t.GetField("isHidden", sm_allInstanceMembers); if (null != fi) { fi.SetValue(prop, true); } else { PropertyInfo pi = t.GetProperty("IsHidden", sm_allInstanceMembers); if (null != pi) { pi.SetValue(prop, true); } else { // Oh dear... where is it?! throw new Exception("Cannot find \"isHidden\" member on PSNoteProperty."); } } } // end _MarkPropertyHidden()
/// <summary> /// Sets or adds the named property value of type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type of the property value to set.</typeparam> /// <param name="source">The <see cref="PSObject"/> that may contain the named property.</param> /// <param name="propertyName">The name of the property to set; if not found, the a <see cref="PSNoteProperty"/> is added.</param> /// <param name="propertyValue">The value of the property to set.</param> /// <exception cref="ArgumentNullException"><paramref name="propertyName"/> is null or empty.</exception> /// <exception cref="PSInvalidCastException">The property value type cannot be converted to type <typeparamref name="T"/>.</exception> internal static void SetPropertyValue<T>(this PSObject source, string propertyName, T propertyValue) { if (null == source) { throw new ArgumentNullException("source"); } else if (string.IsNullOrEmpty(propertyName)) { throw new ArgumentNullException("propertyName"); } var property = source.Properties.Match(propertyName, PSMemberTypes.Properties).FirstOrDefault(); if (null != property) { if (property.Value is T) { property.Value = propertyValue; } else if (null != property.Value) { property.Value = LanguagePrimitives.ConvertTo(propertyValue, property.Value.GetType(), CultureInfo.InvariantCulture); } else { // Best effort may throw. property.Value = propertyValue; } } else { property = new PSNoteProperty(propertyName, propertyValue); source.Properties.Add(property); } }
/// <summary> /// Create a new ClientMethodExecutor object and then dispatch it. /// </summary> internal static void Dispatch( BaseClientTransportManager transportManager, PSHost clientHost, PSDataCollectionStream <ErrorRecord> errorStream, ObjectStream methodExecutorStream, bool isMethodExecutorStreamEnabled, RemoteRunspacePoolInternal runspacePool, Guid clientPowerShellId, RemoteHostCall remoteHostCall) { ClientMethodExecutor methodExecutor = new ClientMethodExecutor(transportManager, clientHost, runspacePool.InstanceId, clientPowerShellId, remoteHostCall); // If the powershell id is not specified, this message is for the runspace pool, execute // it immediately and return if (clientPowerShellId == Guid.Empty) { methodExecutor.Execute(errorStream); return; } // Check client host to see if SetShouldExit should be allowed bool hostAllowSetShouldExit = false; if (clientHost != null) { PSObject hostPrivateData = clientHost.PrivateData as PSObject; if (hostPrivateData != null) { PSNoteProperty allowSetShouldExit = hostPrivateData.Properties["AllowSetShouldExitFromRemote"] as PSNoteProperty; hostAllowSetShouldExit = allowSetShouldExit != null && allowSetShouldExit.Value is bool && (bool)allowSetShouldExit.Value; } } // Should we kill remote runspace? Check if "SetShouldExit" and if we are in the // cmdlet case. In the API case (when we are invoked from an API not a cmdlet) we // should not interpret "SetShouldExit" but should pass it on to the host. The // variable IsMethodExecutorStreamEnabled is only true in the cmdlet case. In the // API case it is false. if (remoteHostCall.IsSetShouldExit && isMethodExecutorStreamEnabled && !hostAllowSetShouldExit) { runspacePool.Close(); return; } // Cmdlet case: queue up the executor in the pipeline stream. if (isMethodExecutorStreamEnabled) { Dbg.Assert(methodExecutorStream != null, "method executor stream can't be null when enabled"); methodExecutorStream.Write(methodExecutor); } // API case: execute it immediately. else { methodExecutor.Execute(errorStream); } }
public void WhenFileSystemIsNotSupportedValidationResultIsError() { // Prepare string aValidFilesystem = "valid_filesystem"; List <string> validFilesystems = new List <string> { aValidFilesystem }; var configurationMockFactory = new Mock <IConfiguration>(); configurationMockFactory.Setup(configuration => configuration.ValidFilesystems()).Returns(validFilesystems); var powershellCommandRunnerMockFactory = new Moq.Mock <IPowershellCommandRunner>(); powershellCommandRunnerMockFactory.Setup(powershellCommandRunner => powershellCommandRunner.AddScript(It.IsAny <string>())).Verifiable(); PSObject getVolumeResult = new PSObject(); string anInvalidFilesystem = "an_invalid_filesystem"; PSMemberInfo versionMember = new PSNoteProperty("FileSystem", anInvalidFilesystem); getVolumeResult.Members.Add(versionMember); Collection <PSObject> commandResults = new Collection <PSObject> { getVolumeResult }; powershellCommandRunnerMockFactory.Setup(powershellCommandRunner => powershellCommandRunner.Invoke()).Returns(commandResults); // Exercise string path = "C:\\"; FileSystemValidation fileSystemValidation = new FileSystemValidation(configurationMockFactory.Object, path); IValidationResult validationResult = fileSystemValidation.ValidateUsing(powershellCommandRunnerMockFactory.Object); // Verify Assert.StrictEqual <Result>(Result.Fail, validationResult.Result); }
protected override void ProcessRecord() { DateTime dateToUse; switch (ParameterSetName) { case "Date": dateToUse = Date; break; case "Adjust": dateToUse = DateTime.Now.Add(Adjust); break; default: Dbg.Diagnostics.Assert(false, "Only one of the specified parameter sets should be called."); goto case "Date"; } if (ShouldProcess(dateToUse.ToString())) { #if UNIX if (!Platform.NonWindowsSetDate(dateToUse)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } #else // build up the SystemTime struct to pass to SetSystemTime NativeMethods.SystemTime systemTime = new NativeMethods.SystemTime(); systemTime.Year = (UInt16)dateToUse.Year; systemTime.Month = (UInt16)dateToUse.Month; systemTime.Day = (UInt16)dateToUse.Day; systemTime.Hour = (UInt16)dateToUse.Hour; systemTime.Minute = (UInt16)dateToUse.Minute; systemTime.Second = (UInt16)dateToUse.Second; systemTime.Milliseconds = (UInt16)dateToUse.Millisecond; #pragma warning disable 56523 if (!NativeMethods.SetLocalTime(ref systemTime)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // MSDN says to call this twice to account for changes // between DST if (!NativeMethods.SetLocalTime(ref systemTime)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } #pragma warning restore 56523 #endif } // output DateTime object wrapped in an PSObject with DisplayHint attached PSObject outputObj = new PSObject(dateToUse); PSNoteProperty note = new PSNoteProperty("DisplayHint", DisplayHint); outputObj.Properties.Add(note); WriteObject(outputObj); }
public void WriteItemObject(object item, Path path, bool isContainer) { PSObject psObject = GetItemAsPSObject(item, path); PSNoteProperty member = new PSNoteProperty("PSIsContainer", isContainer); psObject.Properties.Add(member); ProviderRuntime.WriteObject(psObject); }
private void Emit(OrderByPropertyEntry entry, string sideIndicator) { Diagnostics.Assert(entry != null, "null entry"); PSObject mshobj; if (PassThru) { mshobj = PSObject.AsPSObject(entry.inputObject); } else { mshobj = new PSObject(); if (Property == null || 0 == Property.Length) { PSNoteProperty inputNote = new PSNoteProperty( InputObjectPropertyName, entry.inputObject); mshobj.Properties.Add(inputNote); } else { List <MshParameter> mshParameterList = _orderByProperty.MshParameterList; Diagnostics.Assert(mshParameterList != null, "null mshParameterList"); Diagnostics.Assert(mshParameterList.Count == Property.Length, "mshParameterList.Count " + mshParameterList.Count); for (int i = 0; i < Property.Length; i++) { // 2005/07/05 This is the closest we can come to // the string typed by the user MshParameter mshParameter = mshParameterList[i]; Diagnostics.Assert(mshParameter != null, "null mshParameter"); Hashtable hash = mshParameter.hash; Diagnostics.Assert(hash != null, "null hash"); object prop = hash[FormatParameterDefinitionKeys.ExpressionEntryKey]; Diagnostics.Assert(prop != null, "null prop"); string propName = prop.ToString(); PSNoteProperty propertyNote = new PSNoteProperty( propName, entry.orderValues[i].PropertyValue); try { mshobj.Properties.Add(propertyNote); } catch (ExtendedTypeSystemException) { // this is probably a duplicate add } } } } mshobj.Properties.Remove(SideIndicatorPropertyName); PSNoteProperty sideNote = new PSNoteProperty( SideIndicatorPropertyName, sideIndicator); mshobj.Properties.Add(sideNote); WriteObject(mshobj); }
private void WriteObject(object item, string path, bool isContainer) { using (CmdletProvider.providerBaseTracer.TraceMethod(path, new object[0])) { PSObject psObject = this.WrapOutputInPSObject(item, path); PSNoteProperty psNoteProperty = new PSNoteProperty("PSIsContainer", (object)isContainer); psObject.Properties.Add((PSPropertyInfo)psNoteProperty, true); CmdletProvider.providerBaseTracer.WriteLine("Attaching {0} = {1}", (object)"PSIsContainer", (object)isContainer); this.Context.WriteObject((object)psObject); } }
/// <summary> /// Gets the value for the property specified by <paramref name="propertyName"/> from /// <paramref name="inputObject"/> and adds the value to <paramref name="matchedProperties"/> /// </summary> /// <param name="propertyName">Property to get the value for.</param> /// <param name="inputObject">Input object to get the value from.</param> /// <param name="matchedProperties">Collection to add the value to.</param> /// <remarks> /// <paramref name="matchedProperties"/> is assumed to be initialized. /// </remarks> private void ProcessParameter(string propertyName, PSObject inputObject, List <PSNoteProperty> matchedProperties) { object propValue = GetPropValue(inputObject, propertyName); // propValue can be null. PSNoteProperty newProperty = new PSNoteProperty(propertyName, propValue); matchedProperties.Add(newProperty); }
public static void TestMemberSetIsNotProperty() { var pso = new PSObject(DateTime.Now); var psNoteProperty = new PSNoteProperty("NewMember", "AValue"); pso.Members.Add(psNoteProperty); pso.Members.Add(new PSMemberSet("NewMemberSet", new[] { psNoteProperty })); var member = pso.GetFirstPropertyOrDefault(name => name == "NewMemberSet"); Assert.Null(member); }
private PSObject CreatePSObject(GenericRecord x) { var result = new PSObject(); foreach (var field in x.Schema.Fields) { var pSProperty = new PSNoteProperty(field.Name, x[field.Name]); result.Properties.Add(pSProperty); } return(result); }
private void ProcessParameter(MshParameter p, PSObject inputObject, List <PSNoteProperty> result) { string entry = p.GetEntry("name") as string; MshExpression re = p.GetEntry("expression") as MshExpression; List <MshExpressionResult> list = new List <MshExpressionResult>(); foreach (MshExpression expression2 in re.ResolveNames(inputObject)) { if ((this.exclusionFilter == null) || !this.exclusionFilter.IsMatch(expression2)) { List <MshExpressionResult> values = expression2.GetValues(inputObject); if (values != null) { foreach (MshExpressionResult result2 in values) { list.Add(result2); } } } } if (list.Count == 0) { list.Add(new MshExpressionResult(null, re, null)); } else if (!string.IsNullOrEmpty(entry) && (list.Count > 1)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(SelectObjectStrings.RenamingMultipleResults), "RenamingMultipleResults", ErrorCategory.InvalidOperation, inputObject); base.WriteError(errorRecord); return; } foreach (MshExpressionResult result3 in list) { if ((this.exclusionFilter == null) || !this.exclusionFilter.IsMatch(result3.ResolvedExpression)) { PSNoteProperty property; if (string.IsNullOrEmpty(entry)) { string str3 = result3.ResolvedExpression.ToString(); if (string.IsNullOrEmpty(str3)) { PSArgumentException exception = PSTraceSource.NewArgumentException("Property", this.ResourcesBaseName, "EmptyScriptBlockAndNoName", new object[0]); base.ThrowTerminatingError(new ErrorRecord(exception, "EmptyScriptBlockAndNoName", ErrorCategory.InvalidArgument, null)); } property = new PSNoteProperty(str3, result3.Result); } else { property = new PSNoteProperty(entry, result3.Result); } result.Add(property); } } }
public static void TestMemberSet() { var psObject = new PSObject(DateTime.Now); var psNoteProperty = new PSNoteProperty("NewMember", "AValue"); psObject.Members.Add(psNoteProperty); psObject.Members.Add(new PSMemberSet("NewMemberSet", new[] { psNoteProperty })); var member = psObject.Members.FirstOrDefault(name => name == "NewMemberSet"); Assert.NotNull(member); Assert.Equal("NewMemberSet", member.Name); }
internal static PSObject Serialize(object obj) { if (obj is MapiFolderPath) { return(new PSObject(obj.ToString())); } PSObject psobject = new PSObject(obj); PSNoteProperty member = new PSNoteProperty("SerializationData", SerializationTypeConverter.GetSerializationData(psobject)); psobject.Properties.Add(member); psobject.TypeNames.Insert(0, "Deserialized." + obj.GetType().FullName); return(psobject); }
/// <summary> /// Adds the related links properties. /// </summary> /// <param name="obj"></param> /// <param name="relatedLink"></param> internal static void AddRelatedLinksProperties(PSObject obj, string relatedLink) { if (!string.IsNullOrEmpty(relatedLink)) { PSObject navigationLinkObj = new PSObject(); navigationLinkObj.TypeNames.Clear(); navigationLinkObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#navigationLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); navigationLinkObj.Properties.Add(new PSNoteProperty("uri", relatedLink)); List <PSObject> navigationLinkValues = new List <PSObject> { navigationLinkObj }; // check if obj already has relatedLinks property PSNoteProperty relatedLinksPO = obj.Properties["relatedLinks"] as PSNoteProperty; if ((relatedLinksPO != null) && (relatedLinksPO.Value != null)) { PSObject relatedLinksValue = PSObject.AsPSObject(relatedLinksPO.Value); PSNoteProperty navigationLinkPO = relatedLinksValue.Properties["navigationLink"] as PSNoteProperty; if ((navigationLinkPO != null) && (navigationLinkPO.Value != null)) { PSObject navigationLinkValue = navigationLinkPO.Value as PSObject; if (navigationLinkValue != null) { navigationLinkValues.Add(navigationLinkValue); } else { PSObject[] navigationLinkValueArray = navigationLinkPO.Value as PSObject[]; if (navigationLinkValueArray != null) { foreach (var psObject in navigationLinkValueArray) { navigationLinkValues.Add(psObject); } } } } } PSObject relatedLinksObj = new PSObject(); relatedLinksObj.TypeNames.Clear(); relatedLinksObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#relatedLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); relatedLinksObj.Properties.Add(new PSNoteProperty("navigationLink", navigationLinkValues.ToArray())); obj.Properties.Add(new PSNoteProperty("relatedLinks", relatedLinksObj)); } }
internal static void AddShowComputerNameMarker(PSObject pso) { PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo; if (psShowComputerNameProperty != null) { psShowComputerNameProperty.Value = true; } else { psShowComputerNameProperty = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, true); pso.InstanceMembers.Add(psShowComputerNameProperty); } }
private void AddIndexToPSObject(PSObject ps, int i) { var prop = ps.Properties.Match(MagicNames.DataItemIndexPropertyName).FirstOrDefault(); if (null == prop) { var m = new PSNoteProperty(MagicNames.DataItemIndexPropertyName, i); ps.Properties.Add(m); } else { prop.Value = i; } }
protected virtual void ProcessPackage(SoftwareIdentity package) { // Check for duplicates if (!IsDuplicate(package)) { // Display the SoftwareIdentity object in a format: Name, Version, Source and Provider var swidTagAsPsobj = PSObject.AsPSObject(package); var noteProperty = new PSNoteProperty("PropertyOfSoftwareIdentity", "PropertyOfSoftwareIdentity"); swidTagAsPsobj.Properties.Add(noteProperty, true); swidTagAsPsobj.TypeNames.Insert(0, _newSoftwareIdentityTypeName); WriteObject(swidTagAsPsobj); } }
public void WriteItemObject(object item, string path, bool isContainer) { PSObject psObject = GetItemAsPSObject(item, path); PSNoteProperty member = new PSNoteProperty("PSIsContainer", isContainer); psObject.Properties.Add(member); ProviderRuntime.WriteObject(psObject); }
} // WriteObject #if SUPPORTS_IMULTIVALUEPROPERTYCMDLETPROVIDER /// <summary> /// Converts the incoming object to a PSObject and then adds extra /// data as notes. Then it writes the shell object to the context. /// </summary> /// /// <param name="item"> /// The value of the property being written out. /// </param> /// /// <param name="path"> /// The path of the item being written out. /// </param> /// /// <param name="propertyName"> /// The name of the property the value came from. /// </param> /// /// <param name="position"> /// The position in the property they value came from. /// </param> /// private void WriteObject( object item, string path, string propertyName, object position) { PSObject result = WrapOutputInPSObject(item, path); // Now add the property PSNoteProperty propertyToAdd = new PSNoteProperty("PSProperty", propertyName); result.Properties.Add(propertyToAdd); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSProperty", propertyName); // Now add the position propertyToAdd = new PSNoteProperty("MshAt", position); result.Properties.Add(propertyToAdd); providerBaseTracer.WriteLine("Attaching {0} = {1}", "MshAt", position); Diagnostics.Assert ( Context != null, "The context should always be set"); Context.WriteObject(result); } // WriteObject