public override PSMemberInfo Copy() { PSNoteProperty psNoteProperty = new PSNoteProperty(this.name, this.noteValue); this.CloneBaseProperties((PSMemberInfo)psNoteProperty); return((PSMemberInfo)psNoteProperty); }
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; } } }
public override PSMemberInfo Copy() { PSNoteProperty destiny = new PSNoteProperty(base.name, this.noteValue); base.CloneBaseProperties(destiny); return(destiny); }
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); } }
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; } } }
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> /// A helper method for creating an object that represents a total count /// of objects that the cmdlet would return without paging /// (this can be more than the size of the page specified in the <see cref="First"/> cmdlet parameter). /// </summary> /// <param name="totalCount">A total count of objects that the cmdlet would return without paging.</param> /// <param name="accuracy"> /// accuracy of the <paramref name="totalCount"/> parameter. /// <c>1.0</c> means 100% accurate; /// <c>0.0</c> means that total count is unknown; /// anything in-between means that total count is estimated /// </param> /// <returns>An object that represents a total count of objects that the cmdlet would return without paging.</returns> public PSObject NewTotalCount(UInt64 totalCount, double accuracy) { PSObject result = new PSObject(totalCount); string toStringMethodBody = string.Format( CultureInfo.CurrentCulture, @" $totalCount = $this.PSObject.BaseObject switch ($this.Accuracy) {{ {{ $_ -ge 1.0 }} {{ '{0}' -f $totalCount }} {{ $_ -le 0.0 }} {{ '{1}' -f $totalCount }} default {{ '{2}' -f $totalCount }} }} ", CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportAccurateTotalCountTemplate), CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportUnknownTotalCountTemplate), CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportEstimatedTotalCountTemplate)); PSScriptMethod toStringMethod = new PSScriptMethod("ToString", ScriptBlock.Create(toStringMethodBody)); result.Members.Add(toStringMethod); accuracy = Math.Max(0.0, Math.Min(1.0, accuracy)); PSNoteProperty statusProperty = new PSNoteProperty("Accuracy", accuracy); result.Members.Add(statusProperty); return(result); }
internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp) { if (((commandFullHelp != null) && (commandFullHelp.Properties["relatedLinks"] != null)) && (commandFullHelp.Properties["relatedLinks"].Value != null)) { PSObject obj2 = PSObject.AsPSObject(commandFullHelp.Properties["relatedLinks"].Value); if (obj2.Properties["navigationLink"] != null) { object[] objArray = (object[])LanguagePrimitives.ConvertTo(obj2.Properties["navigationLink"].Value, typeof(object[]), CultureInfo.InvariantCulture); foreach (object obj3 in objArray) { if (obj3 != null) { PSNoteProperty property = PSObject.AsPSObject(obj3).Properties["uri"] as PSNoteProperty; if (property != null) { string result = string.Empty; LanguagePrimitives.TryConvertTo <string>(property.Value, CultureInfo.InvariantCulture, out result); if (!string.IsNullOrEmpty(result)) { try { return(new Uri(result)); } catch (UriFormatException) { throw PSTraceSource.NewInvalidOperationException("HelpErrors", "InvalidURI", new object[] { result }); } } } } } } } return(null); }
public override PSMemberInfo Copy() { PSNoteProperty outVal = new PSNoteProperty(Name, Value); CopyProperties(outVal); return(outVal); }
private void HandleOutputReady(object sender, EventArgs eventArgs) { PSDataCollectionPipelineReader <PSObject, PSObject> reader = sender as PSDataCollectionPipelineReader <PSObject, PSObject>; foreach (PSObject obj2 in reader.NonBlockingRead()) { if (obj2 != null) { if (obj2.Properties[RemotingConstants.ComputerNameNoteProperty] != null) { obj2.Properties.Remove(RemotingConstants.ComputerNameNoteProperty); } if (obj2.Properties[RemotingConstants.RunspaceIdNoteProperty] != null) { obj2.Properties.Remove(RemotingConstants.RunspaceIdNoteProperty); } obj2.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, reader.ComputerName)); obj2.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, reader.RunspaceId)); if (obj2.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null) { PSNoteProperty member = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, !this.hideComputerName); obj2.Properties.Add(member); } } this.WriteObject(obj2); } }
internal static object GetPropertyValue(PSObject psObject, string propertyName) { PSNoteProperty property = (PSNoteProperty)psObject.Properties[propertyName]; if (property == null) { return(null); } return(property.Value); }
private static object GetNoteValue(PSObject mshObject, string note) { PSNoteProperty property = mshObject.Properties[note] as PSNoteProperty; if (property != null) { return(property.Value); } return(null); }
public PSObject NewTotalCount(ulong totalCount, double accuracy) { PSObject obj2 = new PSObject(totalCount); string script = string.Format(CultureInfo.CurrentCulture, "\r\n $totalCount = $this.PSObject.BaseObject\r\n switch ($this.Accuracy) {{\r\n {{ $_ -ge 1.0 }} {{ '{0}' -f $totalCount }}\r\n {{ $_ -le 0.0 }} {{ '{1}' -f $totalCount }}\r\n default {{ '{2}' -f $totalCount }}\r\n }}\r\n ", new object[] { CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportAccurateTotalCountTemplate), CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportUnknownTotalCountTemplate), CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportEstimatedTotalCountTemplate) }); PSScriptMethod member = new PSScriptMethod("ToString", ScriptBlock.Create(script)); obj2.Members.Add(member); accuracy = Math.Max(0.0, Math.Min(1.0, accuracy)); PSNoteProperty property = new PSNoteProperty("Accuracy", accuracy); obj2.Members.Add(property); return obj2; }
public PSObject NewTotalCount(ulong totalCount, double accuracy) { PSObject obj2 = new PSObject(totalCount); string script = string.Format(CultureInfo.CurrentCulture, "\r\n $totalCount = $this.PSObject.BaseObject\r\n switch ($this.Accuracy) {{\r\n {{ $_ -ge 1.0 }} {{ '{0}' -f $totalCount }}\r\n {{ $_ -le 0.0 }} {{ '{1}' -f $totalCount }}\r\n default {{ '{2}' -f $totalCount }}\r\n }}\r\n ", new object[] { CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportAccurateTotalCountTemplate), CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportUnknownTotalCountTemplate), CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportEstimatedTotalCountTemplate) }); PSScriptMethod member = new PSScriptMethod("ToString", ScriptBlock.Create(script)); obj2.Members.Add(member); accuracy = Math.Max(0.0, Math.Min(1.0, accuracy)); PSNoteProperty property = new PSNoteProperty("Accuracy", accuracy); obj2.Members.Add(property); return(obj2); }
/// <summary> /// Add the 'UserName' NoteProperty to the Process object /// </summary> /// <param name="process"></param> /// <returns></returns> private static PSObject AddUserNameToProcess(Process process) { // Return null if we failed to get the owner information string userName = ClrFacade.RetrieveProcessUserName(process); PSObject processAsPsobj = PSObject.AsPSObject(process); PSNoteProperty noteProperty = new PSNoteProperty("UserName", userName); processAsPsobj.Properties.Add(noteProperty, true); processAsPsobj.TypeNames.Insert(0, TypeNameForProcessWithUserName); return(processAsPsobj); }
internal static RemoteDataObject GenerateRunspacePoolStateInfo(Guid clientRunspacePoolId, RunspacePoolStateInfo stateInfo) { PSObject data = CreateEmptyPSObject(); PSNoteProperty member = new PSNoteProperty("RunspaceState", (int)stateInfo.State); data.Properties.Add(member); if (stateInfo.Reason != null) { string errorId = "RemoteRunspaceStateInfoReason"; PSNoteProperty property2 = GetExceptionProperty(stateInfo.Reason, errorId, ErrorCategory.NotSpecified); data.Properties.Add(property2); } return(RemoteDataObject.CreateFrom(RemotingDestination.InvalidDestination | RemotingDestination.Client, RemotingDataType.RunspacePoolStateInfo, clientRunspacePoolId, Guid.Empty, data)); }
/// <summary> /// Returns the default property for this object. /// </summary> /// <returns>An <see cref="PSObjectPropertyDescriptor"/> that represents the default property for this object, or a null reference (Nothing in Visual Basic) if this object does not have properties.</returns> public override PropertyDescriptor GetDefaultProperty() { if (this.Instance == null) { return(null); } string defaultProperty = null; PSMemberSet standardMembers = this.Instance.PSStandardMembers; if (standardMembers != null) { PSNoteProperty note = standardMembers.Properties[TypeTable.DefaultDisplayProperty] as PSNoteProperty; if (note != null) { defaultProperty = note.Value as string; } } if (defaultProperty == null) { object[] defaultPropertyAttributes = this.Instance.BaseObject.GetType().GetCustomAttributes(typeof(DefaultPropertyAttribute), true); if (defaultPropertyAttributes.Length == 1) { DefaultPropertyAttribute defaultPropertyAttribute = defaultPropertyAttributes[0] as DefaultPropertyAttribute; if (defaultPropertyAttribute != null) { defaultProperty = defaultPropertyAttribute.Name; } } } PropertyDescriptorCollection properties = this.GetProperties(); if (defaultProperty != null) { // There is a defaultProperty, but let's check if it is actually one of the properties we are // returning in GetProperties foreach (PropertyDescriptor descriptor in properties) { if (string.Equals(descriptor.Name, defaultProperty, StringComparison.OrdinalIgnoreCase)) { return(descriptor); } } } return(null); }
internal void SetProfileVariable(string currentUserCurrentHost, string currentUserAllHosts, string allUsersCurrentHost, string allUsersAllHosts) { var profileObj = new PSObject(currentUserCurrentHost); var profiles = new Dictionary<string, string> { { "CurrentUserCurrentHost", currentUserCurrentHost }, { "CurrentUserAllHosts", currentUserAllHosts }, { "AllUsersCurrentHost", allUsersCurrentHost }, { "AllUsersAllHosts", allUsersAllHosts } }; foreach (var pair in profiles) { var psNoteProperty = new PSNoteProperty(pair.Key, pair.Value); profileObj.Properties.Add(psNoteProperty); profileObj.Members.Add(psNoteProperty); } _currentRunspace.SessionStateProxy.SetVariable("Profile", profileObj); }
internal static bool ReportErrorRecord(IScriptExtent extent, RuntimeException rte, ExecutionContext context) { if (context.ShellFunctionErrorOutputPipe == null) { return(false); } if (((rte.ErrorRecord.InvocationInfo == null) && (extent != null)) && (extent != PositionUtilities.EmptyExtent)) { rte.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, extent, context)); } PSObject obj2 = PSObject.AsPSObject(new ErrorRecord(rte.ErrorRecord, rte)); PSNoteProperty member = new PSNoteProperty("writeErrorStream", true); obj2.Properties.Add(member); context.ShellFunctionErrorOutputPipe.Add(obj2); return(true); }
internal static RemoteDataObject GenerateRunspacePoolStateInfo( Guid clientRunspacePoolId, RunspacePoolStateInfo stateInfo) { using (RemotingEncoder._trace.TraceMethod()) { PSObject emptyPsObject = RemotingEncoder.CreateEmptyPSObject(); PSNoteProperty psNoteProperty = new PSNoteProperty("RunspaceState", (object)(int)stateInfo.State); emptyPsObject.Properties.Add((PSPropertyInfo)psNoteProperty); if (stateInfo.Reason != null) { string errorId = "RemoteRunspaceStateInfoReason"; PSNoteProperty exceptionProperty = RemotingEncoder.GetExceptionProperty(stateInfo.Reason, errorId, ErrorCategory.NotSpecified); emptyPsObject.Properties.Add((PSPropertyInfo)exceptionProperty); } return(RemoteDataObject.CreateFrom(RemotingDestination.Client, RemotingDataType.RunspacePoolStateInfo, clientRunspacePoolId, Guid.Empty, (object)emptyPsObject)); } }
/// <summary> /// Ensures the 'UserName' and 'HandleCount' Properties exist the Process object. /// </summary> /// <param name="process"></param> /// <param name="includeUserName"></param> /// <returns></returns> internal static PSObject AddProcessProperties(bool includeUserName, Process process) { PSObject processAsPsobj = includeUserName ? AddUserNameToProcess(process) : PSObject.AsPSObject(process); #if CORECLR // In CoreCLR, the System.Diagnostics.Process.HandleCount property does not exist. // I am adding a note property HandleCount and temporarily setting it to zero. // This issue will be fix for RTM and it is tracked by 5024994: Get-process does not populate the Handles field. PSMemberInfo hasHandleCount = processAsPsobj.Properties["HandleCount"]; if (hasHandleCount == null) { PSNoteProperty noteProperty = new PSNoteProperty("HandleCount", 0); processAsPsobj.Properties.Add(noteProperty, true); processAsPsobj.TypeNames.Insert(0, "System.Diagnostics.Process#HandleCount"); } #endif return(processAsPsobj); }
protected override void BeginProcessing() { if (!this.list || !this.scopeSpecified) { string shellID = base.Context.ShellID; if (!this.list) { if (!this.scopeSpecified) { base.WriteObject(SecuritySupport.GetExecutionPolicy(shellID)); return; } else { base.WriteObject(SecuritySupport.GetExecutionPolicy(shellID, this.executionPolicyScope)); return; } } else { ExecutionPolicyScope[] executionPolicyScopePreferences = SecuritySupport.ExecutionPolicyScopePreferences; for (int i = 0; i < (int)executionPolicyScopePreferences.Length; i++) { ExecutionPolicyScope executionPolicyScope = executionPolicyScopePreferences[i]; PSObject pSObject = new PSObject(); ExecutionPolicy executionPolicy = SecuritySupport.GetExecutionPolicy(shellID, executionPolicyScope); PSNoteProperty pSNoteProperty = new PSNoteProperty("Scope", (object)executionPolicyScope); pSObject.Properties.Add(pSNoteProperty); pSNoteProperty = new PSNoteProperty("ExecutionPolicy", (object)executionPolicy); pSObject.Properties.Add(pSNoteProperty); base.WriteObject(pSObject); } return; } } else { string listAndScopeSpecified = ExecutionPolicyCommands.ListAndScopeSpecified; ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(), "ListAndScopeSpecified", ErrorCategory.InvalidOperation, null); errorRecord.ErrorDetails = new ErrorDetails(listAndScopeSpecified); base.ThrowTerminatingError(errorRecord); return; } }
private void HandleRemainingArguments(Collection <CommandParameterInternal> arguments) { ArrayList list = new ArrayList(); foreach (CommandParameterInternal internal2 in arguments) { object obj2 = internal2.ArgumentSpecified ? internal2.ArgumentValue : null; if (internal2.ParameterAndArgumentSpecified && internal2.ParameterName.Equals("$args", StringComparison.OrdinalIgnoreCase)) { if (obj2 is object[]) { list.AddRange(obj2 as object[]); } else { list.Add(obj2); } } else { if (internal2.ParameterNameSpecified) { PSObject obj3 = new PSObject(string.Copy(internal2.ParameterText)); if (obj3.Properties["<CommandParameterName>"] == null) { PSNoteProperty member = new PSNoteProperty("<CommandParameterName>", internal2.ParameterName) { isHidden = true }; obj3.Properties.Add(member); } list.Add(obj3); } if (internal2.ArgumentSpecified) { list.Add(obj2); } } } object[] objArray = list.ToArray(); base.DefaultParameterBinder.BindParameter("args", objArray); this.DollarArgs.AddRange(objArray); }
internal bool ReportErrorRecord( Token statementToken, RuntimeException rte, ExecutionContext context) { if (context.ShellFunctionErrorOutputPipe == null) { return(false); } if (rte.ErrorRecord.InvocationInfo == null) { rte.ErrorRecord.SetInvocationInfo(new InvocationInfo((CommandInfo)null, statementToken, context)); } PSObject psObject = PSObject.AsPSObject((object)new ErrorRecord(rte.ErrorRecord, (Exception)rte)); PSNoteProperty psNoteProperty = new PSNoteProperty("writeErrorStream", (object)true); psObject.Properties.Add((PSPropertyInfo)psNoteProperty); context.ShellFunctionErrorOutputPipe.Add((object)psObject); return(true); }
internal static RemoteDataObject GenerateCreatePowerShell(ClientRemotePowerShell shell) { HostInfo info; PowerShell powerShell = shell.PowerShell; PSInvocationSettings settings = shell.Settings; PSObject data = CreateEmptyPSObject(); Guid empty = Guid.Empty; ApartmentState unknown = ApartmentState.Unknown; RunspacePool runspaceConnection = powerShell.GetRunspaceConnection() as RunspacePool; empty = runspaceConnection.InstanceId; unknown = runspaceConnection.ApartmentState; data.Properties.Add(new PSNoteProperty("PowerShell", powerShell.ToPSObjectForRemoting())); data.Properties.Add(new PSNoteProperty("NoInput", shell.NoInput)); if (settings == null) { info = new HostInfo(null) { UseRunspaceHost = true }; data.Properties.Add(new PSNoteProperty("ApartmentState", unknown)); data.Properties.Add(new PSNoteProperty("RemoteStreamOptions", RemoteStreamOptions.AddInvocationInfo)); data.Properties.Add(new PSNoteProperty("AddToHistory", false)); } else { info = new HostInfo(settings.Host); if (settings.Host == null) { info.UseRunspaceHost = true; } data.Properties.Add(new PSNoteProperty("ApartmentState", settings.ApartmentState)); data.Properties.Add(new PSNoteProperty("RemoteStreamOptions", settings.RemoteStreamOptions)); data.Properties.Add(new PSNoteProperty("AddToHistory", settings.AddToHistory)); } PSNoteProperty member = CreateHostInfoProperty(info); data.Properties.Add(member); data.Properties.Add(new PSNoteProperty("IsNested", shell.PowerShell.IsNested)); return(RemoteDataObject.CreateFrom(RemotingDestination.InvalidDestination | RemotingDestination.Server, RemotingDataType.CreatePowerShell, empty, shell.InstanceId, data)); }
public override PropertyDescriptor GetDefaultProperty() { if (this.Instance != null) { string b = null; PSMemberSet pSStandardMembers = this.Instance.PSStandardMembers; if (pSStandardMembers != null) { PSNoteProperty property = pSStandardMembers.Properties["DefaultDisplayProperty"] as PSNoteProperty; if (property != null) { b = property.Value as string; } } if (b == null) { object[] customAttributes = this.Instance.BaseObject.GetType().GetCustomAttributes(typeof(DefaultPropertyAttribute), true); if (customAttributes.Length == 1) { DefaultPropertyAttribute attribute = customAttributes[0] as DefaultPropertyAttribute; if (attribute != null) { b = attribute.Name; } } } PropertyDescriptorCollection properties = this.GetProperties(); if (b != null) { foreach (PropertyDescriptor descriptor in properties) { if (string.Equals(descriptor.Name, b, StringComparison.OrdinalIgnoreCase)) { return(descriptor); } } } } return(null); }
internal static RemoteDataObject GenerateCreatePowerShell( ClientRemotePowerShell shell) { PowerShell powerShell = shell.PowerShell; PSInvocationSettings settings = shell.Settings; PSObject emptyPsObject = RemotingEncoder.CreateEmptyPSObject(); Guid empty = Guid.Empty; RunspacePool runspaceConnection = powerShell.GetRunspaceConnection() as RunspacePool; Guid instanceId = runspaceConnection.InstanceId; ApartmentState apartmentState = runspaceConnection.ApartmentState; emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("PowerShell", (object)powerShell.ToPSObjectForRemoting())); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("NoInput", (object)shell.NoInput)); HostInfo hostInfo; if (settings == null) { hostInfo = new HostInfo((PSHost)null); hostInfo.UseRunspaceHost = true; emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("ApartmentState", (object)apartmentState)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("RemoteStreamOptions", (object)RemoteStreamOptions.AddInvocationInfo)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("AddToHistory", (object)false)); } else { hostInfo = new HostInfo(settings.Host); if (settings.Host == null) { hostInfo.UseRunspaceHost = true; } emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("ApartmentState", (object)settings.ApartmentState)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("RemoteStreamOptions", (object)settings.RemoteStreamOptions)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("AddToHistory", (object)settings.AddToHistory)); } PSNoteProperty hostInfoProperty = RemotingEncoder.CreateHostInfoProperty(hostInfo); emptyPsObject.Properties.Add((PSPropertyInfo)hostInfoProperty); return(RemoteDataObject.CreateFrom(RemotingDestination.Server, RemotingDataType.CreatePowerShell, instanceId, shell.InstanceId, (object)emptyPsObject)); }
private void Emit(OrderByPropertyEntry entry, string sideIndicator) { PSObject obj2; if (this.PassThru != 0) { obj2 = PSObject.AsPSObject(entry.inputObject); } else { obj2 = new PSObject(); if ((this.Property == null) || (this.Property.Length == 0)) { PSNoteProperty property = new PSNoteProperty("InputObject", entry.inputObject); obj2.Properties.Add(property); } else { List<MshParameter> mshParameterList = this.orderByProperty.MshParameterList; for (int i = 0; i < this.Property.Length; i++) { MshParameter parameter = mshParameterList[i]; object obj3 = parameter.hash["expression"]; PSNoteProperty property2 = new PSNoteProperty(obj3.ToString(), entry.orderValues[i].PropertyValue); try { obj2.Properties.Add(property2); } catch (ExtendedTypeSystemException) { } } } } obj2.Properties.Remove("SideIndicator"); PSNoteProperty member = new PSNoteProperty("SideIndicator", sideIndicator); obj2.Properties.Add(member); base.WriteObject(obj2); }
/// <summary> /// Ensure property info path exists. /// </summary> internal static void EnsurePropertyInfoPathExists(PSObject psObject, string[] path) { if (path.Length == 0) { return; } // Walk the path and extend it if necessary. for (int i = 0; i < path.Length; ++i) { string propertyName = path[i]; PSPropertyInfo propertyInfo = psObject.Properties[propertyName]; // Add a property info here if none was found. if (propertyInfo == null) { // Add null on the last one, since we don't need to extend path further. object propertyValue = (i < path.Length - 1) ? new PSObject() : null; propertyInfo = new PSNoteProperty(propertyName, propertyValue); psObject.Properties.Add(propertyInfo); } // If we are on the last path element, we are done. Let's not mess with modifying Value. if (i == path.Length - 1) { return; } // If we are not on the last path element, let's make sure we can extend the path. if (propertyInfo.Value == null || propertyInfo.Value is not PSObject) { propertyInfo.Value = new PSObject(); } // Now move one step further along the path. psObject = (PSObject)propertyInfo.Value; } }
protected override void ProcessRecord() { DateTime date; string str; if ((((str = base.ParameterSetName) == null) || (str == "Date")) || (str != "Adjust")) { date = this.Date; } else { date = DateTime.Now.Add(this.Adjust); } NativeMethods.SystemTime systime = new NativeMethods.SystemTime { Year = (ushort) date.Year, Month = (ushort) date.Month, Day = (ushort) date.Day, Hour = (ushort) date.Hour, Minute = (ushort) date.Minute, Second = (ushort) date.Second, Milliseconds = (ushort) date.Millisecond }; if (base.ShouldProcess(date.ToString())) { if (!NativeMethods.SetLocalTime(ref systime)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (!NativeMethods.SetLocalTime(ref systime)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } PSObject sendToPipeline = new PSObject(date); PSNoteProperty member = new PSNoteProperty("DisplayHint", this.DisplayHint); sendToPipeline.Properties.Add(member); base.WriteObject(sendToPipeline); }
/// <summary> /// Creates a PSObject from the specified IDataRecord implementation. /// </summary> /// <param name="record">The IDataRecord implementation such as the current row in a SqlDataReader.</param> /// <param name="trimSpaces">True to remove leading/trailing spaces from string columns. The default is true.</param> /// <returns>A new PSObject with properties corresponding to the columns of the IDataRecord.</returns> public static PSObject FromDataRecord(IDataRecord record, bool trimSpaces) { // Cache the names of the fields string[] columnNames = new string[record.FieldCount]; for ( int i = 0 ; i < record.FieldCount ; i++ ) { columnNames[i] = record.GetName( i ); } PSObject obj = new PSObject(); for (int i = 0; i < record.FieldCount; i++) { object value = null; if ( !record.IsDBNull(i) ) { value = record.GetValue(i); // Trim leading and trailing spaces from the column? if (trimSpaces) { string valueAsString = value as string; if (valueAsString != null) { value = valueAsString.Trim(); } } } PSNoteProperty prop = new PSNoteProperty(columnNames[i], value); obj.Properties.Add(prop); } return obj; }
/// <summary> /// Takes the remaining arguments that haven't been bound, and binds /// them to $args /// </summary> /// /// <param name="arguments"> /// The remaining unbound arguments. /// </param> /// /// <remarks> /// An array containing the values that were bound to $args. /// </remarks> private void HandleRemainingArguments(Collection<CommandParameterInternal> arguments) { List<object> args = new List<object>(); foreach (CommandParameterInternal parameter in arguments) { object argValue = parameter.ArgumentSpecified ? parameter.ArgumentValue : null; // Proper automatic proxy generation requires the ability to prevent unbound arguments // in the proxy from binding to positional parameters in the proxied command. We use // a special key ("$args") when splatting @CommandLineArguments to package up $args. // This special key is not created automatically because it is useful to splat @args, // just not in the automatically generated proxy. // // Example usage: // // function foo { param($a, $b) $a; $b; $args } // function foo_proxy { param($a) ; $CommandLineArguments.Add('$args', $args); foo @CommandLineArguments } // foo_proxy 1 2 3 // // Then in foo, $a=1, $b=, $args=2,3 // // Here, we want $b in foo to be unbound because the proxy doesn't have $b (an Exchange scenario.) // So we pass $args (2,3) in the special entry in @CommandLineArguments. If we had instead written: // // function foo_proxy { param($a) ; foo @CommandLineArguments @args } // foo_proxy 1 2 3 // // Then in foo, $a=1, $b=2, $args=3 // // Note that the name $args is chosen to be: // * descriptive // * obscure (it can't be a property/field name in C#, and is an unlikely variable in script) // So we shouldn't have any real conflict. Note that if someone actually puts ${$args} in their // param block, then the value will be bound and we won't have an unbound argument for "$args" here. if (parameter.ParameterAndArgumentSpecified && parameter.ParameterName.Equals("$args", StringComparison.OrdinalIgnoreCase)) { // $args is normally an object[], but because this feature is accessible from script, it's possible // for it to contain anything. if (argValue is object[]) { args.AddRange(argValue as object[]); } else { args.Add(argValue); } continue; } if (parameter.ParameterNameSpecified) { // Add a property to the string so we can tell the difference between: // foo -abc // foo "-abc" // This is important when splatting, we reconstruct the parameter if the // value is splatted. var parameterText = new PSObject(new String(parameter.ParameterText.ToCharArray())); if (parameterText.Properties[NotePropertyNameForSplattingParametersInArgs] == null) { var noteProperty = new PSNoteProperty(NotePropertyNameForSplattingParametersInArgs, parameter.ParameterName) { IsHidden = true }; parameterText.Properties.Add(noteProperty); } args.Add(parameterText); } if (parameter.ArgumentSpecified) { args.Add(argValue); } } object[] argsArray = args.ToArray(); DefaultParameterBinder.BindParameter(SpecialVariables.Args, argsArray, parameterMetadata: null); DollarArgs.AddRange(argsArray); return; }
void AddMagicPropertiesToPSObject( PSObject ps ) { if (!ps.Properties.Match(MagicNames.DataSourcePropertyName).Any()) { var m = new PSNoteProperty(MagicNames.DataSourcePropertyName, this); ps.Properties.Add(m); } //Scales.ToList().ForEach(sda => // { // try // { // var sm = new PSNoteProperty(sda.PropertyName + "_Scale", sda); // ps.Properties.Add(sm); // } // catch // { // } // }); }
/// <summary> /// This method is used for customizing the format of the OneGet *-Package output display. /// </summary> /// <param name="package"></param> /// <returns></returns> protected object AddPropertyToSoftwareIdentity(SoftwareIdentity package) { // Use the default output format if a user does not provide the -providername property, e.g. find-package if (package == null || (!_isUserSpecifyOneProviderName && !IsDisplayCulture && UseDefaultSourceFormat)) { return package; } // Customize the output format var typeName = GetSoftwareIdentityTypeName(package); // For the find-package -providername nuget case, we can return right away. if (!_hasTypeNameChanged) { return package; } var swidTagAsPsobj = PSObject.AsPSObject(package); var noteProperty = new PSNoteProperty("PropertyOfSoftwareIdentity", "PropertyOfSoftwareIdentity"); swidTagAsPsobj.Properties.Add(noteProperty, true); swidTagAsPsobj.TypeNames.Insert(0, typeName); return swidTagAsPsobj; }
protected void SetSyncModeOnHost(bool isSync) { if (_nugetHost != null) { PSPropertyInfo property = _nugetHost.PrivateData.Properties["IsSyncMode"]; if (property == null) { property = new PSNoteProperty("IsSyncMode", isSync); _nugetHost.PrivateData.Properties.Add(property); } else { property.Value = isSync; } } }
/// <summary> /// Outputs the execution policy. /// </summary> protected override void BeginProcessing() { if (_list && _scopeSpecified) { string message = ExecutionPolicyCommands.ListAndScopeSpecified; ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(), "ListAndScopeSpecified", ErrorCategory.InvalidOperation, null); errorRecord.ErrorDetails = new ErrorDetails(message); ThrowTerminatingError(errorRecord); return; } string shellId = base.Context.ShellID; if (_list) { foreach (ExecutionPolicyScope scope in SecuritySupport.ExecutionPolicyScopePreferences) { PSObject outputObject = new PSObject(); ExecutionPolicy policy = SecuritySupport.GetExecutionPolicy(shellId, scope); PSNoteProperty inputNote = new PSNoteProperty( "Scope", scope); outputObject.Properties.Add(inputNote); inputNote = new PSNoteProperty( "ExecutionPolicy", policy); outputObject.Properties.Add(inputNote); WriteObject(outputObject); } } else if (_scopeSpecified) { WriteObject(SecuritySupport.GetExecutionPolicy(shellId, _executionPolicyScope)); } else { WriteObject(SecuritySupport.GetExecutionPolicy(shellId)); } }//End BeginProcess()
/// <summary> /// Attaches the cached notes to the specified PSObject. /// </summary> /// /// <param name="content"> /// The PSObject to attached the cached notes to. /// </param> /// /// <returns> /// The PSObject that was passed in with the cached notes added. /// </returns> /// public PSObject AttachNotes(PSObject content) { // Construct a provider qualified path as the Path note PSNoteProperty note = new PSNoteProperty("PSPath", PSPath); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSPath", PSPath); // Now attach the parent path and child name note = new PSNoteProperty("PSParentPath", ParentPath); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", ParentPath); // Attach the child name note = new PSNoteProperty("PSChildName", ChildName); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSChildName", ChildName); // PSDriveInfo if (PathInfo.Drive != null) { note = new PSNoteProperty("PSDrive", Drive); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSDrive", Drive); } // ProviderInfo note = new PSNoteProperty("PSProvider", Provider); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSProvider", Provider); return content; } // AttachNotes
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); } }
internal Uri LookupUriFromCommandInfo() { CommandTypes cmdTypesToLookFor = CommandTypes.Cmdlet; switch (this.HelpCategory) { case Automation.HelpCategory.Cmdlet: cmdTypesToLookFor = CommandTypes.Cmdlet; break; case Automation.HelpCategory.Function: cmdTypesToLookFor = CommandTypes.Function; break; case Automation.HelpCategory.ScriptCommand: cmdTypesToLookFor = CommandTypes.Script; break; case Automation.HelpCategory.ExternalScript: cmdTypesToLookFor = CommandTypes.ExternalScript; break; case Automation.HelpCategory.Filter: cmdTypesToLookFor = CommandTypes.Filter; break; case Automation.HelpCategory.Configuration: cmdTypesToLookFor = CommandTypes.Configuration; break; default: return(null); } string commandName = this.Name; string moduleName = string.Empty; if (this.FullHelp.Properties["ModuleName"] != null) { PSNoteProperty moduleNameNP = this.FullHelp.Properties["ModuleName"] as PSNoteProperty; if (null != moduleNameNP) { LanguagePrimitives.TryConvertTo <string>(moduleNameNP.Value, CultureInfo.InvariantCulture, out moduleName); } } string commandToSearch = commandName; if (!string.IsNullOrEmpty(moduleName)) { commandToSearch = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", moduleName, commandName); } ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); if (null == context) { return(null); } try { CommandInfo cmdInfo = null; if (cmdTypesToLookFor == CommandTypes.Cmdlet) { cmdInfo = context.SessionState.InvokeCommand.GetCmdlet(commandToSearch); } else { cmdInfo = context.SessionState.InvokeCommand.GetCommands(commandToSearch, cmdTypesToLookFor, false).FirstOrDefault(); } if ((cmdInfo == null) || (cmdInfo.CommandMetadata == null)) { return(null); } string uriString = cmdInfo.CommandMetadata.HelpUri; if (!string.IsNullOrEmpty(uriString)) { if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute)) { // WinBlue: 545315 Online help links are broken with localized help // Example: https://go.microsoft.com/fwlink/?LinkID=113324 (möglicherwei se auf Englisch) // Split the string based on <s> (space). We decided to go with this approach as // UX localization authors use spaces. Correctly extracting only the wellformed URI // is out-of-scope for this fix. string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space); uriString = tempUriSplitArray[0]; } try { return(new System.Uri(uriString)); // return only the first Uri (ignore other uris) } catch (UriFormatException) { throw PSTraceSource.NewInvalidOperationException(HelpErrors.InvalidURI, cmdInfo.CommandMetadata.HelpUri); } } } catch (CommandNotFoundException) { } return(null); }
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; } }
internal Uri LookupUriFromCommandInfo() { CommandTypes cmdlet = CommandTypes.Cmdlet; switch (this.HelpCategory) { case System.Management.Automation.HelpCategory.Function: cmdlet = CommandTypes.Function; break; case System.Management.Automation.HelpCategory.Filter: cmdlet = CommandTypes.Filter; break; case System.Management.Automation.HelpCategory.ExternalScript: cmdlet = CommandTypes.ExternalScript; break; case System.Management.Automation.HelpCategory.Cmdlet: cmdlet = CommandTypes.Cmdlet; break; case System.Management.Automation.HelpCategory.ScriptCommand: cmdlet = CommandTypes.Script; break; default: return(null); } string name = this.Name; string result = string.Empty; if (this.FullHelp.Properties["ModuleName"] != null) { PSNoteProperty property = this.FullHelp.Properties["ModuleName"] as PSNoteProperty; if (property != null) { LanguagePrimitives.TryConvertTo <string>(property.Value, CultureInfo.InvariantCulture, out result); } } string commandName = name; if (!string.IsNullOrEmpty(result)) { commandName = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", new object[] { result, name }); } ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if (executionContextFromTLS != null) { try { CommandInfo info = null; if (cmdlet == CommandTypes.Cmdlet) { info = executionContextFromTLS.SessionState.InvokeCommand.GetCmdlet(commandName); } else { info = executionContextFromTLS.SessionState.InvokeCommand.GetCommands(commandName, cmdlet, false).FirstOrDefault <CommandInfo>(); } if ((info == null) || (info.CommandMetadata == null)) { return(null); } if (!string.IsNullOrEmpty(info.CommandMetadata.HelpUri)) { try { return(new Uri(info.CommandMetadata.HelpUri)); } catch (UriFormatException) { throw PSTraceSource.NewInvalidOperationException("HelpErrors", "InvalidURI", new object[] { info.CommandMetadata.HelpUri }); } } } catch (CommandNotFoundException) { } } return(null); }
/// <summary> /// Gets property records from the item. /// </summary> /// <param name="item">The item from which properties are retrieved.</param> protected override void ProcessItem(PSObject item) { var path = item.GetPropertyValue<string>("PSPath"); var providerPath = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); var db = this.OpenDatabase(providerPath); if (null != db) { // Keep track of which properties were selected. IList<string> properties = null; if (this.PassThru) { properties = new List<string>(); } using (db) { TransformView transform = null; if (db.Tables.Contains(TransformView.TableName)) { transform = new TransformView(db); } var table = "Property"; if ((db is PatchPackage) && db.Tables.Contains("MsiPatchMetadata")) { table = "MsiPatchMetadata"; } var query = string.Format("SELECT `Property`, `Value` FROM `{0}`", table); using (var view = db.OpenView(query)) { view.Execute(); // Get column information from the view before being disposed. var columns = ViewManager.GetColumns(view); var record = view.Fetch(); while (null != record) { using (record) { var name = record.GetString(1); if (0 == this.propertyPatterns.Count() || name.Match(this.propertyPatterns)) { if (this.PassThru) { if (0 == item.Properties.Match(name).Count()) { properties.Add(name); var property = new PSNoteProperty(name, record.GetString(2)); item.Properties.Add(property, true); } } else { // Create a locally cached copy of the record. var copy = new Record(record, columns, transform, providerPath); var obj = PSObject.AsPSObject(copy); // Show only column properties by default. var memberSet = ViewManager.GetMemberSet(view); obj.Members.Add(memberSet, true); base.WriteObject(obj); } } } record = view.Fetch(); } } } if (this.PassThru) { var propertySet = new PSPropertySet("MSIProperties", properties); item.Members.Add(propertySet, true); base.WriteObject(item); } } }
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."); } }
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."); } }
/// <summary> /// get the time /// </summary> protected override void ProcessRecord() { DateTime dateToUse = DateTime.Now; int offset; // use passed date object if specified if (_dateSpecified) { dateToUse = Date; } //use passed year if specified if (_yearSpecified) { offset = Year - dateToUse.Year; dateToUse = dateToUse.AddYears(offset); } //use passed month if specified if (_monthSpecified) { offset = Month - dateToUse.Month; dateToUse = dateToUse.AddMonths(offset); } //use passed day if specified if (_daySpecified) { offset = Day - dateToUse.Day; dateToUse = dateToUse.AddDays(offset); } //use passed hour if specified if (_hourSpecified) { offset = Hour - dateToUse.Hour; dateToUse = dateToUse.AddHours(offset); } //use passed minute if specified if (_minuteSpecified) { offset = Minute - dateToUse.Minute; dateToUse = dateToUse.AddMinutes(offset); } //use passed second if specified if (_secondSpecified) { offset = Second - dateToUse.Second; dateToUse = dateToUse.AddSeconds(offset); } //use passed millisecond if specified if (_millisecondSpecified) { offset = Millisecond - dateToUse.Millisecond; dateToUse = dateToUse.AddMilliseconds(offset); dateToUse = dateToUse.Subtract(TimeSpan.FromTicks(dateToUse.Ticks % 10000)); } if (UFormat != null) { //format according to UFormat string WriteObject(UFormatDateString(dateToUse)); } else if (Format != null) { //format according to Format string // Special case built-in primitives: FileDate, FileDateTime. // These are the ISO 8601 "basic" formats, dropping dashes and colons // so that they can be used in file names if (String.Equals("FileDate", Format, StringComparison.OrdinalIgnoreCase)) { Format = "yyyyMMdd"; } else if (String.Equals("FileDateUniversal", Format, StringComparison.OrdinalIgnoreCase)) { dateToUse = dateToUse.ToUniversalTime(); Format = "yyyyMMddZ"; } else if (String.Equals("FileDateTime", Format, StringComparison.OrdinalIgnoreCase)) { Format = "yyyyMMddTHHmmssffff"; } else if (String.Equals("FileDateTimeUniversal", Format, StringComparison.OrdinalIgnoreCase)) { dateToUse = dateToUse.ToUniversalTime(); Format = "yyyyMMddTHHmmssffffZ"; } WriteObject(dateToUse.ToString(Format, CultureInfo.CurrentCulture)); } else { //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); } } // EndProcessing
public override PSMemberInfo Copy() { PSNoteProperty outVal = new PSNoteProperty(Name, Value); CopyProperties(outVal); return outVal; }
private void HandleRemainingArguments(Collection<CommandParameterInternal> arguments) { ArrayList list = new ArrayList(); foreach (CommandParameterInternal internal2 in arguments) { object obj2 = internal2.ArgumentSpecified ? internal2.ArgumentValue : null; if (internal2.ParameterAndArgumentSpecified && internal2.ParameterName.Equals("$args", StringComparison.OrdinalIgnoreCase)) { if (obj2 is object[]) { list.AddRange(obj2 as object[]); } else { list.Add(obj2); } } else { if (internal2.ParameterNameSpecified) { PSObject obj3 = new PSObject(string.Copy(internal2.ParameterText)); if (obj3.Properties["<CommandParameterName>"] == null) { PSNoteProperty member = new PSNoteProperty("<CommandParameterName>", internal2.ParameterName) { isHidden = true }; obj3.Properties.Add(member); } list.Add(obj3); } if (internal2.ArgumentSpecified) { list.Add(obj2); } } } object[] objArray = list.ToArray(); base.DefaultParameterBinder.BindParameter("args", objArray); this.DollarArgs.AddRange(objArray); }
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"; } // // 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; if (ShouldProcess(dateToUse.ToString())) { if (Platform.IsWindows) { #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 } else { Platform.NonWindowsSetDate(dateToUse); } } //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); } // EndProcessing
/// <summary> /// Ensure property info path exists. /// </summary> internal static void EnsurePropertyInfoPathExists(PSObject psObject, string[] path) { if (path.Length <= 0) { return; } // Walk the path and extend it if necessary. for (int i = 0; i < path.Length; ++i) { string propertyName = path[i]; PSPropertyInfo propertyInfo = psObject.Properties[propertyName]; // Add a property info here if none was found. if (propertyInfo == null) { // Add null on the last one, since we don't need to extend path further. object propertyValue = (i < path.Length - 1) ? new PSObject() : null; propertyInfo = new PSNoteProperty(propertyName, propertyValue); psObject.Properties.Add(propertyInfo); } // If we are on the last path element, we are done. Let's not mess with modifying Value. if (i == path.Length - 1) { return; } // If we are not on the last path element, let's make sure we can extend the path. if (propertyInfo.Value == null || !(propertyInfo.Value is PSObject)) { propertyInfo.Value = new PSObject(); } // Now move one step further along the path. psObject = (PSObject)propertyInfo.Value; } }
// NTRAID#Windows Out Of Band Releases-915506-2005/09/09 // Removed HandleUnexpectedExceptions infrastructure private void ReportException(Exception e, Executor exec) { Dbg.Assert(e != null, "must supply an Exception"); Dbg.Assert(exec != null, "must supply an Executor"); // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 // Removed HandleUnexpectedExceptions infrastructure // Attempt to write the exception into the error stream so that the normal F&O machinery will // display it according to preferences. object error = null; Pipeline tempPipeline = exec.CreatePipeline(); // NTRAID#Windows OS Bugs-1143621-2005/04/08-sburns IContainsErrorRecord icer = e as IContainsErrorRecord; if (icer != null) { error = icer.ErrorRecord; } else { error = (object)new ErrorRecord(e, "ConsoleHost.ReportException", ErrorCategory.NotSpecified, null); } PSObject wrappedError = new PSObject(error); PSNoteProperty note = new PSNoteProperty("writeErrorStream", true); wrappedError.Properties.Add(note); Exception e1 = null; tempPipeline.Input.Write(wrappedError); if (IsRunningAsync) { exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter); } else { exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter); } if (e1 != null) { // that didn't work. Write out the error ourselves as a last resort. ReportExceptionFallback(e, null); } }
internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp) { // this object knows Maml format... // So retrieve Uri information as per the format.. if ((commandFullHelp == null) || (commandFullHelp.Properties["relatedLinks"] == null) || (commandFullHelp.Properties["relatedLinks"].Value == null)) { // return the default.. return(null); } PSObject relatedLinks = PSObject.AsPSObject(commandFullHelp.Properties["relatedLinks"].Value); if (relatedLinks.Properties["navigationLink"] == null) { return(null); } object[] navigationLinks = (object[])LanguagePrimitives.ConvertTo( relatedLinks.Properties["navigationLink"].Value, typeof(object[]), CultureInfo.InvariantCulture); foreach (object navigationLinkAsObject in navigationLinks) { if (navigationLinkAsObject == null) { continue; } PSObject navigationLink = PSObject.AsPSObject(navigationLinkAsObject); PSNoteProperty uriNP = navigationLink.Properties["uri"] as PSNoteProperty; if (null != uriNP) { string uriString = string.Empty; LanguagePrimitives.TryConvertTo <string>(uriNP.Value, CultureInfo.InvariantCulture, out uriString); if (!string.IsNullOrEmpty(uriString)) { if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute)) { // WinBlue: 545315 Online help links are broken with localized help // Example: https://go.microsoft.com/fwlink/?LinkID=113324 (möglicherwei se auf Englisch) // Split the string based on <s> (space). We decided to go with this approach as // UX localization authors use spaces. Correctly extracting only the wellformed URI // is out-of-scope for this fix. string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space); uriString = tempUriSplitArray[0]; } try { return(new System.Uri(uriString)); // return only the first Uri (ignore other uris) } catch (UriFormatException) { throw PSTraceSource.NewInvalidOperationException(HelpErrors.InvalidURI, uriString); } } } } return(null); }
protected override void ProcessRecord() { int num; DateTime now = DateTime.Now; if (this.dateSpecified) { now = this.Date; } if (this.yearSpecified) { num = this.Year - now.Year; now = now.AddYears(num); } if (this.monthSpecified) { num = this.Month - now.Month; now = now.AddMonths(num); } if (this.daySpecified) { num = this.Day - now.Day; now = now.AddDays((double) num); } if (this.hourSpecified) { num = this.Hour - now.Hour; now = now.AddHours((double) num); } if (this.minuteSpecified) { num = this.Minute - now.Minute; now = now.AddMinutes((double) num); } if (this.secondSpecified) { num = this.Second - now.Second; now = now.AddSeconds((double) num); } if (this.millisecondSpecified) { num = this.Millisecond - now.Millisecond; now = now.AddMilliseconds((double) num); now = now.Subtract(TimeSpan.FromTicks(now.Ticks % 0x2710L)); } if (this.UFormat != null) { base.WriteObject(this.UFormatDateString(now)); } else if (this.Format != null) { base.WriteObject(now.ToString(this.Format, Thread.CurrentThread.CurrentCulture)); } else { PSObject sendToPipeline = new PSObject(now); PSNoteProperty member = new PSNoteProperty("DisplayHint", this.DisplayHint); sendToPipeline.Properties.Add(member); base.WriteObject(sendToPipeline); } }
/// <summary> /// Wraps the content into a PSObject and adds context information as notes /// </summary> /// /// <param name="content"> /// The content being written out. /// </param> /// /// <param name="readCount"> /// The number of blocks that have been read so far. /// </param> /// /// <param name="pathInfo"> /// The context the content was retrieved from. /// </param> /// /// <param name="context"> /// The context the command is being run under. /// </param> /// internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context) { Dbg.Diagnostics.Assert( content != null, "The caller should verify the content."); Dbg.Diagnostics.Assert( pathInfo != null, "The caller should verify the pathInfo."); Dbg.Diagnostics.Assert( context != null, "The caller should verify the context."); PSObject result = PSObject.AsPSObject(content); Dbg.Diagnostics.Assert( result != null, "A PSObject should always be constructed."); // Use the cached notes if the cache exists and the path is still the same PSNoteProperty note; if (_currentContentItem != null && ((_currentContentItem.PathInfo == pathInfo) || ( String.Compare( pathInfo.Path, _currentContentItem.PathInfo.Path, StringComparison.OrdinalIgnoreCase) == 0) ) ) { result = _currentContentItem.AttachNotes(result); } else { // Generate a new cache item and cache the notes _currentContentItem = new ContentPathsCache(pathInfo); // Construct a provider qualified path as the Path note string psPath = pathInfo.Path; note = new PSNoteProperty("PSPath", psPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath); _currentContentItem.PSPath = psPath; try { // Now get the parent path and child name string parentPath = null; if (pathInfo.Drive != null) { parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context); } else { parentPath = SessionState.Path.ParseParent(pathInfo.Path, String.Empty, context); } note = new PSNoteProperty("PSParentPath", parentPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath); _currentContentItem.ParentPath = parentPath; // Get the child name string childName = SessionState.Path.ParseChildName(pathInfo.Path, context); note = new PSNoteProperty("PSChildName", childName); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName); _currentContentItem.ChildName = childName; } catch (NotSupportedException) { // Ignore. The object just won't have ParentPath or ChildName set. } // PSDriveInfo if (pathInfo.Drive != null) { PSDriveInfo drive = pathInfo.Drive; note = new PSNoteProperty("PSDrive", drive); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive); _currentContentItem.Drive = drive; } // ProviderInfo ProviderInfo provider = pathInfo.Provider; note = new PSNoteProperty("PSProvider", provider); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider); _currentContentItem.Provider = provider; } // Add the ReadCount note note = new PSNoteProperty("ReadCount", readCount); result.Properties.Add(note, true); WriteObject(result); } // WriteContentObject
private PSObject RehydrateCimInstance(PSObject deserializedObject) { CimInstance instance; if (!(deserializedObject.BaseObject is PSCustomObject)) { return deserializedObject; } PSPropertyInfo classMetadataProperty = deserializedObject.InstanceMembers["__ClassMetadata"] as PSPropertyInfo; CimClass cimClass = this.RehydrateCimClass(classMetadataProperty); if (cimClass == null) { return deserializedObject; } try { instance = new CimInstance(cimClass); } catch (CimException) { return deserializedObject; } PSObject obj2 = PSObject.AsPSObject(instance); HashSet<string> namesOfModifiedProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase); PSPropertyInfo info2 = deserializedObject.InstanceMembers["__InstanceMetadata"] as PSPropertyInfo; if ((info2 != null) && (info2.Value != null)) { PSPropertyInfo info3 = PSObject.AsPSObject(info2.Value).InstanceMembers["Modified"] as PSPropertyInfo; if ((info3 != null) && (info3.Value != null)) { foreach (string str2 in info3.Value.ToString().Split(new char[] { ' ' })) { namesOfModifiedProperties.Add(str2); } } } if (deserializedObject.adaptedMembers != null) { foreach (PSMemberInfo info4 in deserializedObject.adaptedMembers) { PSPropertyInfo deserializedProperty = info4 as PSPropertyInfo; if ((deserializedProperty != null) && !this.RehydrateCimInstanceProperty(instance, deserializedProperty, namesOfModifiedProperties)) { return deserializedObject; } } } foreach (PSMemberInfo info6 in deserializedObject.InstanceMembers) { PSPropertyInfo info7 = info6 as PSPropertyInfo; if (((info7 != null) && ((deserializedObject.adaptedMembers == null) || (deserializedObject.adaptedMembers[info7.Name] == null))) && (!info7.Name.Equals("__ClassMetadata", StringComparison.OrdinalIgnoreCase) && (obj2.Properties[info7.Name] == null))) { PSNoteProperty member = new PSNoteProperty(info7.Name, info7.Value); obj2.Properties.Add(member); } } return obj2; }
/// <summary> /// Takes the remaining arguments that haven't been bound, and binds /// them to $args. /// </summary> /// <param name="arguments"> /// The remaining unbound arguments. /// </param> /// <remarks> /// An array containing the values that were bound to $args. /// </remarks> private void HandleRemainingArguments(Collection <CommandParameterInternal> arguments) { List <object> args = new List <object>(); foreach (CommandParameterInternal parameter in arguments) { object argValue = parameter.ArgumentSpecified ? parameter.ArgumentValue : null; // Proper automatic proxy generation requires the ability to prevent unbound arguments // in the proxy from binding to positional parameters in the proxied command. We use // a special key ("$args") when splatting @CommandLineArguments to package up $args. // This special key is not created automatically because it is useful to splat @args, // just not in the automatically generated proxy. // // Example usage: // // function foo { param($a, $b) $a; $b; $args } // function foo_proxy { param($a) ; $CommandLineArguments.Add('$args', $args); foo @CommandLineArguments } // foo_proxy 1 2 3 // // Then in foo, $a=1, $b=, $args=2,3 // // Here, we want $b in foo to be unbound because the proxy doesn't have $b (an Exchange scenario.) // So we pass $args (2,3) in the special entry in @CommandLineArguments. If we had instead written: // // function foo_proxy { param($a) ; foo @CommandLineArguments @args } // foo_proxy 1 2 3 // // Then in foo, $a=1, $b=2, $args=3 // // Note that the name $args is chosen to be: // * descriptive // * obscure (it can't be a property/field name in C#, and is an unlikely variable in script) // So we shouldn't have any real conflict. Note that if someone actually puts ${$args} in their // param block, then the value will be bound and we won't have an unbound argument for "$args" here. if (parameter.ParameterAndArgumentSpecified && parameter.ParameterName.Equals("$args", StringComparison.OrdinalIgnoreCase)) { // $args is normally an object[], but because this feature is accessible from script, it's possible // for it to contain anything. if (argValue is object[]) { args.AddRange(argValue as object[]); } else { args.Add(argValue); } continue; } if (parameter.ParameterNameSpecified) { // Add a property to the string so we can tell the difference between: // foo -abc // foo "-abc" // This is important when splatting, we reconstruct the parameter if the // value is splatted. var parameterText = new PSObject(new string(parameter.ParameterText.ToCharArray())); if (parameterText.Properties[NotePropertyNameForSplattingParametersInArgs] == null) { var noteProperty = new PSNoteProperty(NotePropertyNameForSplattingParametersInArgs, parameter.ParameterName) { IsHidden = true }; parameterText.Properties.Add(noteProperty); } args.Add(parameterText); } if (parameter.ArgumentSpecified) { args.Add(argValue); } } object[] argsArray = args.ToArray(); DefaultParameterBinder.BindParameter(SpecialVariables.Args, argsArray, parameterMetadata: null); DollarArgs.AddRange(argsArray); return; }
private void SetPropertyValueOnHost(string propertyName, object value) { if (_nugetHost != null) { PSPropertyInfo property = _nugetHost.PrivateData.Properties[propertyName]; if (property == null) { property = new PSNoteProperty(propertyName, value); _nugetHost.PrivateData.Properties.Add(property); } else { property.Value = value; } } }