Update files from Source Depot changeset [SD:715912]

Corresponds to 77eda782aa78ba8b7a36c51ee619629ce6c990f2 in psl-monad.
This commit is contained in:
PowerShell Team authored and Andrew Schwartzmeyer committed 2016-06-15 18:02:03 -07:00
1 parent d9b11669ce
commit 8ee6d6ca43
74 files changed
+1376 -1336

No files matched your search

@@ -244,21 +244,6 @@ namespace Extensions
internal static class CIMExtensions
{
/// <summary>
/// An "overload" of the
/// <see cref="Microsoft.Management.Infrastructure.CimSession"/>.QueryInstances
/// method that takes only the query string as a parameter
/// </summary>
/// <param name="session">The CimSession to be queried</param>
/// <param name="query">A string containing the query to be run</param>
/// <returns>
/// An IEnumerable interface that can be used to enumerate the instances
/// </returns>
internal static IEnumerable<CimInstance> QueryInstances(this CimSession session, string query)
{
return session.QueryInstances(CIMHelper.DefaultNamespace, CIMHelper.DefaultQueryDialect, query);
}
/// <summary>
/// An "overload" of the
/// <see cref="Microsoft.Management.Infrastructure.CimSession"/>.QueryInstances
@@ -9,6 +9,7 @@ using System.Runtime.InteropServices;
using System.Reflection;
using System.Linq.Expressions;
using System.Management.Automation;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Management.Infrastructure;
using Microsoft.Win32;
@@ -22,7 +23,8 @@ namespace Microsoft.PowerShell.Commands
/// The Get=ComputerInfo cmdlet gathers and reports information
/// about a computer.
/// </summary>
[Cmdlet(VerbsCommon.Get, "ComputerInfo")]
[Cmdlet(VerbsCommon.Get, "ComputerInfo",
HelpUri = "http://go.microsoft.com/fwlink/?LinkId=799466")]
[Alias("gin")]
public class GetComputerInfoCommand : PSCmdlet
{
@@ -114,6 +116,7 @@ namespace Microsoft.PowerShell.Commands
[Parameter(Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Property { get; set; }
#endregion Parameters
@@ -1290,6 +1293,7 @@ namespace Microsoft.PowerShell.Commands
}
}
#pragma warning disable 649 // fields and properties in these class are assigned dynamically
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiBaseBoard
{
public string Caption;
@@ -1322,6 +1326,7 @@ namespace Microsoft.PowerShell.Commands
public float? Width;
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiBios : WmiClassBase
{
public UInt16[] BiosCharacteristics;
@@ -1356,6 +1361,7 @@ namespace Microsoft.PowerShell.Commands
public string Version;
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiComputerSystem
{
public UInt16? AdminPasswordStatus;
@@ -1438,6 +1444,7 @@ namespace Microsoft.PowerShell.Commands
}
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiDeviceGuard
{
public UInt32[] AvailableSecurityProperties;
@@ -1511,6 +1518,7 @@ namespace Microsoft.PowerShell.Commands
}
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiKeyboard
{
public UInt16? Availability;
@@ -1537,12 +1545,14 @@ namespace Microsoft.PowerShell.Commands
public string SystemName;
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WMiLogicalMemory
{
//TODO: fill this in!!!
public UInt32? TotalPhysicalMemory;
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiMsftNetAdapter
{
public string Caption;
@@ -1630,6 +1640,7 @@ namespace Microsoft.PowerShell.Commands
public bool? AdminLocked;
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiNetworkAdapter
{
public string AdapterType;
@@ -1673,6 +1684,7 @@ namespace Microsoft.PowerShell.Commands
public DateTime? TimeOfLastReset;
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiNetworkAdapterConfiguration
{
public bool? ArpAlwaysSourceRoute;
@@ -1738,6 +1750,7 @@ namespace Microsoft.PowerShell.Commands
public string WINSSecondaryServer;
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiOperatingSystem : WmiClassBase
{
#region Fields
@@ -1849,6 +1862,7 @@ namespace Microsoft.PowerShell.Commands
#endregion Private Methods
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiPageFileUsage
{
public UInt32? AllocatedBaseSize;
@@ -1862,6 +1876,7 @@ namespace Microsoft.PowerShell.Commands
public bool? TempPageFile;
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")]
internal class WmiProcessor
{
public UInt16? AddressWidth;
@@ -1950,27 +1965,32 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Array of required security properties
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public DeviceGuardHardwareSecure[] RequiredSecurityProperties { get; internal set; }
/// <summary>
/// Array of available security properties
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public DeviceGuardHardwareSecure[] AvailableSecurityProperties { get; internal set; }
/// <summary>
/// Indicates which security services have been configured
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public DeviceGuardSoftwareSecure[] SecurityServicesConfigured { get; internal set; }
/// <summary>
/// Indicates which security services are running
/// </summary>
public DeviceGuardSoftwareSecure[] SecurityServicesRunning;
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public DeviceGuardSoftwareSecure[] SecurityServicesRunning { get; internal set; }
/// <summary>
/// Indicates the status of the Device Guard Code Integrity policy
/// </summary>
public DeviceGuardConfigCodeIntegrityStatus? CodeIntegrityPolicyEnforcementStatus;
public DeviceGuardConfigCodeIntegrityStatus? CodeIntegrityPolicyEnforcementStatus { get; internal set; }
/// <summary>
/// Indicates the status of the Device Guard user mode Code Integrity policy
/// </summary>
public DeviceGuardConfigCodeIntegrityStatus? UserModeCodeIntegrityPolicyEnforcementStatus;
public DeviceGuardConfigCodeIntegrityStatus? UserModeCodeIntegrityPolicyEnforcementStatus { get; internal set; }
}
/// <summary>
@@ -1981,19 +2001,42 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Unique identifier associated with a particular update.
/// </summary>
public string HotFixID { get; internal set; }
public string HotFixID
{
get;
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Class is instantiated directly from a CIM instance")]
internal set;
}
/// <summary>
/// Description of the update
/// </summary>
public string Description { get; internal set; }
public string Description
{
get;
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Class is instantiated directly from a CIM instance")]
internal set;
}
/// <summary>
/// String containing the date that the update was installed
/// </summary>
public string InstalledOn { get; internal set; }
public string InstalledOn
{
get;
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Class is instantiated directly from a CIM instance")]
internal set;
}
/// <summary>
/// Additional comments that relate to the update
/// </summary>
public string FixComments { get; internal set; }
public string FixComments
{
get;
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Class is instantiated directly from a CIM instance")]
internal set;
}
}
/// <summary>
@@ -2026,6 +2069,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Array of all of the IP addresses associated with the current network adapter.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] IPAddresses { get; internal set; }
}
@@ -2185,6 +2229,7 @@ namespace Microsoft.PowerShell.Commands
/// Array of BIOS characteristics supported by the system as defined by
/// the System Management BIOS Reference Specification
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public UInt16[] BiosCharacteristics { get; internal set; }
/// <summary>
@@ -2192,6 +2237,7 @@ namespace Microsoft.PowerShell.Commands
/// there can be several version strings that are stored in the registry
/// and represent the system BIOS information
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] BiosBIOSVersion { get; internal set; }
/// <summary>
@@ -2266,6 +2312,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Array of names of available BIOS-installable languages
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] BiosListOfLanguages { get; internal set; }
/// <summary>
@@ -2395,6 +2442,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Status and Additional Data fields that identify the boot status
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public UInt16[] CsBootStatus { get; internal set; }
/// <summary>
@@ -2520,6 +2568,7 @@ namespace Microsoft.PowerShell.Commands
/// An array of <see cref="NetworkAdapter"/> objects describing any
/// network adapters on the system.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public NetworkAdapter[] CsNetworkAdapters { get; internal set; }
/// <summary>
@@ -2547,6 +2596,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Array of <see cref="Processor"/> objects describing each processor on the system.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Processor[] CsProcessors { get; internal set; }
/// <summary>
@@ -2554,6 +2604,7 @@ namespace Microsoft.PowerShell.Commands
/// For example, an OEM defines the part numbers for system reference
/// documents, manufacturer contact information, and so on
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CsOEMStringArray { get; internal set; }
/// <summary>
@@ -2583,6 +2634,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Array of the specific power-related capabilities of a logical device
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public PowerManagementCapabilities[] CsPowerManagementCapabilities { get; internal set; }
/// <summary>
@@ -2645,6 +2697,7 @@ namespace Microsoft.PowerShell.Commands
/// Array that specifies the roles of a system in the information
/// technology environment
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CsRoles { get; internal set; }
/// <summary>
@@ -2655,6 +2708,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Array of the support contact information for the Windows operating system
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CsSupportContactDescription { get; internal set; }
/// <summary>
@@ -2755,6 +2809,7 @@ namespace Microsoft.PowerShell.Commands
/// any Quick-Fix Enginnering patches (Hot Fixes) applied to the operating
/// system
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public HotFix[] OsHotFixes { get; internal set; }
/// <summary>
@@ -2946,6 +3001,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Array of fiel paths to the operating system's paging files
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] OsPagingFiles { get; internal set; }
/// <summary>
@@ -2978,6 +3034,7 @@ namespace Microsoft.PowerShell.Commands
/// Array of Multilingual User Interface Pack (MUI Pack) languages installed
/// on the computer
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] OsMuiLanguages { get; internal set; }
/// <summary>
@@ -3015,6 +3072,7 @@ namespace Microsoft.PowerShell.Commands
/// Array of <see cref="OSProductSuite"/> objects indicating installed
/// and licensed product additions to the operating system
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public OSProductSuite[] OsProductSuites { get; internal set; }
/// <summary>
@@ -3073,6 +3131,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Product suites available on the operating system
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public OSProductSuite[] OsSuites { get; internal set; }
/// <summary>
@@ -3142,21 +3201,25 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Required Device Guard security properties
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public DeviceGuardHardwareSecure[] DeviceGuardRequiredSecurityProperties { get; internal set; }
/// <summary>
/// Available Device Guard security properties
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public DeviceGuardHardwareSecure[] DeviceGuardAvailableSecurityProperties { get; internal set; }
/// <summary>
/// Configured Device Guard security services
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public DeviceGuardSoftwareSecure[] DeviceGuardSecurityServicesConfigured { get; internal set; }
/// <summary>
/// Running Device Guard security services
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public DeviceGuardSoftwareSecure[] DeviceGuardSecurityServicesRunning { get; internal set; }
/// <summary>
@@ -3203,12 +3266,13 @@ namespace Microsoft.PowerShell.Commands
/// Actions related to the BootOptionOn* properties of the Win32_ComputerSystem
/// CIM class
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")]
public enum BootOptionAction
{
/// <summary>
/// This value is reserved
/// </summary>
Reserved = 0,
// <summary>
// This value is reserved
// </summary>
//Reserved = 0,
/// <summary>
/// Boot into operating system
@@ -3229,6 +3293,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Indicates the state of a system element
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")]
public enum SystemElementState
{
/// <summary>
@@ -3306,6 +3371,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Specifies a CPU's availability and status
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")]
public enum CpuAvailability
{
/// <summary>
@@ -3418,6 +3484,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Specifies that current status of the processor
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags", Justification = "The underlying MOF definition is not a bit field.")]
public enum CpuStatus
{
/// <summary>
@@ -3445,15 +3512,15 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
Idle = 4,
/// <summary>
/// This value is reserved
/// </summary>
Reserved_5 = 5,
// <summary>
// This value is reserved
// </summary>
//Reserved_5 = 5,
/// <summary>
/// This value is reserved
/// </summary>
Reserved_6 = 6,
// <summary>
// This value is reserved
// </summary>
//Reserved_6 = 6,
/// <summary>
/// CPU is in another state
@@ -3540,6 +3607,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Device Guard hardware security properties
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")]
public enum DeviceGuardHardwareSecure
{
/// <summary>
@@ -3566,6 +3634,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Device Guard software security properties
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")]
public enum DeviceGuardSoftwareSecure
{
/// <summary>
@@ -3814,6 +3883,8 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Indicates installed and licensed system product additions to the operating system
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")]
[FlagsAttribute]
public enum OSProductSuite
{
/// <summary>
@@ -4696,6 +4767,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Specifies the primary function of a processor
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")]
public enum ProcessorType
{
/// <summary>
@@ -4732,6 +4804,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Specifies a computer's reset capability
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")]
public enum ResetCapability
{
/// <summary>
@@ -4763,12 +4836,13 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Specifies the kind of event that causes a computer to power up
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")]
public enum WakeUpType
{
/// <summary>
/// This value is reserved
/// </summary>
Reserved = 0,
// <summary>
// This value is reserved
// </summary>
//Reserved = 0,
/// <summary>
/// An event other than specified in this enumeration
@@ -4927,7 +5001,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// State of a software element
/// </summary>
public enum SoftwareElementState : UInt16
public enum SoftwareElementState
{
/// <summary>
/// Software element is deployable
@@ -2249,7 +2249,7 @@ namespace Microsoft.PowerShell.Commands
// Wait for the job object to finish
jobObject.WaitOne(waithandle);
}
else
else if (!process.HasExited)
{
// WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower.
process.Exited += new EventHandler(myProcess_Exited);
@@ -1677,6 +1677,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
///
/// </summary>
[ArchitectureSensitive]
protected override void ProcessRecord()
{
@@ -2064,6 +2065,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Create the service
/// </summary>
[ArchitectureSensitive]
protected override void BeginProcessing()
{
Diagnostics.Assert(!String.IsNullOrEmpty(Name),
@@ -347,7 +347,7 @@ namespace Microsoft.PowerShell.Commands
string activeExtension = null;
foreach (string path in resolvedPaths)
{
string currentExtension = System.IO.Path.GetExtension(path).ToUpper();
string currentExtension = System.IO.Path.GetExtension(path).ToUpperInvariant();
switch (currentExtension)
{
@@ -1063,10 +1063,20 @@ namespace Microsoft.PowerShell.Commands
private static PortableExecutableReference ObjectDeclaredAssemblyReference =
MetadataReference.CreateFromFile(ClrFacade.GetAssemblies(typeof(object).FullName).First().Location);
// CoreCLR RC2 bits don't have SecureString. We are using a separate assembly with SecureString implementation.
// This fact is an implementation detail and should not require the user to specify one more assembly,
// if they want to use SecureString in Add-Type -TypeDefinition.
// So this assembly should be in the default assemblies list to provide the best experience.
//
// TODO: This reference should be removed, if we take CoreCLR version that has SecureString implementation.
private static PortableExecutableReference SecureStringAssemblyReference =
MetadataReference.CreateFromFile(typeof(System.Security.SecureString).GetTypeInfo().Assembly.Location);
private static MetadataReference[] defaultAssemblies = new MetadataReference[]
{
ObjectImplementationAssemblyReference,
ObjectDeclaredAssemblyReference,
SecureStringAssemblyReference,
MetadataReference.CreateFromFile(typeof(PSObject).GetTypeInfo().Assembly.Location)
};
@@ -1210,6 +1220,7 @@ namespace Microsoft.PowerShell.Commands
var tempReferences = ReferencedAssemblies.Select(a => MetadataReference.CreateFromFile(ResolveReferencedAssembly(a))).ToList();
tempReferences.Add(ObjectImplementationAssemblyReference);
tempReferences.Add(ObjectDeclaredAssemblyReference);
tempReferences.Add(SecureStringAssemblyReference);
references = tempReferences.ToArray();
}
@@ -2526,7 +2526,7 @@ function Get-PSImplicitRemotingSession
)
";
// index 0 - "-ContainerId <container id>" (ContainerId is used instead of ContainerName due to its uniqueness)
// index 0 - "-ContainerId <container id>"
// index 1 - "-RunAsAdministrator" or empty string
// index 2 - "-ConfigurationName <configuration name>" or empty string
private const string NewContainerRunspaceTemplate = @"
@@ -83,6 +83,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// set the date
/// </summary>
[ArchitectureSensitive]
protected override void ProcessRecord()
{
DateTime dateToUse;
@@ -171,4 +171,7 @@
<data name="CouldNotParseAsPowerShellDataFile" xml:space="preserve">
<value>The file '{0}' could not be parsed as a PowerShell Data File.</value>
</data>
<data name="TypeNotSupported" xml:space="preserve">
<value>'{0}' is not supported in this system.</value>
</data>
</root>
@@ -623,29 +623,6 @@ namespace Microsoft.PowerShell
return _outputHandle.Value;
}
internal enum StandardHandleId : uint
{
// From winnt.h
// #define STD_INPUT_HANDLE ((DWORD)-10)
// #define STD_OUTPUT_HANDLE ((DWORD)-11)
// #define STD_ERROR_HANDLE ((DWORD)-12)
Input = 0xFFFFFFF6,
Output = 0xFFFFFFF5,
Error = 0xFFFFFFF4
}
internal static NakedWin32Handle GetStdHandle(StandardHandleId handleId)
{
unchecked
{
// Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to
// get the error code.
#pragma warning disable 56523
return NativeMethods.GetStdHandle((DWORD)handleId);
}
}
#endregion
#region Mode
@@ -3492,9 +3469,6 @@ namespace Microsoft.PowerShell
[DllImport(PinvokeDllNames.GetLargestConsoleWindowSizeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern COORD GetLargestConsoleWindowSize(NakedWin32Handle consoleOutput);
[DllImport(PinvokeDllNames.GetStdHandleDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern NakedWin32Handle GetStdHandle(DWORD handleId);
[DllImport(PinvokeDllNames.ReadConsoleDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool ReadConsole
(
@@ -1421,7 +1421,7 @@ namespace Microsoft.PowerShell
if (ExitCode == ExitCodeInitFailure) { break; }
if (!noExit && !ui.ReadFromStdin)
if (!noExit && (!ui.ReadFromStdin || Console.In.Peek() == -1))
{
// Wait for runspace to open, init, and run init script before
// setting ShouldEndSession, to allow debugger to work.
@@ -4,6 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Threading;
using System.Reflection;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
@@ -34,6 +35,13 @@ namespace Microsoft.PowerShell
public int Start(string consoleFilePath, string[] args)
#endif
{
#if !CORECLR
// For long-path support, Full .NET requires some AppContext switches;
// (for CoreCLR this is Not needed, because CoreCLR supports long paths by default)
// internally in .NET they are cached once retrieved and are typically hit very early during an application run;
// so per .NET team's recommendation, we are setting them as soon as we enter managed code.
EnableLongPathsInDotNetIfAvailable();
#endif
System.Management.Automation.Runspaces.EarlyStartup.Init();
// Set ETW activity Id
@@ -152,6 +160,27 @@ namespace Microsoft.PowerShell
#endif
}
}
#if !CORECLR
private static void EnableLongPathsInDotNetIfAvailable()
{
// We build against CLR4.5 so we can run on Win7/Win8, but we want to use apis added to CLR 4.6, so we use reflection
try
{
Type appContextType = Type.GetType("System.AppContext"); // type is in mscorlib, so it is sufficient to supply the type name qualified by its namespace
object[] blockLongPathsSwitch = new object[] { "Switch.System.IO.BlockLongPaths", false };
object[] useLegacyPathHandlingSwitch = new object[] { "Switch.System.IO.UseLegacyPathHandling", false };
appContextType.InvokeMember("SetSwitch", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, blockLongPathsSwitch);
appContextType.InvokeMember("SetSwitch", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, useLegacyPathHandlingSwitch);
}
catch
{
// If there are any exceptions (e.g. we are running on CLR prior to 4.6.2), we won't be able to use long paths
}
}
#endif
}
}
@@ -233,7 +233,7 @@ namespace Microsoft.PowerShell.Commands
System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
this.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool());
Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool(), this.Context.CurrentRunspace.InstanceId);
// ch.StartTranscribing(effectiveFilePath, Append);
@@ -249,7 +249,7 @@ namespace Microsoft.PowerShell.Commands
{
try
{
Host.UI.StopTranscribing();
Host.UI.StopTranscribing(this.Context.CurrentRunspace.InstanceId);
}
catch
{
@@ -35,7 +35,7 @@ namespace Microsoft.PowerShell.Commands
{
try
{
string outFilename = Host.UI.StopTranscribing();
string outFilename = Host.UI.StopTranscribing(this.Context.CurrentRunspace.InstanceId);
if (outFilename != null)
{
PSObject outputObject = new PSObject(
@@ -294,15 +294,6 @@ namespace Microsoft.PowerShell.Commands
#endregion Cmdlet Overrides
#region Private Methods
private LocalUser GetUser()
{
if (InputObject != null)
return InputObject;
return SID != null ? sam.GetLocalUser(SID)
: sam.GetLocalUser(Name);
}
private bool CheckShouldProcess(string target)
{
return ShouldProcess(target, Strings.ActionSetUser);
@@ -267,7 +267,11 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
public class InvalidParametersException : LocalAccountsException
{
internal InvalidParametersException(string message)
/// <summary>
/// Creates InvalidParametersException using the specified message.
/// </summary>
/// <param name="message"></param>
public InvalidParametersException(string message)
: base(message, null, ErrorCategory.InvalidArgument)
{
}
@@ -30,7 +30,7 @@ namespace System.Management.Automation.SecurityAccountsManager.Extensions
bool allowSidConstants = false)
{
if (!allowSidConstants)
if (!(s.Length > 2 && s.StartsWith("S-") && Char.IsDigit(s[2])))
if (!(s.Length > 2 && s.StartsWith("S-", StringComparison.Ordinal) && Char.IsDigit(s[2])))
return null;
SecurityIdentifier sid = null;
@@ -144,21 +144,7 @@ namespace System.Management.Automation.SecurityAccountsManager.Extensions
}
internal static class SecureStringExtensions
{
private static Regex pwRegex = new Regex(@"^[^\x00-\x1F""/\\\[\]:;\|=,+\*?<>@]{0,127}$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
internal static bool IsValidPassword(this SecureString str)
{
return str.Length == 0 || pwRegex.IsMatch(str.AsString());
}
internal static void ValidatePassword(this SecureString str)
{
if (!str.IsValidPassword())
throw new InvalidPasswordException();
}
{
/// <summary>
/// Extension method to extract clear text from a
/// <see cref="System.Security.SecureString"/> object.
@@ -149,37 +149,7 @@ namespace System.Management.Automation.SecurityAccountsManager.Native
public IntPtr SecurityQualityOfService;
private IntPtr objectName;
public OBJECT_ATTRIBUTES(string name, uint attrs)
{
Length = 0;
RootDirectory = IntPtr.Zero;
objectName = IntPtr.Zero;
Attributes = attrs;
SecurityDescriptor = IntPtr.Zero;
SecurityQualityOfService = IntPtr.Zero;
Length = ClrFacade.SizeOf<OBJECT_ATTRIBUTES>();
ObjectName = new UNICODE_STRING(name);
}
public UNICODE_STRING ObjectName
{
get
{
return ClrFacade.PtrToStructure<UNICODE_STRING>(objectName);
}
set
{
bool fDeleteOld = objectName != IntPtr.Zero;
if (!fDeleteOld)
objectName = Marshal.AllocHGlobal(Marshal.SizeOf(value));
Marshal.StructureToPtr(value, objectName, fDeleteOld);
}
}
public UNICODE_STRING ObjectName;
public void Dispose()
{
@@ -463,8 +433,6 @@ namespace System.Management.Automation.SecurityAccountsManager.Native
ref uint domainNameLength,
out SID_NAME_USE peUse);
[DllImport(PInvokeDllNames.GetComputerNameDllName, CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern bool GetComputerName(StringBuilder name, ref uint size);
[DllImport(PInvokeDllNames.GetSecurityDescriptorDaclDllName, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
@@ -484,7 +452,7 @@ namespace System.Management.Automation.SecurityAccountsManager.Native
[MarshalAs(UnmanagedType.Bool)]
bool bDaclDefaulted);
[DllImport(PInvokeDllNames.FormatMessageDllName, SetLastError = true)]
[DllImport(PInvokeDllNames.FormatMessageDllName, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern uint FormatMessage(uint dwFlags,
IntPtr lpSource,
uint dwMessageId,
@@ -1,4 +1,6 @@

using System.Diagnostics.CodeAnalysis;
namespace System.Management.Automation.SecurityAccountsManager.Native
{
internal static class NtStatus
@@ -451,6 +453,7 @@ namespace System.Management.Automation.SecurityAccountsManager.Native
return Severity(ntstatus) == STATUS_SEVERITY_ERROR;
}
/// <summary>
/// Determine if an NTSTATUS value indicates a Warning
/// </summary>
@@ -458,6 +461,7 @@ namespace System.Management.Automation.SecurityAccountsManager.Native
/// <returns>
/// True if the NTSTATUS value indicates a warning, false otherwise.
/// </returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static bool IsWarning(UInt32 ntstatus)
{
return Severity(ntstatus) == STATUS_SEVERITY_WARNING;
@@ -470,11 +474,12 @@ namespace System.Management.Automation.SecurityAccountsManager.Native
/// <returns>
/// True if the NTSTATUS value indicates that it is informational, false otherwise.
/// </returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static bool IsInformational(UInt32 ntstatus)
{
return Severity(ntstatus) == STATUS_SEVERITY_INFORMATIONAL;
}
/// <summary>
/// Return the Severity part of an NTSTATUS value
@@ -488,6 +493,7 @@ namespace System.Management.Automation.SecurityAccountsManager.Native
return ntstatus >> 30;
}
/// <summary>
/// Return the Facility part of an NSTATUS value
/// </summary>
@@ -495,11 +501,14 @@ namespace System.Management.Automation.SecurityAccountsManager.Native
/// <returns>
/// The value of the Facility portion of an NTSTATUS value.
/// </returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static uint Facility(UInt32 ntstatus)
{
return (ntstatus >> 16) & 0x0FFF;
}
/// <summary>
/// Return the Code part of an NTSTATUS value
/// </summary>
@@ -507,10 +516,12 @@ namespace System.Management.Automation.SecurityAccountsManager.Native
/// <returns>
/// The value of the Code portion of an NTSTATUS value.
/// </returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static uint Code(UInt32 ntstatus)
{
return ntstatus & 0xFFFF;
}
#endregion Public Methods
}
}
@@ -11,6 +11,9 @@ using System.Management.Automation.SecurityAccountsManager.Native.NtSam;
using System.Text;
using Microsoft.PowerShell.LocalAccounts;
using System.Diagnostics.CodeAnalysis;
[module: SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant")]
namespace System.Management.Automation.SecurityAccountsManager
{
@@ -262,6 +265,7 @@ namespace System.Management.Automation.SecurityAccountsManager
/// <summary>
/// Gets a string containing the type of operation under way.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string OperationName
{
get { return operation.ToString(); }
@@ -271,6 +275,7 @@ namespace System.Management.Automation.SecurityAccountsManager
/// Gets a string containing the type of object ("User" or "Group")
/// being used.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string TypeNamne
{
get { return type.ToString(); }
@@ -1083,31 +1088,6 @@ namespace System.Management.Automation.SecurityAccountsManager
}
}
/// <summary>
/// Find a named group and return a <see cref="SamRidEnumeration"/> object
/// representing the group.
/// </summary>
/// <param name="groupName">Name of the group to search for.</param>
/// <returns>
/// A SamRidEnumeration object representing the group.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown when the specified group is not found.
/// </exception>
/// <remarks>
/// This method saves some time and effort over the GetGroup method
/// because it does not have to open a group to populate a full Group
/// object.
/// </remarks>
private SamRidEnumeration GetGroupSre(string groupName)
{
foreach (var sre in EnumerateGroups())
if (sre.Name.Equals(groupName, StringComparison.CurrentCultureIgnoreCase))
return sre;
throw new GroupNotFoundException(groupName, context.target);
}
/// <summary>
/// Find a group by SID and return a <see cref="SamRidEnumeration"/> object
/// representing the group.
@@ -1134,31 +1114,6 @@ namespace System.Management.Automation.SecurityAccountsManager
throw new GroupNotFoundException(sid.ToString(), sid);
}
/// <summary>
/// Find a named user and return a <see cref="SamRidEnumeration"/> object
/// representing the user.
/// </summary>
/// <param name="userName">Name of the user to search for.</param>
/// <returns>
/// A SamRidEnumeration object representing the user.
/// </returns>
/// <exception cref="UserNotFoundException">
/// Thrown when the specified user is not found.
/// </exception>
/// <remarks>
/// This method saves some time and effort over the GetUser method
/// because it does not have to open a group to populate a full LocalUser
/// object.
/// </remarks>
private SamRidEnumeration GetUserSre(string userName)
{
foreach (var sre in EnumerateGroups())
if (sre.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase))
return sre;
throw new GroupNotFoundException(userName, userName);
}
/// <summary>
/// Find a user by SID and return a <see cref="SamRidEnumeration"/> object
/// representing the user.
@@ -1205,14 +1160,12 @@ namespace System.Management.Automation.SecurityAccountsManager
do
{
status = SamApi.SamEnumerateUsersInDomain2(domainHandle,
ref context,
0,
SamApi.SAM_USER_ENUMERATION_FILTER_LOCAL,
//0, // non-filtered
out buffer,
1,
out countReturned);
status = SamApi.SamEnumerateUsersInDomain(domainHandle,
ref context,
0,
out buffer,
1,
out countReturned);
if (status == NtStatus.STATUS_MORE_ENTRIES && countReturned == 1)
{
@@ -1350,6 +1303,8 @@ namespace System.Management.Automation.SecurityAccountsManager
status = SamApi.SamDeleteAlias(aliasHandle);
ThrowOnFailure(status);
aliasHandle = IntPtr.Zero; // The handle is freed internally if SamDeleteAlias succeeds
}
finally
{
@@ -1829,6 +1784,8 @@ namespace System.Management.Automation.SecurityAccountsManager
status = SamApi.SamDeleteUser(userHandle);
ThrowOnFailure(status);
userHandle = IntPtr.Zero; // The handle is freed internally if SamDeleteUser succeeds
}
finally
{
@@ -2677,7 +2634,7 @@ namespace System.Management.Automation.SecurityAccountsManager
try
{
SamApi.SamRidToSid(domainHandle, rid, out sidBytes);
status = SamApi.SamRidToSid(domainHandle, rid, out sidBytes);
if (status == NtStatus.STATUS_NOT_FOUND)
throw new InternalException(status,
@@ -2808,7 +2765,7 @@ namespace System.Management.Automation.SecurityAccountsManager
// Ideally , accountname should be processed to hold only accout name (without domain)
// as we are keeping the domain in 'DomainName' variable.
int index = accountName.IndexOf("\\");
int index = accountName.IndexOf("\\", StringComparison.CurrentCultureIgnoreCase);
if (index > -1)
{
accountName = accountName.Substring(index + 1);
@@ -407,60 +407,16 @@ namespace System.Management.Automation.SecurityAccountsManager.Native.NtSam
internal static extern UInt32 SamAddMemberToAlias(IntPtr aliasHandle,
byte[] memberId); // PSID
[DllImport("samlib.dll")]
internal static extern UInt32 SamAddMultipleMembersToAlias(IntPtr aliasHandle,
IntPtr memberIds, // PSID
UInt32 memberCount);
[DllImport("samlib.dll")]
internal static extern UInt32 SamRemoveMemberFromAlias(IntPtr aliasHandle,
byte[] memberId); // PSID
[DllImport("samlib.dll")]
internal static extern UInt32 SamRemoveMultipleMembersFromAlias(IntPtr aliasHandle,
IntPtr memberIds, // PSID
UInt32 memberCount);
[DllImport("samlib.dll")]
internal static extern UInt32 SamGetMembersInAlias(IntPtr aliasHandle,
out IntPtr memberIds, // PSID **
out UInt32 memberCount);
#endregion Alias Functions
#region Group Functions
[DllImport("samlib.dll")]
internal static extern UInt32 SamEnumerateGroupsInDomain(IntPtr domainHandle,
ref UInt32 enumerationContext,
out IntPtr buffer,
UInt32 preferredMaximumLength,
out UInt32 countReturned);
[DllImport("samlib.dll")]
internal static extern UInt32 SamCreateGroupInDomain(IntPtr domainHandle,
ref UNICODE_STRING accountName,
UInt32 desiredAccess,
out IntPtr groupHandle,
out UInt32 relativeId);
[DllImport("samlib.dll")]
internal static extern UInt32 SamOpenGroup(IntPtr domainHandle,
UInt32 desiredAccess,
UInt32 groupId,
out IntPtr groupHandle);
[DllImport("samlib.dll")]
internal static extern UInt32 SamQueryInformationGroup(IntPtr groupHandle,
GROUP_INFORMATION_CLASS groupInformationClass,
out IntPtr buffer);
[DllImport("samlib.dll")]
internal static extern UInt32 SamSetInformationGroup(IntPtr groupHandle,
GROUP_INFORMATION_CLASS groupInformationClass,
IntPtr buffer);
#endregion Group Functions
#region User Functions
[DllImport("samlib.dll")]
internal static extern UInt32 SamOpenUser(IntPtr domainHandle,
@@ -479,22 +435,6 @@ namespace System.Management.Automation.SecurityAccountsManager.Native.NtSam
UInt32 preferredMaximumLength,
out UInt32 countReturned);
[DllImport("samlib.dll")]
internal static extern UInt32 SamEnumerateUsersInDomain2(IntPtr domainHandle,
ref UInt32 enumerationContext,
UInt32 userAccountControl,
UInt32 filter,
out IntPtr buffer,
UInt32 preferredMaximumLength,
out UInt32 countReturned);
[DllImport("samlib.dll")]
internal static extern UInt32 SamCreateUserInDomain(IntPtr domainHandle,
ref UNICODE_STRING accountName,
UInt32 desiredAccess,
out IntPtr userHandle,
out UInt32 relativeId);
[DllImport("samlib.dll")]
internal static extern UInt32 SamCreateUser2InDomain(IntPtr domainHandle,
ref UNICODE_STRING accountName,
@@ -8,6 +8,14 @@ namespace System.Management.Automation.SecurityAccountsManager
/// </summary>
internal class StringUtil
{
/// <summary>
/// Private constructor to precent auto-generation of a default constructor with greater accessability.
/// </summary>
private StringUtil()
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static string Format(string str)
{
return string.Format(CultureInfo.CurrentCulture, str);
@@ -3843,6 +3843,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// get a list of store names at the specified location
/// </summary>
[ArchitectureSensitive]
internal static List<string> GetStoreNamesAtLocation(StoreLocation location)
{
Security.NativeMethods.CertStoreFlags locationFlag =
@@ -83,6 +83,7 @@ namespace Microsoft.PowerShell.Commands
/// digital signature.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] SourcePathOrExtension
{
get
@@ -622,4 +623,4 @@ namespace Microsoft.PowerShell.Commands
return SigningOption.AddFullCertificateChainExceptRoot;
}
}
}
}
@@ -131,6 +131,7 @@ namespace Microsoft.PowerShell
///
/// <remarks> </remarks>
///
[ArchitectureSensitive]
internal static string GetStringFromSecureString(SecureString ss)
{
IntPtr p = Marshal.SecureStringToGlobalAllocUnicode(ss);
@@ -572,7 +572,7 @@ function ConvertFrom-SddlString
[CmdletBinding(HelpUri = "http://go.microsoft.com/fwlink/?LinkId=623636")]
param(
## The string representing the security descriptor in SDDL syntax
[Parameter(Mandatory, Position = 0)]
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[String] $Sddl,
## The type of rights that this SDDL string represents, if any.
@@ -584,126 +584,157 @@ function ConvertFrom-SddlString
$Type
)
## Translates a SID into a NT Account
function ConvertTo-NtAccount
Begin
{
param($Sid)
if($Sid)
# On CoreCLR CryptoKeyRights and ActiveDirectoryRights are not supported.
if ($PSEdition -eq "Core" -and ($Type -eq "CryptoKeyRights" -or $Type -eq "ActiveDirectoryRights"))
{
$securityIdentifier = [System.Security.Principal.SecurityIdentifier] $Sid
try
$errorId = "TypeNotSupported"
$errorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument
$errorMessage = [Microsoft.PowerShell.Commands.UtilityResources]::TypeNotSupported -f $Type
$exception = [System.ArgumentException]::New($errorMessage)
$errorRecord = [System.Management.Automation.ErrorRecord]::New($exception, $errorId, $errorCategory, $null)
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
## Translates a SID into a NT Account
function ConvertTo-NtAccount
{
param($Sid)
if($Sid)
{
$ntAccount = $securityIdentifier.Translate([System.Security.Principal.NTAccount]).ToString()
}
catch{}
$ntAccount
}
}
## Gets the access rights that apply to an access mask, preferring right types
## of 'Type' if specified.
function Get-AccessRights
{
param($AccessMask, $Type)
## All the types of access rights understood by .NET
$rightTypes = [Ordered] @{
"FileSystemRights" = [System.Security.AccessControl.FileSystemRights]
"RegistryRights" = [System.Security.AccessControl.RegistryRights]
"ActiveDirectoryRights" = [System.DirectoryServices.ActiveDirectoryRights]
"MutexRights" = [System.Security.AccessControl.MutexRights]
"SemaphoreRights" = [System.Security.AccessControl.SemaphoreRights]
"CryptoKeyRights" = [System.Security.AccessControl.CryptoKeyRights]
"EventWaitHandleRights" = [System.Security.AccessControl.EventWaitHandleRights]
}
$typesToExamine = $rightTypes.Values
$securityIdentifier = [System.Security.Principal.SecurityIdentifier] $Sid
## If they know the access mask represents a certain type, prefer its names
## (i.e.: CreateLink for the registry over CreateDirectories for the filesystem)
if($Type)
{
$typesToExamine = @($rightTypes[$Type]) + $typesToExamine
try
{
$ntAccount = $securityIdentifier.Translate([System.Security.Principal.NTAccount]).ToString()
}
catch{}
$ntAccount
}
}
## Gets the access rights that apply to an access mask, preferring right types
## of 'Type' if specified.
function Get-AccessRights
{
param($AccessMask, $Type)
if ($PSEdition -eq "Core")
{
## All the types of access rights understood by .NET Core
$rightTypes = [Ordered] @{
"FileSystemRights" = [System.Security.AccessControl.FileSystemRights]
"RegistryRights" = [System.Security.AccessControl.RegistryRights]
"MutexRights" = [System.Security.AccessControl.MutexRights]
"SemaphoreRights" = [System.Security.AccessControl.SemaphoreRights]
"EventWaitHandleRights" = [System.Security.AccessControl.EventWaitHandleRights]
}
}
else
{
## All the types of access rights understood by .NET
$rightTypes = [Ordered] @{
"FileSystemRights" = [System.Security.AccessControl.FileSystemRights]
"RegistryRights" = [System.Security.AccessControl.RegistryRights]
"ActiveDirectoryRights" = [System.DirectoryServices.ActiveDirectoryRights]
"MutexRights" = [System.Security.AccessControl.MutexRights]
"SemaphoreRights" = [System.Security.AccessControl.SemaphoreRights]
"CryptoKeyRights" = [System.Security.AccessControl.CryptoKeyRights]
"EventWaitHandleRights" = [System.Security.AccessControl.EventWaitHandleRights]
}
}
$typesToExamine = $rightTypes.Values
## If they know the access mask represents a certain type, prefer its names
## (i.e.: CreateLink for the registry over CreateDirectories for the filesystem)
if($Type)
{
$typesToExamine = @($rightTypes[$Type]) + $typesToExamine
}
## Stores the access types we've found that apply
$foundAccess = @()
## Stores the access types we've found that apply
$foundAccess = @()
## Store the access types we've already seen, so that we don't report access
## flags that are essentially duplicate. Many of the access values in the different
## enumerations have the same value but with different names.
$foundValues = @{}
## Store the access types we've already seen, so that we don't report access
## flags that are essentially duplicate. Many of the access values in the different
## enumerations have the same value but with different names.
$foundValues = @{}
## Go through the entries in the different right types, and see if they apply to the
## provided access mask. If they do, then add that to the result.
foreach($rightType in $typesToExamine)
{
foreach($accessFlag in [Enum]::GetNames($rightType))
## Go through the entries in the different right types, and see if they apply to the
## provided access mask. If they do, then add that to the result.
foreach($rightType in $typesToExamine)
{
$longKeyValue = [long] $rightType::$accessFlag
if(-not $foundValues.ContainsKey($longKeyValue))
foreach($accessFlag in [Enum]::GetNames($rightType))
{
$foundValues[$longKeyValue] = $true
if(($AccessMask -band $longKeyValue) -eq ($longKeyValue))
$longKeyValue = [long] $rightType::$accessFlag
if(-not $foundValues.ContainsKey($longKeyValue))
{
$foundAccess += $accessFlag
$foundValues[$longKeyValue] = $true
if(($AccessMask -band $longKeyValue) -eq ($longKeyValue))
{
$foundAccess += $accessFlag
}
}
}
}
$foundAccess | Sort-Object
}
$foundAccess | Sort-Object
## Converts an ACE into a string representation
function ConvertTo-AceString
{
param(
[Parameter(ValueFromPipeline)]
$Ace,
$Type
)
process
{
foreach($aceEntry in $Ace)
{
$AceString = (ConvertTo-NtAccount $aceEntry.SecurityIdentifier) + ": " + $aceEntry.AceQualifier
if($aceEntry.AceFlags -ne "None")
{
$AceString += " " + $aceEntry.AceFlags
}
if($aceEntry.AccessMask)
{
$foundAccess = Get-AccessRights $aceEntry.AccessMask $Type
if($foundAccess)
{
$AceString += " ({0})" -f ($foundAccess -join ", ")
}
}
$AceString
}
}
}
}
## Converts an ACE into a string representation
function ConvertTo-AceString
Process
{
param(
[Parameter(ValueFromPipeline)]
$Ace,
$Type
)
$rawSecurityDescriptor = [Security.AccessControl.CommonSecurityDescriptor]::new($false,$false,$Sddl)
process
{
foreach($aceEntry in $Ace)
{
$AceString = (ConvertTo-NtAccount $aceEntry.SecurityIdentifier) + ": " + $aceEntry.AceQualifier
if($aceEntry.AceFlags -ne "None")
{
$AceString += " " + $aceEntry.AceFlags
}
$owner = ConvertTo-NtAccount $rawSecurityDescriptor.Owner
$group = ConvertTo-NtAccount $rawSecurityDescriptor.Group
$discretionaryAcl = ConvertTo-AceString $rawSecurityDescriptor.DiscretionaryAcl $Type
$systemAcl = ConvertTo-AceString $rawSecurityDescriptor.SystemAcl $Type
if($aceEntry.AccessMask)
{
$foundAccess = Get-AccessRights $aceEntry.AccessMask $Type
if($foundAccess)
{
$AceString += " ({0})" -f ($foundAccess -join ", ")
}
}
$AceString
}
[PSCustomObject] @{
Owner = $owner
Group = $group
DiscretionaryAcl = @($discretionaryAcl)
SystemAcl = @($systemAcl)
RawDescriptor = $rawSecurityDescriptor
}
}
$rawSecurityDescriptor = [Security.AccessControl.CommonSecurityDescriptor]::new($false,$false,$Sddl)
$owner = ConvertTo-NtAccount $rawSecurityDescriptor.Owner
$group = ConvertTo-NtAccount $rawSecurityDescriptor.Group
$discretionaryAcl = ConvertTo-AceString $rawSecurityDescriptor.DiscretionaryAcl $Type
$systemAcl = ConvertTo-AceString $rawSecurityDescriptor.SystemAcl $Type
[PSCustomObject] @{
Owner = $owner
Group = $group
DiscretionaryAcl = @($discretionaryAcl)
SystemAcl = @($systemAcl)
RawDescriptor = $rawSecurityDescriptor
}
}
}
Binary file not shown.
Binary file not shown.
+499 -219
View File
@@ -405,8 +405,11 @@ $source = @"
using System;
using System.Net;
using System.Management.Automation;
using Microsoft.Win32.SafeHandles;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
namespace Microsoft.PowerShell.Get
namespace Microsoft.PowerShell.Commands.PowerShellGet
{
public static class Telemetry
{
@@ -462,6 +465,96 @@ namespace Microsoft.PowerShell.Get
return false;
}
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct CERT_CHAIN_POLICY_PARA {
public CERT_CHAIN_POLICY_PARA(int size) {
cbSize = (uint) size;
dwFlags = 0;
pvExtraPolicyPara = IntPtr.Zero;
}
public uint cbSize;
public uint dwFlags;
public IntPtr pvExtraPolicyPara;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct CERT_CHAIN_POLICY_STATUS {
public CERT_CHAIN_POLICY_STATUS(int size) {
cbSize = (uint) size;
dwError = 0;
lChainIndex = IntPtr.Zero;
lElementIndex = IntPtr.Zero;
pvExtraPolicyStatus = IntPtr.Zero;
}
public uint cbSize;
public uint dwError;
public IntPtr lChainIndex;
public IntPtr lElementIndex;
public IntPtr pvExtraPolicyStatus;
}
public class Win32Helpers
{
[DllImport("Crypt32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public extern static
bool CertVerifyCertificateChainPolicy(
[In] IntPtr pszPolicyOID,
[In] SafeX509ChainHandle pChainContext,
[In] ref CERT_CHAIN_POLICY_PARA pPolicyPara,
[In,Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus);
[DllImport("Crypt32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern
SafeX509ChainHandle CertDuplicateCertificateChain(
[In] IntPtr pChainContext);
public static bool IsMicrosoftCertificate([In] SafeX509ChainHandle pChainContext)
{
//-------------------------------------------------------------------------
// CERT_CHAIN_POLICY_MICROSOFT_ROOT
//
// Checks if the last element of the first simple chain contains a
// Microsoft root public key. If it doesn't contain a Microsoft root
// public key, dwError is set to CERT_E_UNTRUSTEDROOT.
//
// pPolicyPara is optional. However,
// MICROSOFT_ROOT_CERT_CHAIN_POLICY_ENABLE_TEST_ROOT_FLAG can be set in
// the dwFlags in pPolicyPara to also check for the Microsoft Test Roots.
//
// MICROSOFT_ROOT_CERT_CHAIN_POLICY_CHECK_APPLICATION_ROOT_FLAG can be set
// in the dwFlags in pPolicyPara to check for the Microsoft root for
// application signing instead of the Microsoft product root. This flag
// explicitly checks for the application root only and cannot be combined
// with the test root flag.
//
// MICROSOFT_ROOT_CERT_CHAIN_POLICY_DISABLE_FLIGHT_ROOT_FLAG can be set
// in the dwFlags in pPolicyPara to always disable the Flight root.
//
// pvExtraPolicyPara and pvExtraPolicyStatus aren't used and must be set
// to NULL.
//--------------------------------------------------------------------------
const uint MICROSOFT_ROOT_CERT_CHAIN_POLICY_ENABLE_TEST_ROOT_FLAG = 0x00010000;
//const uint MICROSOFT_ROOT_CERT_CHAIN_POLICY_CHECK_APPLICATION_ROOT_FLAG = 0x00020000;
//const uint MICROSOFT_ROOT_CERT_CHAIN_POLICY_DISABLE_FLIGHT_ROOT_FLAG = 0x00040000;
CERT_CHAIN_POLICY_PARA PolicyPara = new CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CERT_CHAIN_POLICY_PARA)));
CERT_CHAIN_POLICY_STATUS PolicyStatus = new CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CERT_CHAIN_POLICY_STATUS)));
int CERT_CHAIN_POLICY_MICROSOFT_ROOT = 7;
PolicyPara.dwFlags = (uint) MICROSOFT_ROOT_CERT_CHAIN_POLICY_ENABLE_TEST_ROOT_FLAG;
if(!CertVerifyCertificateChainPolicy(new IntPtr(CERT_CHAIN_POLICY_MICROSOFT_ROOT),
pChainContext,
ref PolicyPara,
ref PolicyStatus))
{
return false;
}
return (PolicyStatus.dwError == 0);
}
}
}
"@
@@ -958,14 +1051,26 @@ function Publish-Module
Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $moduleInfo.Name} |
Microsoft.PowerShell.Utility\Select-Object -Last 1
if($currentPSGetItemInfo -and $currentPSGetItemInfo.Version -ge $moduleInfo.Version)
if($currentPSGetItemInfo)
{
$message = $LocalizedData.ModuleVersionShouldBeGreaterThanGalleryVersion -f ($moduleInfo.Name, $moduleInfo.Version, $currentPSGetItemInfo.Version, $currentPSGetItemInfo.RepositorySourceLocation)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId "ModuleVersionShouldBeGreaterThanGalleryVersion" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
if($currentPSGetItemInfo.Version -eq $moduleInfo.Version)
{
$message = $LocalizedData.ModuleVersionIsAlreadyAvailableInTheGallery -f ($moduleInfo.Name, $moduleInfo.Version, $currentPSGetItemInfo.Version, $currentPSGetItemInfo.RepositorySourceLocation)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'ModuleVersionIsAlreadyAvailableInTheGallery' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
elseif(-not $Force -and ($currentPSGetItemInfo.Version -gt $moduleInfo.Version))
{
$message = $LocalizedData.ModuleVersionShouldBeGreaterThanGalleryVersion -f ($moduleInfo.Name, $moduleInfo.Version, $currentPSGetItemInfo.Version, $currentPSGetItemInfo.RepositorySourceLocation)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId "ModuleVersionShouldBeGreaterThanGalleryVersion" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
}
$shouldProcessMessage = $LocalizedData.PublishModulewhatIfMessage -f ($moduleInfo.Version, $moduleInfo.Name)
@@ -1481,6 +1586,10 @@ function Install-Module
[switch]
$AllowClobber,
[Parameter()]
[switch]
$SkipPublisherCheck,
[Parameter()]
[switch]
$Force
@@ -1699,6 +1808,10 @@ function Update-Module
[PSCredential]
$ProxyCredential,
[Parameter()]
[switch]
$SkipPublisherCheck,
[Parameter()]
[Switch]
$Force
@@ -2583,17 +2696,32 @@ function Publish-Script
Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $scriptName} |
Microsoft.PowerShell.Utility\Select-Object -Last 1
if($currentPSGetItemInfo -and $currentPSGetItemInfo.Version -ge $PSScriptInfo.Version)
if($currentPSGetItemInfo)
{
$message = $LocalizedData.ScriptVersionShouldBeGreaterThanGalleryVersion -f ($scriptName,
$PSScriptInfo.Version,
$currentPSGetItemInfo.Version,
$currentPSGetItemInfo.RepositorySourceLocation)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId "ScriptVersionShouldBeGreaterThanGalleryVersion" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
if($currentPSGetItemInfo.Version -eq $PSScriptInfo.Version)
{
$message = $LocalizedData.ScriptVersionIsAlreadyAvailableInTheGallery -f ($scriptName,
$PSScriptInfo.Version,
$currentPSGetItemInfo.Version,
$currentPSGetItemInfo.RepositorySourceLocation)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId 'ScriptVersionIsAlreadyAvailableInTheGallery' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
elseif(-not $Force -and ($currentPSGetItemInfo.Version -gt $PSScriptInfo.Version))
{
$message = $LocalizedData.ScriptVersionShouldBeGreaterThanGalleryVersion -f ($scriptName,
$PSScriptInfo.Version,
$currentPSGetItemInfo.Version,
$currentPSGetItemInfo.RepositorySourceLocation)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId "ScriptVersionShouldBeGreaterThanGalleryVersion" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
}
$shouldProcessMessage = $LocalizedData.PublishScriptwhatIfMessage -f ($PSScriptInfo.Version, $scriptName)
@@ -8061,7 +8189,7 @@ function Publish-PSArtifactUtility
$tempOutputFile = Microsoft.PowerShell.Management\Join-Path -Path $nugetPackageRoot -ChildPath "TempPublishOutput.txt"
Microsoft.PowerShell.Management\Start-Process -FilePath "$script:NuGetExePath" `
-ArgumentList @('push', "`"$NupkgPath`"", '-source', "`"$Destination`"", '-NonInteractive', '-ApiKey', "`"$NugetApiKey`"") `
-ArgumentList @('push', "`"$NupkgPath`"", '-source', "`"$($Destination.TrimEnd('\'))`"", '-NonInteractive', '-ApiKey', "`"$NugetApiKey`"") `
-RedirectStandardError $tempErrorFile `
-RedirectStandardOutput $tempOutputFile `
-NoNewWindow `
@@ -8470,6 +8598,7 @@ function Get-DynamicOptions
-PermittedValues @($script:PSArtifactTypeModule,$script:PSArtifactTypeScript, $script:All))
Write-Output -InputObject (New-DynamicOption -Category $category -Name "Scope" -ExpectedType String -IsRequired $false -PermittedValues @("CurrentUser","AllUsers"))
Write-Output -InputObject (New-DynamicOption -Category $category -Name 'AllowClobber' -ExpectedType Switch -IsRequired $false)
Write-Output -InputObject (New-DynamicOption -Category $category -Name 'SkipPublisherCheck' -ExpectedType Switch -IsRequired $false)
Write-Output -InputObject (New-DynamicOption -Category $category -Name "InstallUpdate" -ExpectedType Switch -IsRequired $false)
Write-Output -InputObject (New-DynamicOption -Category $category -Name 'NoPathUpdate' -ExpectedType Switch -IsRequired $false)
}
@@ -9918,6 +10047,7 @@ function Install-PackageUtility
Write-Debug ($LocalizedData.FastPackageReference -f $fastPackageReference)
$Force = $false
$SkipPublisherCheck = $false
$AllowClobber = $false
$Debug = $false
$MinimumVersion = $null
@@ -10007,6 +10137,23 @@ function Install-PackageUtility
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidArgument
}
if($options.ContainsKey('SkipPublisherCheck'))
{
$SkipPublisherCheck = $options['SkipPublisherCheck']
if($SkipPublisherCheck.GetType().ToString() -eq 'System.String')
{
if($SkipPublisherCheck -eq 'true')
{
$SkipPublisherCheck = $true
}
else
{
$SkipPublisherCheck = $false
}
}
}
if($options.ContainsKey('AllowClobber'))
{
@@ -10433,6 +10580,7 @@ function Install-PackageUtility
$CurrentModuleInfo = Test-ValidManifestModule -ModuleBasePath $sourceModulePath `
-InstallLocation $InstallLocation `
-AllowClobber:$AllowClobber `
-SkipPublisherCheck:$SkipPublisherCheck `
-IsUpdateOperation:$installUpdate
if(-not $CurrentModuleInfo)
@@ -13492,152 +13640,143 @@ function Validate-ModuleAuthenticodeSignature
[Parameter()]
[Switch]
$AllowClobber,
[Parameter()]
[Switch]
$IsUpdateOperation
$SkipPublisherCheck
)
$CurrentModuleAuthenticodeIssuer = $null
$InstalledModuleDetails = $null
$InstalledModuleInfo = Test-ModuleInstalled -Name $CurrentModuleInfo.Name
if($InstalledModuleInfo)
{
$InstalledModuleDetails = Get-InstalledModuleAuthenticodeSignature -InstalledModuleInfo $InstalledModuleInfo `
-InstallLocation $InstallLocation
}
# Validate the catalog signature
# Skip the publisher check when -SkipPublisherCheck is specified and
# previously-installed module is not signed by Microsoft
if($SkipPublisherCheck)
{
if($InstalledModuleDetails -and $InstalledModuleDetails.IsMicrosoftCertificate)
{
$Message = $LocalizedData.ProceedingWithPublisherCheckForMicrosoftModules -f ($CurrentModuleInfo.Name)
Write-Verbose -Message $message
}
else
{
$Message = $LocalizedData.SkippingPublisherCheck -f ($CurrentModuleInfo.Version, $CurrentModuleInfo.Name)
Write-Verbose -Message $message
return $true
}
}
# Validate the catalog signature for the current module being installed.
$ev = $null
$CurrentModuleAuthenticodeIssuer = ValidateAndGet-CatalogSigningIssuer -ModuleBasePath $CurrentModuleInfo.ModuleBase `
-ModuleName $CurrentModuleInfo.Name `
-ErrorVariable ev
$CurrentModuleDetails = ValidateAndGet-AuthenticodeSignature -ModuleInfo $CurrentModuleInfo -ErrorVariable ev
if($ev)
{
return $false
}
$InstalledModuleInfo = Test-ModuleInstalled -Name $CurrentModuleInfo.Name
# Remove the version folder on 5.0 to get the actual module base folder without version
if(Test-ModuleSxSVersionSupport)
{
$InstallLocation = Microsoft.PowerShell.Management\Split-Path -Path $InstallLocation
}
if($InstalledModuleInfo)
{
# if $InstalledModuleInfo module base is not starting with current module destination
# Check if the destination location has a previously-installed version, then use that in the further validation.
#
if(-not $InstalledModuleInfo.ModuleBase.StartsWith($InstallLocation, [System.StringComparison]::OrdinalIgnoreCase))
{
$DestinationModulePath = Microsoft.PowerShell.Management\Join-Path -Path $InstallLocation -ChildPath "$($CurrentModuleInfo.Name)"
$ModuleInfoUnderDestination = Microsoft.PowerShell.Core\Get-Module -ListAvailable `
-Name $DestinationModulePath `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue `
-Verbose:$false |
Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction SilentlyContinue
$CurrentModuleAuthenticodePublisher = $null
$IsCurrentModuleSignedByMicrosoft = $false
if($ModuleInfoUnderDestination)
if($CurrentModuleDetails)
{
$CurrentModuleAuthenticodePublisher = $CurrentModuleDetails.Publisher
$IsCurrentModuleSignedByMicrosoft = $CurrentModuleDetails.IsMicrosoftCertificate
$message = $LocalizedData.NewModuleVersionDetailsForPublisherValidation -f ($CurrentModuleInfo.Name,
$CurrentModuleInfo.Version,
$CurrentModuleDetails.Publisher,
$CurrentModuleDetails.IsMicrosoftCertificate)
Write-Verbose $message
}
$InstalledModuleAuthenticodePublisher = $null
$IsInstalledModuleSignedByMicrosoft = $false
$InstalledModuleVersion = [Version]'0.0'
if($InstalledModuleDetails)
{
$InstalledModuleAuthenticodePublisher = $InstalledModuleDetails.Publisher
$IsInstalledModuleSignedByMicrosoft = $InstalledModuleDetails.IsMicrosoftCertificate
$InstalledModuleVersion = $InstalledModuleDetails.Version
$message = $LocalizedData.SourceModuleDetailsForPublisherValidation -f ($CurrentModuleInfo.Name,
$InstalledModuleDetails.Version,
$InstalledModuleDetails.ModuleBase,
$InstalledModuleDetails.Publisher,
$InstalledModuleDetails.IsMicrosoftCertificate)
Write-Verbose $message
}
Write-Debug -Message "Previously-installed module publisher: $InstalledModuleAuthenticodePublisher"
Write-Debug -Message "Current module publisher: $CurrentModuleAuthenticodePublisher"
Write-Debug -Message "Is previously-installed module signed by Microsoft: $IsInstalledModuleSignedByMicrosoft"
Write-Debug -Message "Is current module signed by Microsoft: $IsCurrentModuleSignedByMicrosoft"
if($InstalledModuleAuthenticodePublisher)
{
if(-not $CurrentModuleAuthenticodePublisher)
{
$InstalledModuleInfo = $ModuleInfoUnderDestination
$Message = $LocalizedData.ModuleIsNotCatalogSigned -f ($CurrentModuleInfo.Version, $CurrentModuleInfo.Name, "$($CurrentModuleInfo.Name).cat", $InstalledModuleAuthenticodePublisher, $InstalledModuleDetails.Version, $InstalledModuleDetails.ModuleBase)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'ModuleIsNotCatalogSigned' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
return $false
}
}
$InstalledModuleAuthenticodeIssuer = ValidateAndGet-CatalogSigningIssuer -ModuleBasePath $InstalledModuleInfo.ModuleBase `
-ModuleName $InstalledModuleInfo.Name `
-IsLocal `
-ErrorAction SilentlyContinue
Write-Debug -Message "Previously installed module authenticode issuer: $InstalledModuleAuthenticodeIssuer"
Write-Debug -Message "Current module authenticode issuer: $CurrentModuleAuthenticodeIssuer"
if($InstalledModuleAuthenticodeIssuer -and
$CurrentModuleAuthenticodeIssuer -and
($InstalledModuleAuthenticodeIssuer -eq $CurrentModuleAuthenticodeIssuer))
{
$Message = $LocalizedData.AuthenticodeIssuerMatch -f ($CurrentModuleAuthenticodeIssuer, $CurrentModuleInfo.Name, $CurrentModuleInfo.Version, $InstalledModuleAuthenticodeIssuer, $InstalledModuleInfo.Name, $InstalledModuleInfo.Version)
Write-Verbose -Message $message
return $true
}
elseif(-not $InstalledModuleInfo.ModuleBase.StartsWith($PSHome, [System.StringComparison]::OrdinalIgnoreCase) -and
$InstalledModuleAuthenticodeIssuer -and
(-not $CurrentModuleAuthenticodeIssuer -or
($InstalledModuleAuthenticodeIssuer -ne $CurrentModuleAuthenticodeIssuer)))
{
$Message = $LocalizedData.AuthenticodeIssuerMismatch -f ($CurrentModuleAuthenticodeIssuer, $CurrentModuleInfo.Name, $CurrentModuleInfo.Version, $InstalledModuleAuthenticodeIssuer, $InstalledModuleInfo.Name, $InstalledModuleInfo.Version)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'AuthenticodeIssuerMismatch' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
return $false
}
# Check if there is a system module
$SystemModuleBase = $null
$SystemModuleManifestFilePath = $null
if($InstalledModuleInfo -and
$InstalledModuleInfo.ModuleBase.StartsWith($PSHome, [System.StringComparison]::OrdinalIgnoreCase))
{
$SystemModuleBase = $InstalledModuleInfo.ModuleBase
}
else
{
$SystemModuleBase = Microsoft.PowerShell.Management\Join-Path -Path $PSHome -ChildPath "Modules\$($CurrentModuleInfo.Name)"
}
if($SystemModuleBase -and
(Microsoft.PowerShell.Management\Test-Path -Path $SystemModuleBase -PathType Container))
{
$ManifestFileName = "$($CurrentModuleInfo.Name).psd1"
$SystemModuleManifestFilePath = Microsoft.PowerShell.Management\Join-Path -Path $SystemModuleBase -ChildPath $ManifestFileName
}
if($SystemModuleManifestFilePath -and
(Microsoft.PowerShell.Management\Test-Path -Path $SystemModuleManifestFilePath -PathType Leaf))
{
$AuthenticodeSignature = Microsoft.PowerShell.Security\Get-AuthenticodeSignature -FilePath $SystemModuleManifestFilePath
$SystemModuleAuthenticodeIssuer = Get-AuthentcodeIssuer -AuthenticodeSignature $AuthenticodeSignature
if($SystemModuleAuthenticodeIssuer -eq $CurrentModuleAuthenticodeIssuer)
elseif($InstalledModuleAuthenticodePublisher -eq $CurrentModuleAuthenticodePublisher)
{
$Message = $LocalizedData.AuthenticodeIssuerMatch -f ($CurrentModuleAuthenticodeIssuer, $CurrentModuleInfo.Name, $CurrentModuleInfo.Version, $SystemModuleAuthenticodeIssuer, $SystemModuleInfo.Name, $SystemModuleInfo.Version)
$Message = $LocalizedData.AuthenticodeIssuerMatch -f ($CurrentModuleAuthenticodePublisher, $CurrentModuleInfo.Name, $CurrentModuleInfo.Version, $InstalledModuleAuthenticodePublisher, $InstalledModuleInfo.Name, $InstalledModuleVersion)
Write-Verbose -Message $message
}
elseif($IsInstalledModuleSignedByMicrosoft)
{
if($IsCurrentModuleSignedByMicrosoft)
{
$Message = $LocalizedData.PublishersMatch -f ($CurrentModuleAuthenticodePublisher, $CurrentModuleInfo.Name, $CurrentModuleInfo.Version, $InstalledModuleAuthenticodePublisher, $InstalledModuleInfo.Name, $InstalledModuleVersion)
Write-Verbose -Message $message
}
else
{
$Message = $LocalizedData.PublishersMismatch -f ($CurrentModuleAuthenticodePublisher, $CurrentModuleInfo.Name, $CurrentModuleInfo.Version, $InstalledModuleAuthenticodePublisher, $InstalledModuleInfo.Name, $InstalledModuleVersion)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'PublishersMismatch' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
return $true
return $false
}
}
else
{
$SystemModuleInfo = Microsoft.PowerShell.Core\Test-ModuleManifest -Path $SystemModuleManifestFilePath
$Message = $LocalizedData.AuthenticodeIssuerMismatch -f ($CurrentModuleAuthenticodeIssuer, $CurrentModuleInfo.Name, $CurrentModuleInfo.Version, $SystemModuleAuthenticodeIssuer, $SystemModuleInfo.Name, $SystemModuleInfo.Version)
$Message = $LocalizedData.AuthenticodeIssuerMismatch -f ($CurrentModuleAuthenticodePublisher, $CurrentModuleInfo.Name, $CurrentModuleInfo.Version, $InstalledModuleAuthenticodePublisher, $InstalledModuleInfo.Name, $InstalledModuleVersion)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'AuthenticodeIssuerMismatch' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
-ExceptionMessage $message `
-ErrorId 'AuthenticodeIssuerMismatch' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
return $false
}
}
}
# When module being installed doesn't have the security catalog file, check for the existing commands
# We are calling Test-ModuleCommandAlreadyAvailable as InstalledModuleInfo is required for checking the possible clobbering
#
return Test-ModuleCommandAlreadyAvailable -CurrentModuleInfo $CurrentModuleInfo `
-InstallLocation $InstallLocation `
-InstalledModuleInfo $InstalledModuleInfo `
-AllowClobber:$AllowClobber `
-IsUpdateOperation:$IsUpdateOperation
return $true
}
function Test-ModuleCommandAlreadyAvailable
function Validate-ModuleCommandAlreadyAvailable
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
[PSModuleInfo]
$CurrentModuleInfo,
[Parameter(Mandatory=$true)]
@@ -13645,9 +13784,6 @@ function Test-ModuleCommandAlreadyAvailable
[string]
$InstallLocation,
[Parameter()]
$InstalledModuleInfo,
[Parameter()]
[Switch]
$AllowClobber,
@@ -13656,63 +13792,78 @@ function Test-ModuleCommandAlreadyAvailable
[Switch]
$IsUpdateOperation
)
<#
Install-Module must generate an error message when there is a conflict.
User can specify -AllowClobber to avoid the message.
Scenario: A large module could be separated into 2 smaller modules.
Reason 1: the consumer might have to change code (aka: import-module) to use the command from the new module.
Reason 2: it is too confusing to troubleshoot this problem if the user isn't informed right away.
#>
# When new module has some commands, no clobber error if
# - AllowClobber is specified, or
# - Installing to the same module base, or
# - Update operation
if($CurrentModuleInfo.ExportedCommands.Keys -and
if($CurrentModuleInfo.ExportedCommands.Keys.Count -and
-not $AllowClobber -and
-not $IsUpdateOperation -and
($InstalledModuleInfo -and -not $InstalledModuleInfo.ModuleBase.StartsWith($InstallLocation, [System.StringComparison]::OrdinalIgnoreCase)))
-not $IsUpdateOperation)
{
# Throw an error if there is a command with the same name.
# Get-Command loads the module if a command is already available.
$AvailableCommand = Microsoft.PowerShell.Core\Get-Command -Name $CurrentModuleInfo.ExportedCommands.Values.Name `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue |
Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction SilentlyContinue
if($AvailableCommand)
# Remove the version folder on 5.0 to get the actual module base folder without version
if(Test-ModuleSxSVersionSupport)
{
$message = $LocalizedData.ModuleCommandAlreadyAvailable -f ($AvailableCommand.Name, $CurrentModuleInfo.Name)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'CommandAlreadyAvailable' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
$InstallLocation = Microsoft.PowerShell.Management\Split-Path -Path $InstallLocation
}
return $false
$InstalledModuleInfo = Test-ModuleInstalled -Name $CurrentModuleInfo.Name
if(-not $InstalledModuleInfo -or -not $InstalledModuleInfo.ModuleBase.StartsWith($InstallLocation, [System.StringComparison]::OrdinalIgnoreCase))
{
# Throw an error if there is a command with the same name from a different source.
# Get-Command loads the module if a command is already available.
# To avoid that, appending '*' at the end for each name then comparing the results.
$CommandNames = $CurrentModuleInfo.ExportedCommands.Values.Name
$CommandNamesWithWildcards = $CommandNames | Microsoft.PowerShell.Core\Foreach-Object { "$_*" }
$AvailableCommand = Microsoft.PowerShell.Core\Get-Command -Name $CommandNamesWithWildcards `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue |
Microsoft.PowerShell.Core\Where-Object { ($CommandNames -contains $_.Name) -and
($_.Source -ne $CurrentModuleInfo.Name) } |
Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction SilentlyContinue
if($AvailableCommand)
{
$message = $LocalizedData.ModuleCommandAlreadyAvailable -f ($AvailableCommand.Name, $CurrentModuleInfo.Name)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'CommandAlreadyAvailable' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
return $false
}
}
}
return $true
}
function ValidateAndGet-CatalogSigningIssuer
function ValidateAndGet-AuthenticodeSignature
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$ModuleBasePath,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$ModuleName,
[Parameter()]
[Switch]
$IsLocal
[PSModuleInfo]
$ModuleInfo
)
$ModuleDetails = $null
$AuthenticodeSignature = $null
$ModuleName = $ModuleInfo.Name
$ModuleBasePath = $ModuleInfo.ModuleBase
$CatalogFileName = "$ModuleName.cat"
$CatalogFilePath = Microsoft.PowerShell.Management\Join-Path -Path $ModuleBasePath -ChildPath $CatalogFileName
$AuthenticodeSignature = $null
if(Microsoft.PowerShell.Management\Test-Path -Path $CatalogFilePath -PathType Leaf)
{
$message = $LocalizedData.CatalogFileFound -f ($CatalogFileName, $ModuleName)
@@ -13720,72 +13871,72 @@ function ValidateAndGet-CatalogSigningIssuer
$AuthenticodeSignature = Microsoft.PowerShell.Security\Get-AuthenticodeSignature -FilePath $CatalogFilePath
if(-not $IsLocal)
if(-not $AuthenticodeSignature -or ($AuthenticodeSignature.Status -ne "Valid"))
{
if(-not $AuthenticodeSignature -or ($AuthenticodeSignature.Status -ne "Valid"))
{
$message = $LocalizedData.InvalidModuleAuthenticodeSignature -f ($ModuleName, $CatalogFileName)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'InvalidAuthenticodeSignature' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
$message = $LocalizedData.InvalidModuleAuthenticodeSignature -f ($ModuleName, $CatalogFileName)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'InvalidAuthenticodeSignature' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
return
}
Write-Verbose -Message ($LocalizedData.ValidAuthenticodeSignature -f @($CatalogFileName, $ModuleName))
if(Get-Command -Name Test-FileCatalog -Module Microsoft.PowerShell.Security -ErrorAction SilentlyContinue)
{
Write-Verbose -Message ($LocalizedData.ValidatingCatalogSignature -f @($ModuleName, $CatalogFileName))
# Skip the PSGetModuleInfo.xml and ModuleName.cat files in the catalog validation
$TestFileCatalogResult = Microsoft.PowerShell.Security\Test-FileCatalog -Path $ModuleBasePath `
-CatalogFilePath $CatalogFilePath `
-FilesToSkip $script:PSGetItemInfoFileName,'*.cat' `
-Detailed `
-ErrorAction SilentlyContinue
if(-not $TestFileCatalogResult -or
($TestFileCatalogResult.Status -ne "Valid") -or
($TestFileCatalogResult.Signature.Status -ne "Valid"))
{
$message = $LocalizedData.InvalidCatalogSignature -f ($ModuleName, $CatalogFileName)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'InvalidCatalogSignature' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
return
}
Write-Verbose -Message ($LocalizedData.ValidAuthenticodeSignature -f @($CatalogFileName, $ModuleName))
if(Get-Command -Name Test-FileCatalog -Module Microsoft.PowerShell.Security -ErrorAction SilentlyContinue)
else
{
Write-Verbose -Message ($LocalizedData.ValidatingCatalogSignature -f @($ModuleName, $CatalogFileName))
# Skip the PSGetModuleInfo.xml and ModuleName.cat files in the catalog validation
$TestFileCatalogResult = Microsoft.PowerShell.Security\Test-FileCatalog -Path $ModuleBasePath `
-CatalogFilePath $CatalogFilePath `
-FilesToSkip $script:PSGetItemInfoFileName `
-Detailed
if(-not $TestFileCatalogResult -or
($TestFileCatalogResult.Status -ne "Valid") -or
($TestFileCatalogResult.Signature.Status -ne "Valid"))
{
$message = $LocalizedData.InvalidCatalogSignature -f ($ModuleName, $CatalogFileName)
ThrowError -ExceptionName 'System.InvalidOperationException' `
-ExceptionMessage $message `
-ErrorId 'InvalidCatalogSignature' `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
return
}
else
{
Write-Verbose -Message ($LocalizedData.ValidCatalogSignature -f @($CatalogFileName, $ModuleName))
}
Write-Verbose -Message ($LocalizedData.ValidCatalogSignature -f @($CatalogFileName, $ModuleName))
}
}
}
else
{
if($IsLocal)
{
Write-Verbose -Message ($LocalizedData.CatalogFileNotFoundInAvailableModule -f ($CatalogFileName, $ModuleName))
}
else
{
Write-Verbose -Message ($LocalizedData.CatalogFileNotFoundInNewModule -f ($CatalogFileName, $ModuleName))
}
Write-Verbose -Message ($LocalizedData.CatalogFileNotFoundInNewModule -f ($CatalogFileName, $ModuleName))
}
if($AuthenticodeSignature)
{
return Get-AuthentcodeIssuer -AuthenticodeSignature $AuthenticodeSignature
$ModuleDetails = @{}
$ModuleDetails['AuthenticodeSignature'] = $AuthenticodeSignature
$ModuleDetails['Version'] = $ModuleInfo.Version
$ModuleDetails['ModuleBase']=$ModuleInfo.ModuleBase
$ModuleDetails['IsMicrosoftCertificate'] = Test-MicrosoftCertificate -AuthenticodeSignature $AuthenticodeSignature
$ModuleDetails['Publisher'] = Get-AuthenticodePublisher -AuthenticodeSignature $AuthenticodeSignature
$message = $LocalizedData.NewModuleVersionDetailsForPublisherValidation -f ($ModuleInfo.Name, $ModuleInfo.Version, $ModuleDetails.Publisher, $ModuleDetails.IsMicrosoftCertificate)
Write-Debug $message
}
return $ModuleDetails
}
function Get-AuthentcodeIssuer
function Get-AuthenticodePublisher
{
[CmdletBinding()]
[OutputType([bool])]
Param
(
[Parameter(Mandatory=$true)]
@@ -13793,8 +13944,7 @@ function Get-AuthentcodeIssuer
$AuthenticodeSignature
)
if(($AuthenticodeSignature.Status -eq "Valid") -and
$AuthenticodeSignature.SignerCertificate)
if($AuthenticodeSignature.SignerCertificate)
{
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
$null = $chain.Build($AuthenticodeSignature.SignerCertificate)
@@ -13819,6 +13969,121 @@ function Get-AuthentcodeIssuer
}
}
function Get-InstalledModuleAuthenticodeSignature
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[PSModuleInfo]
$InstalledModuleInfo,
[Parameter(Mandatory=$true)]
[string]
$InstallLocation
)
$ModuleName = $InstalledModuleInfo.Name
# Priority order for getting the published details of the installed module:
# 1. Latest version under the $InstallLocation
# 2. Latest available version in $PSModulePath
# 3. $InstalledModuleInfo
$AvailableModules = Microsoft.PowerShell.Core\Get-Module -ListAvailable `
-Name $ModuleName `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue `
-Verbose:$false |
Microsoft.PowerShell.Utility\Sort-Object -Property Version -Descending
# Remove the version folder on 5.0 to get the actual module base folder without version
if(Test-ModuleSxSVersionSupport)
{
$InstallLocation = Microsoft.PowerShell.Management\Split-Path -Path $InstallLocation
}
$SourceModule = $AvailableModules | Microsoft.PowerShell.Core\Where-Object {
$_.ModuleBase.StartsWith($InstallLocation, [System.StringComparison]::OrdinalIgnoreCase)
} | Microsoft.PowerShell.Utility\Select-Object -First 1
if(-not $SourceModule)
{
$SourceModule = $AvailableModules | Microsoft.PowerShell.Utility\Select-Object -First 1
}
else
{
$SourceModule = $InstalledModuleInfo
}
$SignedFilePath = $SourceModule.Path
$CatalogFileName = "$ModuleName.cat"
$CatalogFilePath = Microsoft.PowerShell.Management\Join-Path -Path $SourceModule.ModuleBase -ChildPath $CatalogFileName
if(Microsoft.PowerShell.Management\Test-Path -Path $CatalogFilePath -PathType Leaf)
{
$message = $LocalizedData.CatalogFileFound -f ($CatalogFileName, $ModuleName)
Write-Debug -Message $message
$SignedFilePath = $CatalogFilePath
}
else
{
Write-Debug -Message ($LocalizedData.CatalogFileNotFoundInAvailableModule -f ($CatalogFileName, $ModuleName))
}
$message = "Using the previously-installed module '{0}' with version '{1}' under '{2}' for getting the publisher details." -f ($SourceModule.Name, $SourceModule.Version, $SourceModule.ModuleBase)
Write-Debug -Message $message
$message = "Using the '{0}' file for getting the authenticode signature." -f ($SignedFilePath)
Write-Debug -Message $message
$AuthenticodeSignature = Microsoft.PowerShell.Security\Get-AuthenticodeSignature -FilePath $SignedFilePath
$ModuleDetails = $null
if($AuthenticodeSignature)
{
$ModuleDetails = @{}
$ModuleDetails['AuthenticodeSignature'] = $AuthenticodeSignature
$ModuleDetails['Version'] = $SourceModule.Version
$ModuleDetails['ModuleBase']=$SourceModule.ModuleBase
$ModuleDetails['IsMicrosoftCertificate'] = Test-MicrosoftCertificate -AuthenticodeSignature $AuthenticodeSignature
$ModuleDetails['Publisher'] = Get-AuthenticodePublisher -AuthenticodeSignature $AuthenticodeSignature
$message = $LocalizedData.SourceModuleDetailsForPublisherValidation -f ($ModuleName, $SourceModule.Version, $SourceModule.ModuleBase, $ModuleDetails.Publisher, $ModuleDetails.IsMicrosoftCertificate)
Write-Debug $message
}
return $ModuleDetails
}
function Test-MicrosoftCertificate
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[System.Management.Automation.Signature]
$AuthenticodeSignature
)
if($AuthenticodeSignature.SignerCertificate)
{
try
{
$X509Chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
$null = $X509Chain.Build($AuthenticodeSignature.SignerCertificate)
}
catch
{
return $false
}
$SafeX509ChainHandle = [Microsoft.PowerShell.Commands.PowerShellGet.Win32Helpers]::CertDuplicateCertificateChain($X509Chain.ChainContext)
return [Microsoft.PowerShell.Commands.PowerShellGet.Win32Helpers]::IsMicrosoftCertificate($SafeX509ChainHandle)
}
return $false
}
function Test-ValidManifestModule
{
[CmdletBinding()]
@@ -13835,6 +14100,10 @@ function Test-ValidManifestModule
[string]
$InstallLocation,
[Parameter()]
[Switch]
$SkipPublisherCheck,
[Parameter()]
[Switch]
$AllowClobber,
@@ -13865,8 +14134,19 @@ function Test-ValidManifestModule
{
$ValidationResult = Validate-ModuleAuthenticodeSignature -CurrentModuleInfo $PSModuleInfo `
-InstallLocation $InstallLocation `
-AllowClobber:$AllowClobber `
-IsUpdateOperation:$IsUpdateOperation
-SkipPublisherCheck:$SkipPublisherCheck
if($ValidationResult)
{
# Checking for the possible command clobbering.
$ValidationResult = Validate-ModuleCommandAlreadyAvailable -CurrentModuleInfo $PSModuleInfo `
-InstallLocation $InstallLocation `
-AllowClobber:$AllowClobber `
-IsUpdateOperation:$IsUpdateOperation
}
if(-not $ValidationResult)
{
$PSModuleInfo = $null
@@ -1620,7 +1620,7 @@ namespace System.Management.Automation
namespace Microsoft.PowerShell.CoreCLR
{
using System;
using System.IO;
using System.Management.Automation;
/// <summary>
@@ -1629,18 +1629,23 @@ namespace Microsoft.PowerShell.CoreCLR
public static class AssemblyExtensions
{
/// <summary>
/// Loads an assembly given its file path.
/// Load an assembly given its file path.
/// </summary>
/// <param name="assemblyFile">The path of the file that contains the manifest of the assembly.</param>
/// <param name="assemblyPath">The path of the file that contains the manifest of the assembly.</param>
/// <returns>The loaded assembly.</returns>
public static Assembly LoadFrom(string assemblyFile)
public static Assembly LoadFrom(string assemblyPath)
{
if (string.IsNullOrEmpty(assemblyFile))
{
throw new ArgumentNullException("assemblyFile");
return ClrFacade.LoadFrom(assemblyPath);
}
return ClrFacade.LoadFrom(assemblyFile);
/// <summary>
/// Load an assembly given its byte stream
/// </summary>
/// <param name="assembly">The byte stream of assembly</param>
/// <returns>The loaded assembly</returns>
public static Assembly LoadFrom(Stream assembly)
{
return ClrFacade.LoadFrom(assembly);
}
}
}
@@ -537,8 +537,7 @@ namespace System.Management.Automation.Runspaces
.AddHeader(Alignment.Right, label: "NPM(K)", width: 7)
.AddHeader(Alignment.Right, label: "PM(K)", width: 8)
.AddHeader(Alignment.Right, label: "WS(K)", width: 10)
.AddHeader(Alignment.Right, label: "VM(M)", width: 5)
.AddHeader(Alignment.Right, label: "CPU(s)", width: 8)
.AddHeader(Alignment.Right, label: "CPU(s)", width: 10)
.AddHeader(Alignment.Right, width: 6)
.AddHeader(Alignment.Right, width: 3)
.AddHeader()
@@ -547,13 +546,7 @@ namespace System.Management.Automation.Runspaces
.AddScriptBlockColumn("[long]($_.NPM / 1024)")
.AddScriptBlockColumn("[long]($_.PM / 1024)")
.AddScriptBlockColumn("[long]($_.WS / 1024)")
.AddScriptBlockColumn("[long]($_.VM / 1048576)")
.AddScriptBlockColumn(@"
if ($_.CPU -ne $())
{
$_.CPU.ToString(""N"")
}
")
.AddScriptBlockColumn(@"if ($_.CPU -ne $()) { $_.CPU.ToString(""N"") }")
.AddPropertyColumn("Id")
.AddPropertyColumn("SI")
.AddPropertyColumn("ProcessName")
@@ -600,21 +593,14 @@ if ($_.CPU -ne $())
TableControl.Create()
.AddHeader(Alignment.Right, label: "Handles", width: 7)
.AddHeader(Alignment.Right, label: "WS(K)", width: 10)
.AddHeader(Alignment.Right, label: "VM(M)", width: 5)
.AddHeader(Alignment.Right, label: "CPU(s)", width: 8)
.AddHeader(Alignment.Right, width: 6)
.AddHeader(width: 17)
.AddHeader(width: 22)
.AddHeader()
.StartRowDefinition()
.AddPropertyColumn("HandleCount")
.AddScriptBlockColumn("[long]($_.WS / 1024)")
.AddScriptBlockColumn("[long]($_.VM / 1048576)")
.AddScriptBlockColumn(@"
if ($_.CPU -ne $())
{
$_.CPU.ToString(""N"")
}
")
.AddScriptBlockColumn(@"if ($_.CPU -ne $()) { $_.CPU.ToString(""N"") }")
.AddPropertyColumn("Id")
.AddPropertyColumn("UserName")
.AddPropertyColumn("ProcessName")
@@ -196,6 +196,7 @@ namespace System.Management.Automation
/// </summary>
/// <param name="typeinfo">reference to ITypeInfo from which to get TypeAttr</param>
/// <returns></returns>
[ArchitectureSensitive]
internal static COM.TYPEATTR GetTypeAttr(COM.ITypeInfo typeinfo)
{
IntPtr pTypeAttr;
@@ -211,6 +212,7 @@ namespace System.Management.Automation
/// <param name="typeinfo"></param>
/// <param name="index"></param>
/// <returns></returns>
[ArchitectureSensitive]
internal static COM.FUNCDESC GetFuncDesc(COM.ITypeInfo typeinfo, int index)
{
IntPtr pFuncDesc;
@@ -103,7 +103,7 @@ namespace System.Management.Automation.ComInterop {
i.ToString(CultureInfo.InvariantCulture),
method.Name,
temps,
initTemps), curArgument.Restrictions, curArgument.Value);
initTemps), curArgument.Restrictions);
}
else
{
@@ -508,6 +508,20 @@ namespace System.Management.Automation.ComInterop {
}
}
if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_INTERFACE)
{
//We have typeinfo for custom interface. Get typeinfo for Dispatch interface.
typeInfo = ComTypeInfo.GetDispatchTypeInfoFromCustomInterfaceTypeInfo(typeInfo);
typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo);
}
if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_COCLASS)
{
//We have typeinfo for the COClass. Find the default interface and get typeinfo for default interface.
typeInfo = ComTypeInfo.GetDispatchTypeInfoFromCoClassTypeInfo(typeInfo);
typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo);
}
ComTypeDesc typeDesc = ComTypeDesc.FromITypeInfo(typeInfo, typeAttr);
ComMethodDesc getItem = null;
@@ -1068,7 +1068,7 @@ namespace System.Management.Automation
var configAst = Ast.GetAncestorAst<ConfigurationDefinitionAst>(keywordAst);
if (configAst != null)
{
var namedBlockAst = keywordAst.Parent as NamedBlockAst;
var namedBlockAst = Ast.GetAncestorAst<NamedBlockAst>(keywordAst);
if (namedBlockAst != null)
{
List<string> allResources = new List<string>();
@@ -1297,9 +1297,6 @@ namespace System.Management.Automation
//Get Target object
object targetObject = RemotingDecoder.GetPropertyValue<object>(serializedErrorRecord, "TargetObject");
//Get InvocationInfo
PSObject invocationInfo = RemotingDecoder.GetPropertyValue<PSObject>(serializedErrorRecord, "InvocationInfo");
string exceptionMessage = null;
if (serializedException != null)
{
@@ -1324,6 +1321,12 @@ namespace System.Management.Automation
string errorCategory_TargetType = RemotingDecoder.GetPropertyValue<string>(serializedErrorRecord, "ErrorCategory_TargetType");
string errorCategory_Message = RemotingDecoder.GetPropertyValue<string>(serializedErrorRecord, "ErrorCategory_Message");
//Get InvocationInfo (optional property)
PSObject invocationInfo = Microsoft.PowerShell.DeserializingTypeConverter.GetPropertyValue<PSObject>(
serializedErrorRecord,
"InvocationInfo",
Microsoft.PowerShell.DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk);
//Get Error Detail (these note properties are optional, so can't right now use RemotingDecoder...)
string errorDetails_Message =
GetNoteValue(serializedErrorRecord, "ErrorDetails_Message") as string;
@@ -5474,7 +5474,12 @@ end
internal const string DefaultMoreFunctionText = @"
param([string[]]$paths)
$OutputEncoding = [System.Console]::OutputEncoding
# Nano needs to use Unicode, but Windows and Linux need the default
$OutputEncoding = if ($IsWindows -and $IsCore) {
[System.Text.Encoding]::Unicode
} else {
[System.Console]::OutputEncoding
}
# Respect PAGER, use more on Windows, and use less on Linux
if (Test-Path env:PAGER) {
@@ -7,6 +7,7 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Text;
@@ -104,6 +105,17 @@ namespace System.Management.Automation
var moduleManifestProperties = PsUtils.GetModuleManifestProperties(modulePath, PsUtils.FastModuleManifestAnalysisPropertyNames);
if (moduleManifestProperties != null)
{
Version version;
if (ModuleUtils.IsModuleInVersionSubdirectory(modulePath, out version))
{
var versionInManifest = LanguagePrimitives.ConvertTo<Version>(moduleManifestProperties["ModuleVersion"]);
if (version != versionInManifest)
{
ModuleIntrinsics.Tracer.WriteLine("ModuleVersion in manifest does not match versioned module directory, skipping module: {0}", modulePath);
return null;
}
}
result = new ConcurrentDictionary<string, CommandTypes>(3, moduleManifestProperties.Count, StringComparer.OrdinalIgnoreCase);
var sawWildcard = false;
@@ -1190,10 +1190,15 @@ namespace Microsoft.PowerShell.Commands
if (module != null)
{
Version directoryVersion;
if (!ModuleUtils.IsModuleInVersionSubdirectory(file, out directoryVersion)
|| directoryVersion == module.Version)
{
availableModules.Add(module);
}
}
}
}
ClearAnalysisCaches();
@@ -4982,7 +4987,7 @@ namespace Microsoft.PowerShell.Commands
/// <returns></returns>
internal string GetAbsolutePath(string moduleBase, string path)
{
if (!IsRooted(path) && (path.Contains('/') || path.Contains('\\')) && !path.Contains('$'))
if (!IsRooted(path) && (path.Contains('/') || path.Contains('\\')))
{
return Path.Combine(moduleBase, path);
}
@@ -797,6 +797,15 @@ namespace System.Management.Automation
int psHomePosition = PathContainsSubstring(currentProcessModulePath, psHomeModulePath); // index of $PSHome\Modules in currentProcessModulePath
if (psHomePosition >= 0) // if $PSHome\Modules IS found - insert <Program Files> location before $PSHome\Modules
{
#if !CORECLR
// for bug 6678623, if we are running wow64 process (x86 32-bit process on 64-bit (amd64) OS), then ensure that <SpecialFolder.MyDocuments> exists in currentProcessModulePath / return value
if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess)
{
string userModulePath = GetPersonalModulePath();
currentProcessModulePath = AddToPath(currentProcessModulePath, userModulePath, psHomePosition);
psHomePosition = PathContainsSubstring(currentProcessModulePath, psHomeModulePath);
}
#endif
return AddToPath(currentProcessModulePath, programFilesModulePath, psHomePosition);
} // if $PSHome\Modules NOT found = <scenario 4> = 'PSModulePath has been constrained by a user to create a sand boxed environment without including System Modules'
@@ -905,27 +914,27 @@ namespace System.Management.Automation
/// <summary>
/// Get the current module path setting.
///
/// 'preferSystemModulePath' should only be used for internal functions - by default,
/// user modules should be able to override system modules.
/// </summary>
/// <param name="includeSystemModulePath">
/// Include The system wide module path ($PSHOME\Modules) even if it's not in PSModulePath.
/// In V3-V5, we prepended this path during module auto-discovery which incorrectly preferred
/// $PSHOME\Modules over user installed modules that might have a command that overrides
/// a product-supplied command.
/// For 5.1, we append $PSHOME\Modules in this case to avoid the rare case where PSModulePath
/// does not contain the path, but a script depends on previous behavior.
/// Note that appending is still a potential breaking change, but necessary to update in-box
/// modules long term - e.g. when open sourcing a module and installing from the gallery.
/// </param>
/// <param name="context"></param>
/// <returns>The module path as an array of strings</returns>
internal static IEnumerable<string> GetModulePath(bool preferSystemModulePath, ExecutionContext context)
internal static IEnumerable<string> GetModulePath(bool includeSystemModulePath, ExecutionContext context)
{
string modulePathString = Environment.GetEnvironmentVariable("PSMODULEPATH") ?? SetModulePath();
HashSet<string> processedPathSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// If we should prefer the system-wide module path, prepend that to what gets returned.
if (preferSystemModulePath)
if (!string.IsNullOrWhiteSpace(modulePathString))
{
yield return ProcessOneModulePath(context, GetSystemwideModulePath(), processedPathSet);
}
// If the path is just whitespace, return an empty collection.
if (string.IsNullOrWhiteSpace(modulePathString))
yield break;
foreach (string envPath in modulePathString.Split(Utils.Separators.Semicolon, StringSplitOptions.RemoveEmptyEntries))
{
var processedPath = ProcessOneModulePath(context, envPath, processedPathSet);
@@ -934,6 +943,14 @@ namespace System.Management.Automation
}
}
if (includeSystemModulePath)
{
var processedPath = ProcessOneModulePath(context, GetSystemwideModulePath(), processedPathSet);
if (processedPath != null)
yield return processedPath;
}
}
static private string ProcessOneModulePath(ExecutionContext context, string envPath, HashSet<string> processedPathSet)
{
string trimmedenvPath = envPath.Trim();
@@ -226,12 +226,8 @@ namespace System.Management.Automation.Internal
string manifestPath = qualifiedPathWithVersion + StringLiterals.PowerShellDataFileExtension;
if (File.Exists(manifestPath))
{
var isValidModuleVersion = version.Equals(ModuleIntrinsics.GetManifestModuleVersion(manifestPath));
if (isValidModuleVersion)
{
isModuleDirectory = true;
yield return manifestPath;
}
isModuleDirectory = true;
yield return manifestPath;
}
}
@@ -309,6 +305,18 @@ namespace System.Management.Automation.Internal
}
}
internal static bool IsModuleInVersionSubdirectory(string modulePath, out Version version)
{
version = null;
var folderName = Path.GetDirectoryName(modulePath);
if (folderName != null)
{
folderName = Path.GetFileName(folderName);
return Version.TryParse(folderName, out version);
}
return false;
}
/// <summary>
/// Gets a list of matching commands
/// </summary>
@@ -978,9 +978,9 @@ namespace Microsoft.PowerShell.Commands
BuildModuleManifest(result, "PowerShellHostVersion", Modules.PowerShellHostVersion, _PowerShellHostVersion != null && !string.IsNullOrEmpty(_PowerShellHostVersion.ToString()), () => QuoteName(_PowerShellHostVersion), streamWriter);
BuildModuleManifest(result, "DotNetFrameworkVersion", Modules.DotNetFrameworkVersion, _DotNetFrameworkVersion != null && !string.IsNullOrEmpty(_DotNetFrameworkVersion.ToString()), () => QuoteName(_DotNetFrameworkVersion), streamWriter);
BuildModuleManifest(result, "DotNetFrameworkVersion", StringUtil.Format(Modules.DotNetFrameworkVersion, Modules.PrerequisiteForDesktopEditionOnly), _DotNetFrameworkVersion != null && !string.IsNullOrEmpty(_DotNetFrameworkVersion.ToString()), () => QuoteName(_DotNetFrameworkVersion), streamWriter);
BuildModuleManifest(result, "CLRVersion", Modules.CLRVersion, _ClrVersion != null && !string.IsNullOrEmpty(_ClrVersion.ToString()), () => QuoteName(_ClrVersion), streamWriter);
BuildModuleManifest(result, "CLRVersion", StringUtil.Format(Modules.CLRVersion, Modules.PrerequisiteForDesktopEditionOnly), _ClrVersion != null && !string.IsNullOrEmpty(_ClrVersion.ToString()), () => QuoteName(_ClrVersion), streamWriter);
BuildModuleManifest(result, "ProcessorArchitecture", Modules.ProcessorArchitecture, _processorArchitecture.HasValue, () => QuoteName(_processorArchitecture), streamWriter);
@@ -848,6 +848,7 @@ namespace System.Management.Automation
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
[ArchitectureSensitive]
static bool IsWindowsApplication(string fileName)
{
#if CORECLR
@@ -1250,6 +1251,7 @@ namespace System.Management.Automation
private static extern IntPtr FindExecutableW(
string fileName, string directoryPath, StringBuilder pathFound);
[ArchitectureSensitive]
private static string FindExecutable(string filename)
{
// Preallocate a
@@ -164,6 +164,7 @@ namespace System.Management.Automation
}
}
[ArchitectureSensitive]
internal static string GetStringFromSecureString(SecureString ss)
{
IntPtr p = IntPtr.Zero;
@@ -878,7 +878,7 @@ namespace System.Management.Automation.Runspaces
PSHostUserInterface host = executionContext.EngineHostInterface.UI;
if (host != null)
{
host.StopAllTranscribing();
host.StopAllTranscribing(executionContext.CurrentRunspace.InstanceId);
}
}
}
@@ -420,12 +420,13 @@ namespace System.Management.Automation.Host
}
}
internal void StartTranscribing(string path, System.Management.Automation.Remoting.PSSenderInfo senderInfo, bool includeInvocationHeader)
{
internal void StartTranscribing(string path, System.Management.Automation.Remoting.PSSenderInfo senderInfo, bool includeInvocationHeader, Guid runspaceInstanceId)
{
TranscriptionOption transcript = new TranscriptionOption();
transcript.Path = path;
transcript.IncludeInvocationHeader = includeInvocationHeader;
TranscriptionData.Transcripts.Add(transcript);
transcript.RunspaceInstanceId = runspaceInstanceId;
TranscriptionData.Transcripts.Add(transcript);
LogTranscriptHeader(senderInfo, transcript);
}
@@ -476,7 +477,7 @@ namespace System.Management.Automation.Host
TranscribeCommandComplete(null);
}
internal string StopTranscribing()
internal string StopTranscribing(Guid runspaceInstanceId)
{
if (TranscriptionData.Transcripts.Count == 0)
{
@@ -484,11 +485,17 @@ namespace System.Management.Automation.Host
}
TranscriptionOption stoppedTranscript = TranscriptionData.Transcripts[TranscriptionData.Transcripts.Count - 1];
LogTranscriptFooter(stoppedTranscript);
stoppedTranscript.Dispose();
TranscriptionData.Transcripts.Remove(stoppedTranscript);
return stoppedTranscript.Path;
if (stoppedTranscript.RunspaceInstanceId == runspaceInstanceId)
{
LogTranscriptFooter(stoppedTranscript);
stoppedTranscript.Dispose();
TranscriptionData.Transcripts.Remove(stoppedTranscript);
return stoppedTranscript.Path;
}
return null;
}
private void LogTranscriptFooter(TranscriptionOption stoppedTranscript)
@@ -514,13 +521,13 @@ namespace System.Management.Automation.Host
}
}
internal void StopAllTranscribing()
internal void StopAllTranscribing(Guid runspaceInstanceId)
{
TranscribeCommandComplete(null);
while (TranscriptionData.Transcripts.Count > 0)
foreach(var transcription in TranscriptionData.Transcripts)
{
StopTranscribing();
StopTranscribing(runspaceInstanceId);
}
lock (TranscriptionData)
@@ -999,7 +1006,7 @@ namespace System.Management.Automation.Host
internal TranscriptionOption SystemTranscript { get; set; }
internal string CommandBeingIgnored { get; set; }
internal bool IsHelperCommand { get; set; }
internal string PromptText { get; set; }
internal string PromptText { get; set; }
}
@@ -1059,6 +1066,12 @@ namespace System.Management.Automation.Host
/// </summary>
internal Encoding Encoding { get; private set; }
/// <summary>
/// RunspaceInstanceId of the transcription session.
/// This is used to choose which transcriptions are closed when runspace is disposed.
/// </summary>
internal Guid RunspaceInstanceId { get; set; }
/// <summary>
/// Logs buffered content to disk. We use this instead of File.AppendAllLines
/// so that we don't need to pay seek penalties all the time, and so that we
@@ -11,9 +11,8 @@ using System.Runtime.CompilerServices;
using System.Reflection;
using System.Text;
using Microsoft.PowerShell;
#if !CORECLR // Configuration Keyword Not Supported On CSS
using Microsoft.PowerShell.DesiredStateConfiguration.Internal;
#endif
namespace System.Management.Automation.Language
{
@@ -1091,8 +1090,6 @@ namespace System.Management.Automation.Language
return AstVisitAction.Continue;
}
#if !CORECLR // Configuration Keyword Not Supported On CSS
public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst)
{
ConfigurationDefinitionAst configAst = Ast.GetAncestorAst<ConfigurationDefinitionAst>(scriptBlockExpressionAst);
@@ -1172,7 +1169,7 @@ namespace System.Management.Automation.Language
}
return AstVisitAction.Continue;
}
}
public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst)
{
@@ -1197,7 +1194,6 @@ namespace System.Management.Automation.Language
return AstVisitAction.Continue;
}
public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordStatementAst)
{
//////////////////////////////////////////////////////////////////////////////////
@@ -1269,7 +1265,7 @@ namespace System.Management.Automation.Language
return AstVisitAction.Continue;
}
#endif //!CORECLR
public override AstVisitAction VisitPropertyMember(PropertyMemberAst propertyMemberAst)
{
@@ -1299,7 +1295,10 @@ namespace System.Management.Automation.Language
}
_scopeStack.Pop();
scriptBlockAst.PostParseChecksPerformed = true;
scriptBlockAst.HadErrors = _parser.ErrorList.Count > 0;
// at this moment, we could use different parser for the initial syntax check
// and this _parser for semantic check.
// that's why '|=' instead of just '='.
scriptBlockAst.HadErrors |= _parser.ErrorList.Count > 0;
}
else if (ast is MemberAst)
{
@@ -261,7 +261,7 @@ namespace System.Management.Automation.Language
// - Assemblies added by 'using assembly'.
// For this case, we REPORT ambiguity, since user explicitly specifies the set of assemblies.
// * All other loaded assemblies (excluding dynamic assemblies created for PS defined types).
// On FullCLR, IGNORE ambiguity. It mimics PS v4. There are two reasons:
// IGNORE ambiguity. It mimics PS v4. There are two reasons:
// 1) If we report ambiguity, we need to fix our caching logic accordingly.
// Consider this code
// Add-Type 'public class Q {}' # ok
@@ -280,7 +280,8 @@ namespace System.Management.Automation.Language
// So [NuGet.VisualStudio.IVsPackageInstallerServices] can be resolved to several different assemblies and it's ok.
// * User defined type accelerators (rare - interface was never public)
//
// If nothing is found, we search again, this time applying any 'using namespace ...' declarations including the implicit 'using namespace System'. We must search all using aliases and REPORT an error if there is an ambiguity.
// If nothing is found, we search again, this time applying any 'using namespace ...' declarations including the implicit 'using namespace System'.
// We must search all using aliases and REPORT an error if there is an ambiguity.
var assemList = assemblies ?? ClrFacade.GetAssemblies(typeResolutionState, typeName);
@@ -301,15 +302,10 @@ namespace System.Management.Automation.Language
return typeName._typeDefinitionAst.Type;
}
#if CORECLR
bool reportAmbigousException = true;
#else
bool reportAmbigousException = false;
#endif
result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, typeResolutionState, /* reportAmbigousException */ true, out exception);
if (exception == null && result == null)
{
result = ResolveTypeNameWorker(typeName, currentScope, assemList, typeResolutionState, reportAmbigousException, out exception);
result = ResolveTypeNameWorker(typeName, currentScope, assemList, typeResolutionState, /* reportAmbigousException */ false, out exception);
}
if (result != null)
@@ -337,7 +333,7 @@ namespace System.Management.Automation.Language
var newResult = ResolveTypeNameWorker(newTypeName, currentScope, typeResolutionState.assemblies, typeResolutionState, /* reportAmbigousException */ true, out exception);
if (exception == null && newResult == null)
{
newResult = ResolveTypeNameWorker(newTypeName, currentScope, assemList, typeResolutionState, reportAmbigousException, out exception);
newResult = ResolveTypeNameWorker(newTypeName, currentScope, assemList, typeResolutionState, /* reportAmbigousException */ false, out exception);
}
if (exception != null)
@@ -1131,12 +1131,17 @@ namespace System.Management.Automation.Language
if (!PostParseChecksPerformed)
{
Parser parser = new Parser();
PerformPostParseChecks(parser);
// we call PerformPostParseChecks on root ScriptBlockAst, to obey contract of SymbolResolver.
// It needs to be run from the top of the tree.
// It's ok to report an error from a different part of AST in this case.
var root = GetRootScriptBlockAst();
root.PerformPostParseChecks(parser);
if (parser.ErrorList.Any())
{
throw new ParseException(parser.ErrorList.ToArray());
}
}
if (HadErrors)
{
throw new PSInvalidOperationException();
@@ -1145,6 +1150,18 @@ namespace System.Management.Automation.Language
return new ScriptBlock(this, isFilter: false);
}
private ScriptBlockAst GetRootScriptBlockAst()
{
ScriptBlockAst rootScriptBlockAst = this;
ScriptBlockAst parent;
while ((parent = Ast.GetAncestorAst<ScriptBlockAst>(rootScriptBlockAst.Parent)) != null)
{
rootScriptBlockAst = parent;
}
return rootScriptBlockAst;
}
/// <summary>
/// Copy the ScriptBlockAst instance
/// </summary>
@@ -85,24 +85,6 @@ namespace System.Management.Automation.Runspaces
}
}
/// <summary>
/// Name of the container target
/// </summary>
public String ContainerName
{
get
{
if (ComputerType == TargetMachineType.Container)
{
return remoteRunspace.ConnectionInfo.ComputerName;
}
else
{
return string.Empty;
}
}
}
/// <summary>
/// Id of the container target
/// </summary>
@@ -360,17 +360,6 @@ namespace Microsoft.PowerShell.Commands
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override string[] ContainerName
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
@@ -143,17 +143,6 @@ namespace Microsoft.PowerShell.Commands
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override string[] ContainerName
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
@@ -281,16 +281,12 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = InvokeCommandCommand.FilePathUriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -343,11 +339,9 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
public override Int32 ThrottleLimit
{
set
@@ -394,11 +388,9 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
public SwitchParameter AsJob
{
get
@@ -453,11 +445,9 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
[Alias("HCN")]
public SwitchParameter HideComputerName
{
@@ -476,9 +466,7 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathSessionParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathUriParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
public String JobName
{
get
@@ -522,9 +510,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[ValidateNotNull]
[Alias("Command")]
public override ScriptBlock ScriptBlock
@@ -568,9 +553,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = FilePathContainerIdParameterSet)]
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = FilePathContainerNameParameterSet)]
[ValidateNotNull]
[Alias("PSPath")]
public override string FilePath
@@ -666,8 +648,6 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
public override SwitchParameter RunAsAdministrator
{
get { return base.RunAsAdministrator; }
@@ -938,11 +918,9 @@ namespace Microsoft.PowerShell.Commands
case InvokeCommandCommand.VMIdParameterSet:
case InvokeCommandCommand.VMNameParameterSet:
case InvokeCommandCommand.ContainerIdParameterSet:
case InvokeCommandCommand.ContainerNameParameterSet:
case InvokeCommandCommand.FilePathVMIdParameterSet:
case InvokeCommandCommand.FilePathVMNameParameterSet:
case InvokeCommandCommand.FilePathContainerIdParameterSet:
case InvokeCommandCommand.FilePathContainerNameParameterSet:
{
if (ResolvedComputerNames.Length != 0 && Operations.Count > 0)
{
@@ -30,7 +30,7 @@ namespace Microsoft.PowerShell.Commands
private int? _processIdleTimeoutSec = null;
internal const string AttribMaxIdleTimeout = "MaxIdleTimeoutms";
internal static readonly int? DefaultMaxIdleTimeout = 43200; // 12 hours in seconds
internal static readonly int? DefaultMaxIdleTimeout = int.MaxValue;
private int? _maxIdleTimeoutSec = null;
internal const string AttribIdleTimeout = "IdleTimeoutms";
@@ -38,27 +38,27 @@ namespace Microsoft.PowerShell.Commands
private int? _idleTimeoutSec = null;
private const string AttribMaxConcurrentUsers = "MaxConcurrentUsers";
internal static readonly int? DefaultMaxConcurrentUsers = 5;
internal static readonly int? DefaultMaxConcurrentUsers = int.MaxValue;
private int? maxConcurrentUsers = null;
private const string AttribMaxProcessesPerSession = "MaxProcessesPerShell";
internal static readonly int? DefaultMaxProcessesPerSession = 15;
internal static readonly int? DefaultMaxProcessesPerSession = int.MaxValue;
private int? maxProcessesPerSession = null;
private const string AttribMaxMemoryPerSessionMB = "MaxMemoryPerShellMB";
internal static readonly int? DefaultMaxMemoryPerSessionMB = 1024;
internal static readonly int? DefaultMaxMemoryPerSessionMB = int.MaxValue;
private int? maxMemoryPerSessionMB = null;
private const string AttribMaxSessions = "MaxShells";
internal static readonly int? DefaultMaxSessions = 25;
internal static readonly int? DefaultMaxSessions = int.MaxValue;
private int? maxSessions = null;
private const string AttribMaxSessionsPerUser = "MaxShellsPerUser";
internal static readonly int? DefaultMaxSessionsPerUser = 25;
internal static readonly int? DefaultMaxSessionsPerUser = int.MaxValue;
private int? maxSessionsPerUser = null;
private const string AttribMaxConcurrentCommandsPerSession = "MaxConcurrentCommandsPerShell";
internal static readonly int? DefaultMaxConcurrentCommandsPerSession = 1000;
internal static readonly int? DefaultMaxConcurrentCommandsPerSession = int.MaxValue;
private int? maxConcurrentCommandsPerSession = null;
/// <summary>
@@ -350,7 +350,9 @@ namespace Microsoft.PowerShell.Commands
}
if (_maxIdleTimeoutSec.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxIdleTimeout, 1000 * _maxIdleTimeoutSec));
// Special case max int value for unbounded default.
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxIdleTimeout,
(_maxIdleTimeoutSec == int.MaxValue) ? _maxIdleTimeoutSec : (1000 * _maxIdleTimeoutSec)));
}
return sb.Length > 0
@@ -167,11 +167,6 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
protected const string ContainerIdParameterSet = "ContainerId";
/// <summary>
/// Container name parameter set
/// </summary>
protected const string ContainerNameParameterSet = "ContainerName";
/// <summary>
/// VM guid parameter set
/// </summary>
@@ -601,28 +596,6 @@ namespace Microsoft.PowerShell.Commands
}
private string[] containerId;
/// <summary>
/// Name of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ContainerNameParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] ContainerName
{
get
{
return containerName;
}
set
{
containerName = value;
}
}
private string[] containerName;
/// <summary>
/// When set, PowerShell process inside container will be launched with
/// high privileged account.
@@ -630,7 +603,6 @@ namespace Microsoft.PowerShell.Commands
/// with low privileged account.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerNameParameterSet)]
public virtual SwitchParameter RunAsAdministrator
{
get
@@ -723,7 +695,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SessionParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
public virtual Int32 ThrottleLimit
@@ -1031,11 +1002,6 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
protected const string FilePathContainerIdParameterSet = "FilePathContainerId";
/// <summary>
/// Container name file path parameter set.
/// </summary>
protected const string FilePathContainerNameParameterSet = "FilePathContainerName";
#endregion
#region Parameters
@@ -1225,25 +1191,6 @@ namespace Microsoft.PowerShell.Commands
}
private string[] containerId;
/// <summary>
/// Name of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
[ValidateNotNullOrEmpty]
public override string[] ContainerName
{
get { return containerName; }
set { containerName = value; }
}
private string[] containerName;
/// <summary>
/// For WSMan session:
/// If this parameter is not specified then the value specified in
@@ -1263,16 +1210,12 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = InvokeCommandCommand.FilePathUriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -1664,26 +1607,13 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
protected virtual void CreateHelpersForSpecifiedContainerSession()
{
string[] inputArray;
bool isContainerIdSet = false;
List<string> resolvedNameList = new List<string>();
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet),
"Expected ParameterSetName == ContainerId or FilePathContainerId");
if ((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet))
{
inputArray = ContainerId;
isContainerIdSet = true;
}
else
{
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerNameParameterSet),
"Expected ParameterSetName == ContainerId, ContainerName, FilePathContainerId or FilePathContainerName");
inputArray = ContainerName;
}
foreach (var input in inputArray)
foreach (var input in ContainerId)
{
//
// Create helper objects for container ID or name.
@@ -1697,14 +1627,7 @@ namespace Microsoft.PowerShell.Commands
// Hyper-V container uses Hype-V socket as transport.
// Windows Server container uses named pipe as transport.
//
if (isContainerIdSet)
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoById(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
else
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoByName(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
resolvedNameList.Add(connectionInfo.ComputerName);
@@ -1975,11 +1898,9 @@ namespace Microsoft.PowerShell.Commands
if ((ParameterSetName == PSExecutionCmdlet.VMIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.VMNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.ContainerNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerNameParameterSet))
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet))
{
SkipWinRMCheck = true;
}
@@ -2031,9 +1952,7 @@ namespace Microsoft.PowerShell.Commands
break;
case PSExecutionCmdlet.ContainerIdParameterSet:
case PSExecutionCmdlet.ContainerNameParameterSet:
case PSExecutionCmdlet.FilePathContainerIdParameterSet:
case PSExecutionCmdlet.FilePathContainerNameParameterSet:
{
CreateHelpersForSpecifiedContainerSession();
}
@@ -2360,11 +2279,6 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
/// </summary>
protected const string ContainerIdInstanceIdParameterSet = "ContainerIdInstanceId";
/// <summary>
/// ContainerNameInstanceId parameter set: container name + session instance id
/// </summary>
protected const string ContainerNameInstanceIdParameterSet = "ContainerNameInstanceId";
/// <summary>
/// VMIdInstanceId parameter set: vm id + session instance id
/// </summary>
@@ -2483,25 +2397,6 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
}
private string[] containerId;
/// <summary>
/// Name of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.ContainerNameParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.ContainerNameInstanceIdParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] ContainerName
{
get { return containerName; }
set { containerName = value; }
}
private string[] containerName;
/// <summary>
/// Guid of target virtual machine.
/// </summary>
@@ -2606,25 +2501,13 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
// container id + optional session name
case PSRunspaceCmdlet.ContainerIdParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerId(writeobject, filterState, configurationName, true, true);
return GetMatchingRunspacesByVMNameContainerId(writeobject, filterState, configurationName, true);
}
// container id + session instanceid
case PSRunspaceCmdlet.ContainerIdInstanceIdParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, true, true);
}
// container name + optional session name
case PSRunspaceCmdlet.ContainerNameParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerId(writeobject, filterState, configurationName, true, false);
}
// container name + session instanceid
case PSRunspaceCmdlet.ContainerNameInstanceIdParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, true, false);
return GetMatchingRunspacesByVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, true);
}
// vm Guid + optional session name
@@ -2642,13 +2525,13 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
// vm name + optional session name
case PSRunspaceCmdlet.VMNameParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerId(writeobject, filterState, configurationName, false, false);
return GetMatchingRunspacesByVMNameContainerId(writeobject, filterState, configurationName, false);
}
// vm name + session instanceid
case PSRunspaceCmdlet.VMNameInstanceIdParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, false, false);
return GetMatchingRunspacesByVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, false);
}
}
@@ -2911,44 +2794,34 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
}
/// <summary>
/// Gets the matching runspaces by container name, vm name or container id with optional session name
/// Gets the matching runspaces by vm name or container id with optional session name
/// </summary>
/// <param name="writeobject">if true write the object down the pipeline</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="configurationName">Runspace configuration name filter value.</param>
/// <param name="isContainer">if true the target is a container instead of virtual machine</param>
/// <param name="useContainerId">if true the input is container id</param>
/// <returns>list of matching runspaces</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesByContainerVMNameContainerId(bool writeobject,
private Dictionary<Guid, PSSession> GetMatchingRunspacesByVMNameContainerId(bool writeobject,
SessionFilterState filterState,
String configurationName,
bool isContainer,
bool useContainerId)
bool isContainer)
{
String[] inputNames;
TargetMachineType computerType;
bool supportWildChar = false;
bool supportWildChar;
String[] sessionNames = { "*" };
WildcardPattern configurationNamePattern =
String.IsNullOrEmpty(configurationName) ? null : WildcardPattern.Get(configurationName, WildcardOptions.IgnoreCase);
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// container name and vm name support wild characters, while container id does not.
// vm name support wild characters, while container id does not.
// vm id does not apply in this method, which does not support wild characters either.
if (isContainer)
{
if (useContainerId)
{
inputNames = ContainerId;
}
else
{
inputNames = ContainerName;
supportWildChar = true;
}
inputNames = ContainerId;
computerType = TargetMachineType.Container;
supportWildChar = false;
}
else
{
@@ -2973,7 +2846,7 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
String.IsNullOrEmpty(sessionName) ? null : WildcardPattern.Get(sessionName, WildcardOptions.IgnoreCase);
var matchingRunspaceInfos = remoteRunspaceInfos
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(isContainer ? session.ContainerName : session.VMName)
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(session.VMName)
: inputName.Equals(session.ContainerId)) &&
((sessionNamePattern == null) ? true : sessionNamePattern.IsMatch(session.Name)) &&
QueryRunspaces.TestRunspaceState(session.Runspace, filterState) &&
@@ -2989,43 +2862,33 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
}
/// <summary>
/// Gets the matching runspaces by container name, vm name or container id with session instanceid
/// Gets the matching runspaces by vm name or container id with session instanceid
/// </summary>
/// <param name="writeobject">if true write the object down the pipeline</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="configurationName">Runspace configuration name filter value.</param>
/// <param name="isContainer">if true the target is a container instead of virtual machine</param>
/// <param name="useContainerId">if true the input is container id</param>
/// <returns>list of matching runspaces</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesByContainerVMNameContainerIdSessionInstanceId(bool writeobject,
private Dictionary<Guid, PSSession> GetMatchingRunspacesByVMNameContainerIdSessionInstanceId(bool writeobject,
SessionFilterState filterState,
String configurationName,
bool isContainer,
bool useContainerId)
bool isContainer)
{
String[] inputNames;
TargetMachineType computerType;
bool supportWildChar = false;
bool supportWildChar;
WildcardPattern configurationNamePattern =
String.IsNullOrEmpty(configurationName) ? null : WildcardPattern.Get(configurationName, WildcardOptions.IgnoreCase);
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// container name and vm name support wild characters, while container id does not.
// vm name support wild characters, while container id does not.
// vm id does not apply in this method, which does not support wild characters either.
if (isContainer)
{
if (useContainerId)
{
inputNames = ContainerId;
}
else
{
inputNames = ContainerName;
supportWildChar = true;
}
inputNames = ContainerId;
computerType = TargetMachineType.Container;
supportWildChar = false;
}
else
{
@@ -3041,7 +2904,7 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
foreach (Guid sessionInstanceId in InstanceId)
{
var matchingRunspaceInfos = remoteRunspaceInfos
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(isContainer ? session.ContainerName : session.VMName)
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(session.VMName)
: inputName.Equals(session.ContainerId)) &&
sessionInstanceId.Equals(session.InstanceId) &&
QueryRunspaces.TestRunspaceState(session.Runspace, filterState) &&
@@ -206,19 +206,6 @@ namespace Microsoft.PowerShell.Commands
}
private string containerId;
/// <summary>
/// The name of the target container.
/// </summary>
[ValidateNotNullOrEmpty]
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true, ParameterSetName = ContainerNameParameterSet)]
public new string ContainerName
{
get { return containerName; }
set { containerName = value; }
}
private string containerName;
/// <summary>
/// For WSMan sessions:
/// If this parameter is not specified then the value specified in
@@ -234,8 +221,6 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = EnterPSSessionCommand.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -377,7 +362,6 @@ namespace Microsoft.PowerShell.Commands
break;
case ContainerIdParameterSet:
case ContainerNameParameterSet:
remoteRunspace = GetRunspaceForContainerSession();
break;
}
@@ -923,8 +907,7 @@ namespace Microsoft.PowerShell.Commands
private bool IsParameterSetForContainer()
{
return ((ParameterSetName == ContainerIdParameterSet) ||
(ParameterSetName == ContainerNameParameterSet));
return (ParameterSetName == ContainerIdParameterSet);
}
/// <summary>
@@ -1196,8 +1179,8 @@ namespace Microsoft.PowerShell.Commands
break;
case ContainerIdParameterSet:
case ContainerNameParameterSet:
targetName = this.ContainerName;
targetName = (this.ContainerId.Length <= 15) ? this.ContainerId
: this.ContainerId.Remove(12) + "...";
break;
case SessionParameterSet:
@@ -1254,24 +1237,16 @@ namespace Microsoft.PowerShell.Commands
try
{
Dbg.Assert(!String.IsNullOrEmpty(ContainerId), "ContainerId has to be set.");
ContainerConnectionInfo connectionInfo = null;
//
// Hyper-V container uses Hype-V socket as transport.
// Windows Server container uses named pipe as transport.
//
if (!String.IsNullOrEmpty(ContainerId))
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoById(ContainerId, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
else
{
Dbg.Assert(!String.IsNullOrEmpty(ContainerName), "Either ContainerId or ContainerName has to be set.");
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(ContainerId, RunAsAdministrator.IsPresent, this.ConfigurationName);
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoByName(ContainerName, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
this.ContainerName = connectionInfo.ComputerName;
connectionInfo.CreateContainerProcess();
remoteRunspace = CreateTemporaryRemoteRunspaceForPowerShellDirect(this.Host, connectionInfo);
}
@@ -357,17 +357,6 @@ namespace Microsoft.PowerShell.Commands
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override string[] ContainerName
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
@@ -137,10 +137,6 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ContainerIdInstanceIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ContainerNameInstanceIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -176,7 +172,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.NameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameParameterSet)]
[ValidateNotNullOrEmpty()]
@@ -197,8 +192,6 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = PSRunspaceCmdlet.InstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerNameInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameInstanceIdParameterSet,
@@ -352,8 +345,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerNameInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameParameterSet)]
@@ -183,8 +183,6 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = NewPSSessionCommand.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -273,7 +271,6 @@ namespace Microsoft.PowerShell.Commands
break;
case NewPSSessionCommand.ContainerIdParameterSet:
case NewPSSessionCommand.ContainerNameParameterSet:
{
remoteRunspaces = CreateRunspacesWhenContainerParameterSpecified();
}
@@ -1023,31 +1020,18 @@ namespace Microsoft.PowerShell.Commands
}// CreateRunspacesWhenVMParameterSpecified
/// <summary>
/// Creates the remote runspace objects when the ContainerId or ContainerName parameter
/// is specified
/// Creates the remote runspace objects when the ContainerId parameter is specified
/// </summary>
private List<RemoteRunspace> CreateRunspacesWhenContainerParameterSpecified()
{
string[] inputArray;
bool isContainerIdSet = false;
int index = 0;
List<string> resolvedNameList = new List<string>();
List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>();
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet),
"Expected ParameterSetName == ContainerId");
if (ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet)
{
inputArray = ContainerId;
isContainerIdSet = true;
}
else
{
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerNameParameterSet),
"Expected ParameterSetName == ContainerId or ContainerName");
inputArray = ContainerName;
}
foreach (var input in inputArray)
foreach (var input in ContainerId)
{
//
// Create helper objects for container ID or name.
@@ -1064,14 +1048,7 @@ namespace Microsoft.PowerShell.Commands
// Hyper-V container uses Hype-V socket as transport.
// Windows Server container uses named pipe as transport.
//
if (isContainerIdSet)
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoById(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
else
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoByName(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
resolvedNameList.Add(connectionInfo.ComputerName);
@@ -78,22 +78,6 @@ namespace Microsoft.PowerShell.Commands
}
private string[] containerId;
/// <summary>
/// Name of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.ContainerNameParameterSet)]
[ValidateNotNullOrEmpty]
public override string[] ContainerName
{
get { return containerName; }
set { containerName = value; }
}
private string[] containerName;
/// <summary>
/// Guid of target virtual machine.
/// </summary>
@@ -149,7 +133,6 @@ namespace Microsoft.PowerShell.Commands
case RemovePSSessionCommand.InstanceIdParameterSet:
case RemovePSSessionCommand.IdParameterSet:
case RemovePSSessionCommand.ContainerIdParameterSet:
case RemovePSSessionCommand.ContainerNameParameterSet:
case RemovePSSessionCommand.VMIdParameterSet:
case RemovePSSessionCommand.VMNameParameterSet:
{
@@ -247,7 +247,7 @@ namespace System.Management.Automation.Runspaces
/// The duration (in ms) for which PowerShell should wait before it times out on cancel operations
/// (close runspace or stop powershell). For instance, when the user hits ctrl-C,
/// New-PSSession cmdlet tries to call a stop on all remote runspaces which are in the Opening state.
/// The administrator wouldn’t mind waiting for 15 seconds, but this should be time bound and of a shorter duration.
/// The administrator wouldn�t mind waiting for 15 seconds, but this should be time bound and of a shorter duration.
/// A high timeout here like 3 minutes will give the administrator a feeling that the PowerShell client has hung.
/// </summary>
public int CancelTimeout
@@ -2181,7 +2181,7 @@ namespace System.Management.Automation.Runspaces
/// </summary>
public override string ComputerName
{
get { return _containerProc.ContainerName; }
get { return _containerProc.ContainerId; }
set { throw new PSNotSupportedException(); }
}
@@ -2235,25 +2235,12 @@ namespace System.Management.Automation.Runspaces
/// <summary>
/// Create ContainerConnectionInfo object based on container id.
/// </summary>
public static ContainerConnectionInfo CreateContainerConnectionInfoById(
public static ContainerConnectionInfo CreateContainerConnectionInfo(
string containerId,
bool runAsAdmin,
string configurationName)
{
ContainerProcess containerProc = new ContainerProcess(containerId, null, null, 0, runAsAdmin, configurationName);
return new ContainerConnectionInfo(containerProc);
}
/// <summary>
/// Create ContainerConnectionInfo object based on container name.
/// </summary>
public static ContainerConnectionInfo CreateContainerConnectionInfoByName(
string containerName,
bool runAsAdmin,
string configurationName)
{
ContainerProcess containerProc = new ContainerProcess(null, containerName, null, 0, runAsAdmin, configurationName);
ContainerProcess containerProc = new ContainerProcess(containerId, null, 0, runAsAdmin, configurationName);
return new ContainerConnectionInfo(containerProc);
}
@@ -2290,7 +2277,6 @@ namespace System.Management.Automation.Runspaces
private Guid runtimeId;
private string containerObRoot;
private string containerId;
private string containerName;
private int processId;
private bool runAsAdmin = false;
private string configurationName;
@@ -2301,8 +2287,6 @@ namespace System.Management.Automation.Runspaces
private const uint NoError = 0;
private const uint InvalidContainerId = 1;
private const uint ContainersFeatureNotEnabled = 2;
private const uint InvalidContainerNameMultiple = 3;
private const uint InvalidContainerNameNotExist = 4;
private const uint OtherError = 9999;
#endregion
@@ -2337,15 +2321,6 @@ namespace System.Management.Automation.Runspaces
set { containerId = value; }
}
/// <summary>
/// Name of the container.
/// </summary>
public string ContainerName
{
get { return containerName; }
set { containerName = value; }
}
/// <summary>
/// Process ID of the process created in container.
/// </summary>
@@ -2405,16 +2380,67 @@ namespace System.Management.Automation.Runspaces
#region Native HCS (i.e., host compute service) methods
[StructLayout(LayoutKind.Sequential)]
internal struct HCS_PROCESS_INFORMATION
{
/// <summary>
/// The process id.
/// </summary>
public uint ProcessId;
/// <summary>
/// Reserved.
/// </summary>
public uint Reserved;
/// <summary>
/// If created, standard input handle of the process.
/// </summary>
public IntPtr StdInput;
/// <summary>
/// If created, standard output handle of the process.
/// </summary>
public IntPtr StdOutput;
/// <summary>
/// If created, standard error handle of the process.
/// </summary>
public IntPtr StdError;
}
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint CreateProcessInComputeSystem(
string id,
string ProcessParameters,
ref int processId);
internal static extern uint HcsOpenComputeSystem(
string id,
ref IntPtr computeSystem,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint TerminateProcessInComputeSystem(
string id,
int processId);
internal static extern uint HcsGetComputeSystemProperties(
IntPtr computeSystem,
string propertyQuery,
ref string properties,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsCreateProcess(
IntPtr computeSystem,
string processParameters,
ref HCS_PROCESS_INFORMATION processInformation,
ref IntPtr process,
ref string reslt);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsOpenProcess(
IntPtr computeSystem,
int processId,
ref IntPtr process,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsTerminateProcess(
IntPtr process,
ref string result);
#endregion
@@ -2423,30 +2449,17 @@ namespace System.Management.Automation.Runspaces
/// <summary>
/// Creates an instance used for PowerShell Direct for container.
/// </summary>
public ContainerProcess(string containerId, string containerName, string containerObRoot, int processId, bool runAsAdmin, string configurationName)
public ContainerProcess(string containerId, string containerObRoot, int processId, bool runAsAdmin, string configurationName)
{
this.ContainerId = containerId;
this.ContainerName = containerName;
this.ContainerObRoot = containerObRoot;
this.ProcessId = processId;
this.RunAsAdmin = runAsAdmin;
this.ConfigurationName = configurationName;
if (!String.IsNullOrEmpty(containerId))
{
if (String.IsNullOrEmpty(containerName))
{
GetContainerPropertiesFromContainerId();
}
}
else if (!String.IsNullOrEmpty(containerName))
{
GetContainerPropertiesFromContainerName();
}
else
{
Dbg.Assert(false, "containerId and containerName inputs cannot be empty at the same time.");
}
Dbg.Assert(!String.IsNullOrEmpty(containerId), "containerId input cannot be empty.");
GetContainerProperties();
}
#endregion
@@ -2497,11 +2510,11 @@ namespace System.Management.Automation.Runspaces
}
/// <summary>
/// Get container name and object root based on given container id.
/// Get object root based on given container id.
/// </summary>
public void GetContainerPropertiesFromContainerId()
public void GetContainerProperties()
{
RunOnMTAThread(GetContainerPropertiesFromContainerIdInternal);
RunOnMTAThread(GetContainerPropertiesInternal);
//
// Report error.
@@ -2519,37 +2532,6 @@ namespace System.Management.Automation.Runspaces
}
}
/// <summary>
/// Get container id and object root based on given container name.
/// </summary>
public void GetContainerPropertiesFromContainerName()
{
RunOnMTAThread(GetContainerPropertiesFromContainerNameInternal);
//
// Report error.
//
switch (ErrorCode)
{
case NoError:
break;
case ContainersFeatureNotEnabled:
throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.ContainersFeatureNotEnabled));
case InvalidContainerNameMultiple:
throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidContainerNameMultiple,
ContainerName));
case InvalidContainerNameNotExist:
throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidContainerNameNotExist,
ContainerName));
case OtherError:
throw new PSInvalidOperationException(ErrorMessage);
}
}
#endregion
#region Private methods
@@ -2583,14 +2565,11 @@ namespace System.Management.Automation.Runspaces
//
try
{
Type computeSystemPropertiesType;
Type hostComputeInteropType;
GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType);
MethodInfo computeSystemExistsInfo = hostComputeInteropType.GetMethod("ComputeSystemExists");
if (!(bool)computeSystemExistsInfo.Invoke(null, new object[]{ ContainerId }))
IntPtr ComputeSystem = IntPtr.Zero;
string resultString = String.Empty;
result = HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString);
if (result != 0)
{
processId = 0;
error = InvalidContainerId;
@@ -2606,19 +2585,23 @@ namespace System.Management.Automation.Runspaces
(RuntimeId != Guid.Empty) ? "-so -NoProfile" : "-NamedPipeServerMode",
String.IsNullOrEmpty(ConfigurationName) ? String.Empty : String.Concat("-Config ", ConfigurationName),
(RunAsAdmin) ? "false" : "true");
HCS_PROCESS_INFORMATION ProcessInformation = new HCS_PROCESS_INFORMATION();
IntPtr Process = IntPtr.Zero;
//
// Create PowerShell process inside the container.
//
result = CreateProcessInComputeSystem(
ContainerId,
cmd,
ref processId);
result = HcsCreateProcess(ComputeSystem, cmd, ref ProcessInformation, ref Process, ref resultString);
if (result != 0)
{
processId = 0;
error = result;
}
else
{
processId = Convert.ToInt32(ProcessInformation.ProcessId);
}
}
}
catch (Exception e)
@@ -2654,35 +2637,54 @@ namespace System.Management.Automation.Runspaces
/// </summary>
private void TerminateContainerProcessInternal()
{
ProcessTerminated =
(TerminateProcessInComputeSystem(ContainerId, ProcessId) == 0);
IntPtr ComputeSystem = IntPtr.Zero;
string resultString = String.Empty;
IntPtr process = IntPtr.Zero;
ProcessTerminated = false;
if (HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString) == 0)
{
if (HcsOpenProcess(ComputeSystem, ProcessId, ref process, ref resultString) == 0)
{
if (HcsTerminateProcess(process, ref resultString) == 0)
{
ProcessTerminated = true;
}
}
}
}
/// <summary>
/// Get container name and object root based on given container id.
/// Get object root based on given container id.
/// </summary>
private void GetContainerPropertiesFromContainerIdInternal()
private void GetContainerPropertiesInternal()
{
try
{
Type computeSystemPropertiesType;
Type hostComputeInteropType;
GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType);
IntPtr ComputeSystem = IntPtr.Zero;
string resultString = String.Empty;
MethodInfo getComputeSystemPropertiesInfo = hostComputeInteropType.GetMethod("GetComputeSystemProperties");
var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[]{ ContainerId });
ContainerName = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(computeSystemPropertiesHandle);
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
//
// Get container object root for Windows Server container.
//
if (RuntimeId == Guid.Empty)
if (HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString) == 0)
{
ContainerObRoot = (string)computeSystemPropertiesType.GetProperty("ObRoot").GetValue(computeSystemPropertiesHandle);
Type computeSystemPropertiesType;
Type hostComputeInteropType;
GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType);
MethodInfo getComputeSystemPropertiesInfo = hostComputeInteropType.GetMethod("HcsGetComputeSystemProperties");
var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[]{ ComputeSystem });
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
//
// Get container object root for Windows Server container.
//
if (RuntimeId == Guid.Empty)
{
ContainerObRoot = (string)computeSystemPropertiesType.GetProperty("ObRoot").GetValue(computeSystemPropertiesHandle);
}
}
}
catch (FileNotFoundException)
@@ -2712,77 +2714,6 @@ namespace System.Management.Automation.Runspaces
}
}
/// <summary>
/// Get container id and object root based on given container name.
/// </summary>
private void GetContainerPropertiesFromContainerNameInternal()
{
try
{
Type computeSystemPropertiesType;
Type hostComputeInteropType;
object computeSystemPropertiesHandle = null;
int computeSystemPropertiesHandlesCount = 0;
var wildCardPattern = WildcardPattern.Get(ContainerName, WildcardOptions.IgnoreCase);
GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType);
MethodInfo enumerateComputeSystemsInfo = hostComputeInteropType.GetMethod("EnumerateComputeSystems");
var computeSystemPropertiesHandles = (IEnumerable)enumerateComputeSystemsInfo.Invoke(null, new object[] { null, null, null, null });
foreach (var currentComputeSystemPropertiesHandle in computeSystemPropertiesHandles)
{
string name = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(currentComputeSystemPropertiesHandle);
if (wildCardPattern.IsMatch(name))
{
computeSystemPropertiesHandle = currentComputeSystemPropertiesHandle;
computeSystemPropertiesHandlesCount++;
if (computeSystemPropertiesHandlesCount > 1)
{
ErrorCode = InvalidContainerNameMultiple;
return;
}
}
}
if (computeSystemPropertiesHandle == null)
{
ErrorCode = InvalidContainerNameNotExist;
return;
}
ContainerId = (string)computeSystemPropertiesType.GetProperty("Id").GetValue(computeSystemPropertiesHandle);
ContainerName = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(computeSystemPropertiesHandle);
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
//
// Get container object root for Windows Server container.
//
if (RuntimeId == Guid.Empty)
{
ContainerObRoot = (string)computeSystemPropertiesType.GetProperty("ObRoot").GetValue(computeSystemPropertiesHandle);
}
}
catch (FileNotFoundException)
{
ErrorCode = ContainersFeatureNotEnabled;
}
catch (FileLoadException)
{
ErrorCode = ContainersFeatureNotEnabled;
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
ErrorCode = OtherError;
ErrorMessage = GetErrorMessageFromException(e);
}
}
/// <summary>
/// Run some tasks on MTA thread if needed.
/// </summary>
@@ -228,8 +228,6 @@ namespace System.Management.Automation.Remoting
CannotTerminateProcessInContainer = 968,
ContainersFeatureNotEnabled = 969,
RemoteSessionHyperVSocketServerConstructorFailure = 970,
InvalidContainerNameMultiple = 971,
InvalidContainerNameNotExist = 972,
ContainerSessionConnectFailed = 973,
RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure = 974,
InvalidVMState = 975,
@@ -459,7 +459,28 @@ namespace System.Management.Automation.Remoting
{
return WSManPluginConstants.ExitCodeFailure;
}
#if !CORECLR
// For long-path support, Full .NET requires some AppContext switches;
// (for CoreCLR this is Not needed, because CoreCLR supports long paths by default)
// internally in .NET they are cached once retrieved and are typically hit very early during an application run;
// so per .NET team's recommendation, we are setting them as soon as we enter managed code.
// We build against CLR4.5 so we can run on Win7/Win8, but we want to use apis added to CLR 4.6, so we use reflection
try
{
Type appContextType = Type.GetType("System.AppContext"); // type is in mscorlib, so it is sufficient to supply the type name qualified by its namespace
object[] blockLongPathsSwitch = new object[] { "Switch.System.IO.BlockLongPaths", false };
object[] useLegacyPathHandlingSwitch = new object[] { "Switch.System.IO.UseLegacyPathHandling", false };
appContextType.InvokeMember("SetSwitch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod, null, null, blockLongPathsSwitch);
appContextType.InvokeMember("SetSwitch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod, null, null, useLegacyPathHandlingSwitch);
}
catch (Exception e)
{
// If there are any non-critical exceptions (e.g. we are running on CLR prior to 4.6.2), we won't be able to use long paths
CommandProcessorBase.CheckForSevereException(e);
}
#endif
ClrFacade.StructureToPtr<WSManPluginEntryDelegates.WSManPluginEntryDelegatesInternal>(workerPtrs.UnmanagedStruct, wkrPtrs, false);
return WSManPluginConstants.ExitCodeSuccess;
}
@@ -596,9 +596,11 @@ namespace System.Management.Automation.Language
// function wouldn't work properly. Instead, we'll fix things up after the binding decisions are made, see
// EnumerableOps.NonEnumerableObjectEnumerator for more comments on how this works.
var bindingRestrictions = BindingRestrictions.GetExpressionRestriction(
Expression.Call(typeof(PSEnumerableBinder).GetMethod("IsComObject", BindingFlags.Static | BindingFlags.NonPublic),
target.Expression));
return new DynamicMetaObject(
Expression.Call(CachedReflectionInfo.EnumerableOps_GetCOMEnumerator, target.Expression),
GetRestrictions(target)).WriteToDebugLog(this);
Expression.Call(CachedReflectionInfo.EnumerableOps_GetCOMEnumerator, target.Expression), bindingRestrictions).WriteToDebugLog(this);
}
var enumerable = targetValue as IEnumerable;
@@ -687,8 +689,8 @@ namespace System.Management.Automation.Language
internal static bool IsComObject(object obj)
{
// Platform notes: We can't use System.Runtime.InteropServices.Marshal.IsComObject(obj)
// since it doesn't work in partial trust
// we can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) since it doesn't work in partial trust
obj = PSObject.Base(obj);
return obj != null && ComObjectTypeInfo != null && ComObjectTypeInfo.IsAssignableFrom(obj.GetType().GetTypeInfo());
}
@@ -701,7 +703,7 @@ namespace System.Management.Automation.Language
private static IEnumerator NotEnumerableRule(CallSite site, object obj)
{
if (!(obj is PSObject) && !(obj is IEnumerable) && !(obj is IEnumerator) && !(obj is DataTable))
if (!(obj is PSObject) && !(obj is IEnumerable) && !(obj is IEnumerator) && !(obj is DataTable) && !IsComObject(obj))
{
return null;
}
@@ -9,9 +9,137 @@ using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Management.Automation.Language;
using System.Threading;
namespace System.Management.Automation
// These APIs are not part of the public contract.
// They are implementation details and intendent to be called from generated assemlbies for PS classes.
//
// Because they are called from other assemblies, we have to make them public.
// We put them in Internal namespace to emphasise that despite the fact that they are public, it's not part of API contract.
namespace System.Management.Automation.Internal
{
/// <summary>
/// Every Runspace in one process contains SessionStateInternal per module (module SessionState).
/// Every RuntimeType is associated to only one SessionState in the Runspace, which creates it:
/// it's ever global state or a module state.
/// In the former case, module can be imported from the different runspaces in the same process.
/// And so runspaces will share RuntimeType. But in every runspace, Type is associated with just one SessionState.
/// We want type methods to be able access $script: variables and module-specific methods.
/// To achive it, we preserve reference to SessionState that creates type in the private field 'SessionStateFieldName'.
/// Later, we use it to call scriptBlocks captured in ScriptBlockMemberMethodWrapper with the right sessionState.
/// </summary>
public class SessionStateKeeper
{
// We use ConditionalWeakTable, because if GC already collect Runspace,
// then there is no way to call a ctor on the type in this Runspace.
private readonly ConditionalWeakTable<Runspace, SessionStateInternal> _stateMap;
internal SessionStateKeeper()
{
_stateMap = new ConditionalWeakTable<Runspace, SessionStateInternal>();
}
internal void RegisterRunspace()
{
// it's not get, but really 'Add' value.
// ConditionalWeakTable.Add throw exception, when you are trying to add a value with the same key.
_stateMap.GetValue(Runspace.DefaultRunspace, runspace => runspace.ExecutionContext.EngineSessionState);
}
/// <summary>
/// This method should be called only from generated ctors for PowerShell classes.
/// It's not intended to be a public API, but because we generate type in a different assembly it has to be public.
/// Return type should be SessionStateInternal, but it violates accessibility consistency, so we use object.
/// </summary>
/// <returns>SessionStateInternal</returns>
public object GetSessionState()
{
SessionStateInternal ss = null;
bool found = _stateMap.TryGetValue(Runspace.DefaultRunspace, out ss);
Diagnostics.Assert(found, "We always should be able to find corresponding SessionState");
return ss;
}
}
/// <summary/>
public class ScriptBlockMemberMethodWrapper
{
/// <summary>Used in codegen</summary>
public static readonly object[] _emptyArgumentArray = Utils.EmptyArray<object>(); // See TypeDefiner.DefineTypeHelper.DefineMethodBody
// we use this _scriptBlock instance for static methods.
private Lazy<ScriptBlock> _scriptBlock;
private IParameterMetadataProvider _ast;
/// <summary>
/// We use ThreadLocal boundScriptBlock to allow multi-thread execution of instance methods.
/// </summary>
private ThreadLocal<ScriptBlock> _boundScriptBlock;
internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast)
{
_ast = ast;
_scriptBlock = new Lazy<ScriptBlock>(() => new ScriptBlock(_ast, isFilter: false));
_boundScriptBlock = new ThreadLocal<ScriptBlock>(
() =>
{
var sb = _scriptBlock.Value.Clone();
return sb;
});
}
internal void InitAtRuntime()
{
var context = Runspace.DefaultRunspace.ExecutionContext;
_scriptBlock.Value.SessionStateInternal = context.EngineSessionState;
}
/// <summary>
/// </summary>
/// <param name="instance">target object or null for static call</param>
/// <param name="sessionStateInternal">sessionStateInternal from private field of instance or null for static call</param>
/// <param name="args"></param>
public void InvokeHelper(object instance, object sessionStateInternal, object[] args)
{
ScriptBlock sb;
if (instance != null)
{
_boundScriptBlock.Value.SessionStateInternal = (SessionStateInternal)sessionStateInternal;
sb = _boundScriptBlock.Value;
}
else
{
sb = _scriptBlock.Value;
}
sb.InvokeAsMemberFunction(instance, args);
}
/// <summary>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance">target object or null for static call</param>
/// <param name="sessionStateInternal">sessionStateInternal from private field of instance or null for static call</param>
/// <param name="args"></param>
/// <returns></returns>
public T InvokeHelperT<T>(object instance, object sessionStateInternal, object[] args)
{
ScriptBlock sb;
if (instance != null)
{
_boundScriptBlock.Value.SessionStateInternal = (SessionStateInternal)sessionStateInternal;
sb = _boundScriptBlock.Value;
}
else
{
sb = _scriptBlock.Value;
}
return sb.InvokeAsMemberFunctionT<T>(instance, args);
}
}
/// <summary>
/// Support methods for PowerShell classes.
/// </summary>
@@ -17,10 +17,6 @@ using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
#if !CORECLR
using Microsoft.CodeAnalysis;
#endif
using Microsoft.PowerShell.Commands;
// ReSharper disable UnusedMember.Global
@@ -1183,127 +1179,6 @@ namespace System.Management.Automation
}
}
/// <summary>
/// Every Runspace in one process contains SessionStateInternal per module (module SessionState).
/// Every RuntimeType is associated to only one SessionState in the Runspace, which creates it:
/// it's ever global state or a module state.
/// In the former case, module can be imported from the different runspaces in the same process.
/// And so runspaces will share RuntimeType. But in every runspace, Type is associated with just one SessionState.
/// We want type methods to be able access $script: variables and module-specific methods.
/// To achive it, we preserve reference to SessionState that creates type in the private field 'SessionStateFieldName'.
/// Later, we use it to call scriptBlocks captured in ScriptBlockMemberMethodWrapper with the right sessionState.
/// </summary>
public class SessionStateKeeper
{
// We use ConditionalWeakTable, because if GC already collect Runspace,
// then there is no way to call a ctor on the type in this Runspace.
private readonly ConditionalWeakTable<Runspace, SessionStateInternal> _stateMap;
internal SessionStateKeeper()
{
_stateMap = new ConditionalWeakTable<Runspace, SessionStateInternal>();
}
internal void RegisterRunspace()
{
// it's not get, but really 'Add' value.
// ConditionalWeakTable.Add throw exception, when you are trying to add a value with the same key.
_stateMap.GetValue(Runspace.DefaultRunspace, runspace => runspace.ExecutionContext.EngineSessionState);
}
/// <summary>
/// This method should be called only from generated ctors for PowerShell classes.
/// It's not intended to be a public API, but because we generate type in a different assembly it has to be public.
/// Return type should be SessionStateInternal, but it violates accessibility consistency, so we use object.
/// </summary>
/// <returns>SessionStateInternal</returns>
public object GetSessionState()
{
SessionStateInternal ss = null;
bool found = _stateMap.TryGetValue(Runspace.DefaultRunspace, out ss);
Diagnostics.Assert(found, "We always should be able to find corresponding SessionState");
return ss;
}
}
/// <summary/>
public class ScriptBlockMemberMethodWrapper
{
/// <summary>Used in codegen</summary>
public static readonly object[] _emptyArgumentArray = Utils.EmptyArray<object>(); // See TypeDefiner.DefineTypeHelper.DefineMethodBody
// we use this _scriptBlock instance for static methods.
private Lazy<ScriptBlock> _scriptBlock;
private IParameterMetadataProvider _ast;
/// <summary>
/// We use ThreadLocal boundScriptBlock to allow multi-thread execution of instance methods.
/// </summary>
private ThreadLocal<ScriptBlock> _boundScriptBlock;
internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast)
{
_ast = ast;
_scriptBlock = new Lazy<ScriptBlock>(() => new ScriptBlock(_ast, isFilter: false));
_boundScriptBlock = new ThreadLocal<ScriptBlock>(
() =>
{
var sb = _scriptBlock.Value.Clone();
return sb;
});
}
internal void InitAtRuntime()
{
var context = Runspace.DefaultRunspace.ExecutionContext;
_scriptBlock.Value.SessionStateInternal = context.EngineSessionState;
}
/// <summary>
/// </summary>
/// <param name="instance">target object or null for static call</param>
/// <param name="sessionStateInternal">sessionStateInternal from private field of instance or null for static call</param>
/// <param name="args"></param>
public void InvokeHelper(object instance, object sessionStateInternal, object[] args)
{
ScriptBlock sb;
if (instance != null)
{
_boundScriptBlock.Value.SessionStateInternal = (SessionStateInternal)sessionStateInternal;
sb = _boundScriptBlock.Value;
}
else
{
sb = _scriptBlock.Value;
}
sb.InvokeAsMemberFunction(instance, args);
}
/// <summary>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance">target object or null for static call</param>
/// <param name="sessionStateInternal">sessionStateInternal from private field of instance or null for static call</param>
/// <param name="args"></param>
/// <returns></returns>
public T InvokeHelperT<T>(object instance, object sessionStateInternal, object[] args)
{
ScriptBlock sb;
if (instance != null)
{
_boundScriptBlock.Value.SessionStateInternal = (SessionStateInternal)sessionStateInternal;
sb = _boundScriptBlock.Value;
}
else
{
sb = _scriptBlock.Value;
}
return sb.InvokeAsMemberFunctionT<T>(instance, args);
}
}
static class HashtableOps
{
internal static void AddKeyValuePair(IDictionary hashtable, object key, object value, IScriptExtent errorExtent)
@@ -250,22 +250,22 @@ namespace System.Management.Automation
private void GetModuleNameAndVersion(string psmodulePathRoot, string filePath, out string moduleName, out Version moduleVersion)
{
Version returnVersion = null;
string returnModuleName = null;
moduleVersion = null;
moduleName = null;
if (filePath.StartsWith(psmodulePathRoot))
if (filePath.StartsWith(psmodulePathRoot, StringComparison.OrdinalIgnoreCase))
{
var moduleRootSubPath = filePath.Remove(0, psmodulePathRoot.Length).TrimStart(Utils.Separators.Directory);
var pathParts = moduleRootSubPath.Split(Utils.Separators.Directory, StringSplitOptions.RemoveEmptyEntries);
//returnModuleRootPath = Path.Combine(psmodulePathRoot, pathParts[0]);
returnModuleName = pathParts[0];
moduleName = pathParts[0];
var potentialVersion = pathParts[1];
Version.TryParse(potentialVersion, out returnVersion);
Version result;
if (Version.TryParse(potentialVersion, out result))
{
moduleVersion = result;
}
}
moduleVersion = returnVersion;
moduleName = returnModuleName;
}
/// <summary>
@@ -392,7 +392,7 @@
<value>Minimum version of the Windows PowerShell engine required by this module</value>
</data>
<data name="CLRVersion" xml:space="preserve">
<value>Minimum version of the common language runtime (CLR) required by this module</value>
<value>Minimum version of the common language runtime (CLR) required by this module. {0}</value>
</data>
<data name="RequiredModules" xml:space="preserve">
<value>Modules that must be imported into the global environment prior to importing this module</value>
@@ -473,7 +473,7 @@
<value>List of all modules packaged with this module</value>
</data>
<data name="DotNetFrameworkVersion" xml:space="preserve">
<value>Minimum version of Microsoft .NET Framework required by this module</value>
<value>Minimum version of Microsoft .NET Framework required by this module. {0}</value>
</data>
<data name="PowerShellHostName" xml:space="preserve">
<value>Name of the Windows PowerShell host required by this module</value>
@@ -634,4 +634,7 @@
<data name="ManifestMemberNotValid" xml:space="preserve">
<value>The module to process '{0}', listed in field '{1}' of module manifest '{2}' was not processed. {3}</value>
</data>
</root>
<data name="PrerequisiteForDesktopEditionOnly" xml:space="preserve">
<value>This prerequisite is valid for the PowerShell Desktop edition only.</value>
</data>
</root>
@@ -1204,12 +1204,6 @@ All WinRM sessions connected to Windows PowerShell session configurations, such
<data name="InvalidContainerId" xml:space="preserve">
<value>The input ContainerId {0} does not exist, or the corresponding container is not running.</value>
</data>
<data name="InvalidContainerNameMultiple" xml:space="preserve">
<value>The input ContainerName {0} does not resolve to a single running container.</value>
</data>
<data name="InvalidContainerNameNotExist" xml:space="preserve">
<value>The input ContainerName {0} does not exist, or the corresponding container is not running.</value>
</data>
<data name="InvalidVMId" xml:space="preserve">
<value>The input VMId parameter does not resolve to a single virtual machine.</value>
</data>
@@ -121,6 +121,7 @@ namespace System.Management.Automation
///
/// <remarks> </remarks>
///
[ArchitectureSensitive]
internal static Signature SignFile(SigningOption option,
string fileName,
X509Certificate2 certificate,
@@ -312,6 +313,7 @@ namespace System.Management.Automation
///
/// <remarks> </remarks>
///
[ArchitectureSensitive]
internal static Signature GetSignature(string fileName, string fileContent)
{
Signature signature = null;
@@ -503,6 +505,7 @@ namespace System.Management.Automation
return signature;
}
[ArchitectureSensitive]
private static DWORD GetWinTrustData(string fileName, string fileContent,
out NativeMethods.WINTRUST_DATA wtData)
{
@@ -559,6 +562,7 @@ namespace System.Management.Automation
return dwResult;
}
[ArchitectureSensitive]
private static X509Certificate2 GetCertFromChain(IntPtr pSigner)
{
X509Certificate2 signerCert = null;
@@ -581,6 +585,7 @@ namespace System.Management.Automation
return signerCert;
}
[ArchitectureSensitive]
private static Signature GetSignatureFromWintrustData(
string filePath,
DWORD error,
@@ -653,6 +658,7 @@ namespace System.Management.Automation
return signature;
}
[ArchitectureSensitive]
private static DWORD GetLastWin32Error()
{
int error = Marshal.GetLastWin32Error();
@@ -76,6 +76,7 @@ namespace Microsoft.PowerShell
///
/// <returns> contents of s (char[]) converted to byte[] </returns>
///
[ArchitectureSensitive]
internal static byte[] GetData(SecureString s)
{
//
@@ -466,6 +466,7 @@ namespace System.Management.Automation
///
/// <param name="path">The path to the file in question</param>
/// <param name="handle">A file handle to the file in question, if available.</param>
[ArchitectureSensitive]
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")]
internal static SaferPolicy GetSaferPolicy(string path, SafeHandle handle)
{
@@ -758,6 +759,7 @@ namespace System.Management.Automation
///
/// <remarks> </remarks>
///
[ArchitectureSensitive]
internal static Collection<string> GetCertEKU(X509Certificate2 cert)
{
Collection<string> ekus = new Collection<string>();
@@ -587,6 +587,7 @@ namespace System.Management.Automation.Security
internal IntPtr psUnauthenticatedNotUsed; // PCRYPT_ATTRIBUTES
};
[ArchitectureSensitive]
internal static CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO
InitSignInfoExtendedStruct(string description,
string moreInfoUrl,
@@ -692,6 +693,7 @@ namespace System.Management.Automation.Security
uint dwGroupId);
[ArchitectureSensitive]
internal static DWORD GetCertChoiceFromSigningOption(
SigningOption option)
{
@@ -719,6 +721,7 @@ namespace System.Management.Automation.Security
return cc;
}
[ArchitectureSensitive]
internal static CRYPTUI_WIZ_DIGITAL_SIGN_INFO
InitSignInfoStruct(string fileName,
X509Certificate2 signingCert,
@@ -815,6 +818,7 @@ namespace System.Management.Automation.Security
internal byte[] Data4;
}
[ArchitectureSensitive]
internal static WINTRUST_FILE_INFO InitWintrustFileInfoStruct(string fileName)
{
WINTRUST_FILE_INFO fi = new WINTRUST_FILE_INFO();
@@ -827,6 +831,7 @@ namespace System.Management.Automation.Security
return fi;
}
[ArchitectureSensitive]
internal static WINTRUST_BLOB_INFO InitWintrustBlobInfoStruct(string fileName, string content)
{
WINTRUST_BLOB_INFO bi = new WINTRUST_BLOB_INFO();
@@ -959,6 +964,7 @@ namespace System.Management.Automation.Security
internal uint dwUIContext;
}
[ArchitectureSensitive]
internal static WINTRUST_DATA InitWintrustDataStructFromFile(WINTRUST_FILE_INFO wfi)
{
WINTRUST_DATA wtd = new WINTRUST_DATA();
@@ -982,6 +988,7 @@ namespace System.Management.Automation.Security
return wtd;
}
[ArchitectureSensitive]
internal static WINTRUST_DATA InitWintrustDataStructFromBlob(WINTRUST_BLOB_INFO wbi)
{
WINTRUST_DATA wtd = new WINTRUST_DATA();
@@ -1005,6 +1012,7 @@ namespace System.Management.Automation.Security
return wtd;
}
[ArchitectureSensitive]
internal static DWORD DestroyWintrustDataStruct(WINTRUST_DATA wtd)
{
DWORD dwResult = Win32Errors.E_FAIL;
@@ -95,7 +95,17 @@ namespace System.Management.Automation
internal static IntPtr GetRawProcessHandle(Process process)
{
#if CORECLR
try
{
return process.SafeHandle.DangerousGetHandle();
}
catch (InvalidOperationException)
{
// It's possible that the process has already exited when we try to get its handle.
// In that case, InvalidOperationException will be thrown from Process.SafeHandle,
// and we return the invalid zero pointer.
return IntPtr.Zero;
}
#else
return process.Handle;
#endif
@@ -866,7 +866,7 @@ namespace System.Management.Automation
internal static readonly string[] ManifestModuleVersionPropertyName = new[] {"ModuleVersion"};
internal static readonly string[] ManifestGuidPropertyName = new[] { "GUID" };
internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] {"AliasesToExport", "CmdletsToExport", "FunctionsToExport", "NestedModules", "RootModule", "ModuleToProcess"};
internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] {"AliasesToExport", "CmdletsToExport", "FunctionsToExport", "NestedModules", "RootModule", "ModuleToProcess", "ModuleVersion"};
internal static Hashtable GetModuleManifestProperties(string psDataFilePath, string[] keys)
{