diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs
new file mode 100644
index 0000000000..48ee46bfde
--- /dev/null
+++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs
@@ -0,0 +1,342 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+
+using Microsoft.Management.Infrastructure;
+
+namespace Microsoft.PowerShell.Commands
+{
+ using Extensions;
+
+ internal static class CIMHelper
+ {
+ internal static class ClassNames
+ {
+ internal const string OperatingSystem = "Win32_OperatingSystem";
+ internal const string PageFileUsage = "Win32_PageFileUsage";
+ internal const string Bios = "Win32_BIOS";
+ internal const string BaseBoard = "Win32_BaseBoard";
+ internal const string ComputerSystem = "Win32_ComputerSystem";
+ internal const string Keyboard = "Win32_Keyboard";
+ internal const string DeviceGuard = "Win32_DeviceGuard";
+ internal const string HotFix = "Win32_QuickFixEngineering";
+ internal const string MicrosoftNetworkAdapter = "MSFT_NetAdapter";
+ internal const string NetworkAdapter = "Win32_NetworkAdapter";
+ internal const string NetworkAdapterConfiguration = "Win32_NetworkAdapterConfiguration";
+ internal const string Processor = "Win32_Processor";
+ internal const string PhysicalMemory = "Win32_PhysicalMemory";
+ internal const string TimeZone = "Win32_TimeZone";
+ }
+
+ internal const string DefaultNamespace = @"root\cimv2";
+ internal const string DeviceGuardNamespace = @"root\Microsoft\Windows\DeviceGuard";
+ internal const string MicrosoftNetworkAdapterNamespace = "root/StandardCimv2";
+ internal const string DefaultQueryDialect = "WQL";
+
+ ///
+ /// Create a WQL query string to retrieve all properties from
+ /// the specified WMI class.
+ ///
+ /// A string containing the WMI class name.
+ ///
+ /// A string containing the WQL query string
+ ///
+ internal static string WqlQueryAll(string from)
+ {
+ return "SELECT * from " + from;
+ }
+
+ ///
+ /// Retrieve a new object of type T, whose properties and fields are
+ /// populated from an instance of the named WMI class. If the CIM
+ /// query results in multiple instances, only the first instance is
+ /// returned.
+ ///
+ ///
+ /// The type of the object to be created. Must be a default-constructable
+ /// reference type.
+ ///
+ ///
+ /// The CIM session to be queried.
+ ///
+ ///
+ /// A string containing the namespace to run the query against
+ ///
+ ///
+ /// A string containing the name of the WMI class from which to populate
+ /// the resultant object.
+ ///
+ ///
+ /// A new object of type T if successful, null otherwise.
+ ///
+ ///
+ /// This method matches property and field names of type T with identically
+ /// named properties in the WMI class instance. The WMI property is converted
+ /// to the type of T's property or field.
+ ///
+ internal static T GetFirst(CimSession session, string nameSpace, string wmiClassName) where T : class, new()
+ {
+ if (string.IsNullOrEmpty(wmiClassName))
+ throw new ArgumentException("String argument may not be null or empty", "wmiClassName");
+
+ try
+ {
+ var type = typeof(T);
+ var binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
+ T rv = new T();
+
+ using (var instance = session.QueryFirstInstance(nameSpace, CIMHelper.WqlQueryAll(wmiClassName)))
+ {
+ SetObjectDataMembers(rv, binding, instance);
+ }
+
+ return rv;
+ }
+ catch (Exception /*ex*/)
+ {
+ // on any error fall through to the null return below
+ }
+
+ return null;
+ }
+
+ ///
+ /// Retrieve an array of new objects of type T, whose properties and fields are
+ /// populated from an instance of the specified WMI class on the specified CIM
+ /// session.
+ ///
+ ///
+ /// The type of the object to be created. Must be a default-constructable
+ /// reference type.
+ ///
+ ///
+ /// The CIM session to be queried.
+ ///
+ ///
+ /// A string containing the namespace to run the query against
+ ///
+ ///
+ /// A string containing the name of the WMI class from which to populate
+ /// the resultant array elements.
+ ///
+ ///
+ /// An array of new objects of type T if successful, null otherwise.
+ ///
+ ///
+ /// This method matches property and field names of type T with identically
+ /// named properties in the WMI class instance. The WMI property is converted
+ /// to the type of T's property or field.
+ ///
+ internal static T[] GetAll(CimSession session, string nameSpace, string wmiClassName) where T : class, new()
+ {
+ if (string.IsNullOrEmpty(wmiClassName))
+ throw new ArgumentException("String argument may not be null or empty", "wmiClassName");
+
+ var rv = new List();
+
+ try
+ {
+ var instances = session.QueryInstances(nameSpace, CIMHelper.WqlQueryAll(wmiClassName));
+
+ if (instances != null)
+ {
+ var type = typeof(T);
+ var binding = BindingFlags.Public | BindingFlags.Instance;
+
+ foreach (var instance in instances)
+ {
+ T objT = new T();
+
+ using (instance)
+ {
+ SetObjectDataMembers(objT, binding, instance);
+ }
+
+ rv.Add(objT);
+ }
+ }
+ }
+ catch (Exception /*ex*/)
+ {
+ // on any error we'll just fall through to the return below
+ }
+
+ return rv.ToArray();
+ }
+
+ ///
+ /// Retrieve an array of new objects of type T, whose properties and fields are
+ /// populated from an instance of the specified WMI class on the specified CIM
+ /// session.
+ ///
+ ///
+ /// The type of the object to be created. Must be a default-constructable
+ /// reference type.
+ ///
+ ///
+ /// The CIM session to be queried.
+ ///
+ ///
+ /// A string containing the name of the WMI class from which to populate
+ /// the resultant array elements.
+ ///
+ ///
+ /// An array of new objects of type T if successful, null otherwise.
+ ///
+ ///
+ /// This method matches property and field names of type T with identically
+ /// named properties in the WMI class instance. The WMI property is converted
+ /// to the type of T's property or field.
+ ///
+ internal static T[] GetAll(CimSession session, string wmiClassName) where T : class, new()
+ {
+ return GetAll(session, DefaultNamespace, wmiClassName);
+ }
+
+ internal static void SetObjectDataMember(object obj, BindingFlags binding, CimProperty cimProperty)
+ {
+ var type = obj.GetType();
+
+ var pi = type.GetProperty(cimProperty.Name, binding);
+
+ if (pi != null && pi.CanWrite)
+ {
+ pi.SetValue(obj, cimProperty.Value, null);
+ }
+ else
+ {
+ var fi = type.GetField(cimProperty.Name, binding);
+
+ if (fi != null && !fi.IsInitOnly)
+ {
+ fi.SetValue(obj, cimProperty.Value);
+ }
+ }
+ }
+
+ internal static void SetObjectDataMembers(object obj, BindingFlags binding, CimInstance instance)
+ {
+ foreach (var wmiProp in instance.CimInstanceProperties)
+ SetObjectDataMember(obj, binding, wmiProp);
+ }
+
+ ///
+ /// Escape any backslash (\) characters in a path with an additional
+ /// backslash, allowing the path to be used within a WMI query.
+ ///
+ ///
+ /// A string that may contain backslash characters.
+ ///
+ ///
+ /// A new string in which any backshlash characters have been "escaped"
+ /// by prefacing then with an additional backslash
+ ///
+ internal static string EscapePath(string path)
+ {
+ return string.Join(@"\\", path.Split('\\'));
+ }
+ }
+}
+
+namespace Extensions
+{
+ using Microsoft.PowerShell.Commands;
+
+ internal static class CIMExtensions
+ {
+ ///
+ /// An "overload" of the
+ /// .QueryInstances
+ /// method that takes only the query string as a parameter
+ ///
+ /// The CimSession to be queried
+ /// A string containing the query to be run
+ ///
+ /// An IEnumerable interface that can be used to enumerate the instances
+ ///
+ internal static IEnumerable QueryInstances(this CimSession session, string query)
+ {
+ return session.QueryInstances(CIMHelper.DefaultNamespace, CIMHelper.DefaultQueryDialect, query);
+ }
+
+ ///
+ /// An "overload" of the
+ /// .QueryInstances
+ /// method that takes only the namespace and query string as a parameters
+ ///
+ /// The CimSession to be queried
+ /// A string containing the namespace to run the query against
+ /// A string containing the query to be run
+ ///
+ /// An IEnumerable interface that can be used to enumerate the instances
+ ///
+ internal static IEnumerable QueryInstances(this CimSession session, string nameSpace, string query)
+ {
+ return session.QueryInstances(nameSpace, CIMHelper.DefaultQueryDialect, query);
+ }
+
+ ///
+ /// Execute a CIM query and return only the first intance in the result.
+ ///
+ /// The CimSesson to be queried
+ /// A string containing the namespace to run the query against
+ /// A string containing the query to be run
+ ///
+ /// A object
+ /// representing the first instance in a query result if successful, null
+ /// otherwise.
+ ///
+ internal static CimInstance QueryFirstInstance(this CimSession session, string nameSpace, string query)
+ {
+ try
+ {
+ var instances = session.QueryInstances(nameSpace, query);
+ var enumerator = instances.GetEnumerator();
+
+ if (enumerator.MoveNext())
+ return enumerator.Current;
+ }
+ catch (Exception /*ex*/)
+ {
+ // on any error, fall through to the null return below
+ }
+
+ return null;
+ }
+
+ ///
+ /// Execute a CIM query and return only the first intance in the result.
+ ///
+ /// The CimSesson to be queried
+ /// A string containing the query to be run
+ ///
+ /// A object
+ /// representing the first instance in a query result if successful, null
+ /// otherwise.
+ ///
+ internal static CimInstance QueryFirstInstance(this CimSession session, string query)
+ {
+ return session.QueryFirstInstance(CIMHelper.DefaultNamespace, query);
+ }
+
+ internal static T GetFirst(this CimSession session, string wmiClassName) where T : class, new()
+ {
+ return session.GetFirst(CIMHelper.DefaultNamespace, wmiClassName);
+ }
+
+ internal static T GetFirst(this CimSession session, string wmiNamespace, string wmiClassName) where T : class, new()
+ {
+ return CIMHelper.GetFirst(session, wmiNamespace, wmiClassName);
+ }
+
+ internal static T[] GetAll(this CimSession session, string wmiClassName) where T : class, new()
+ {
+ return Microsoft.PowerShell.Commands.CIMHelper.GetAll(session, wmiClassName);
+ }
+
+ internal static T[] GetAll(this CimSession session, string wmiNamespace, string wmiClassName) where T : class, new()
+ {
+ return Microsoft.PowerShell.Commands.CIMHelper.GetAll(session, wmiNamespace, wmiClassName);
+ }
+ }
+}
diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs
new file mode 100644
index 0000000000..0586e49ae4
--- /dev/null
+++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs
@@ -0,0 +1,5039 @@
+/********************************************************************++
+Copyright (c) Microsoft Corporation. All rights reserved.
+--********************************************************************/
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Reflection;
+using System.Linq.Expressions;
+using System.Management.Automation;
+
+using Microsoft.Management.Infrastructure;
+using Microsoft.Win32;
+
+namespace Microsoft.PowerShell.Commands
+{
+ using Extensions;
+
+ #region GetComputerInfoCommand cmdlet implementation
+ ///
+ /// The Get=ComputerInfo cmdlet gathers and reports information
+ /// about a computer.
+ ///
+ [Cmdlet(VerbsCommon.Get, "ComputerInfo")]
+ [Alias("gin")]
+ public class GetComputerInfoCommand : PSCmdlet
+ {
+ #region Inner Types
+ private class OSInfoGroup
+ {
+ public WmiOperatingSystem os;
+ public HotFix[] hotFixes;
+ public WmiPageFileUsage[] pageFileUsage;
+ public string halVersion;
+ public TimeSpan? upTime;
+ public RegWinNtCurrentVersion regCurVer;
+ }
+
+ private class SystemInfoGroup
+ {
+ public WmiBaseBoard baseboard;
+ public WmiBios bios;
+ public WmiComputerSystem computer;
+ public Processor[] processors;
+ public NetworkAdapter[] networkAdapters;
+ }
+
+ private class HyperVInfo
+ {
+ public bool? Present;
+ public bool? VMMonitorModeExtensions;
+ public bool? SecondLevelAddressTranslation;
+ public bool? VirtualizationFirmwareEnabled;
+ public bool? DataExecutionPreventionAvailable;
+ }
+
+ private class DeviceGuardInfo
+ {
+ public DeviceGuardSmartStatus status;
+ public DeviceGuard deviceGuard;
+ }
+
+ private class MiscInfoGroup
+ {
+ public UInt64? physicallyInstalledMemory;
+ public string timeZone;
+ public string logonServer;
+ public FirmwareType? firmwareType;
+ public PowerPlatformRole? powerPlatformRole;
+ public WmiKeyboard[] keyboards;
+ public HyperVInfo hyperV;
+ public ServerLevel? serverLevel;
+ public DeviceGuardInfo deviceGuard;
+ }
+ #endregion Inner Types
+
+ #region Static Data and Constants
+ private const string activity = "Get-ComputerInfo";
+ private const string localMachineName = "localhost";
+ #endregion Static Data and Constants
+
+ #region Instance Data
+ private string machineName = localMachineName; // we might need to have cmdlet work on another machine
+ private ProgressRecord progress = null;
+
+ ///
+ /// Collection of property names from the Property parameter,
+ /// including any names resulting from the expansion of wild-card
+ /// patterns given. This list will itself contain no wildcard patterns.
+ ///
+ private List namedProperties = null;
+ #endregion Instance Data
+
+ #region Parameters
+ ///
+ /// The Property parameter contains the names of properties to be retrieved.
+ /// If this parameter is given, the cmdlet returns a PSCustomObject
+ /// containing only the requested properties.
+ /// Wild-card patterns may be provided
+ ///
+ ///
+ ///
+ /// Any named properties that are not recognized are ignored. If no
+ /// recognized properties are provided the cmdlet returns an empty
+ /// PSCustomObject.
+ ///
+ ///
+ /// If a provided wild-card pattern contains only an asterisk ("*"),
+ /// the cmdlet will operate as if the parameter were not given at all
+ /// and will return a fully-populated ComputerInfo object.
+ ///
+ ///
+ [Parameter(Position = 0,
+ ValueFromPipeline = true,
+ ValueFromPipelineByPropertyName = true)]
+ public string[] Property { get; set; }
+ #endregion Parameters
+
+ #region Cmdlet Overrides
+ ///
+ /// Perform any first-stage processing
+ ///
+ protected override void BeginProcessing()
+ {
+ // if the Property parameter was given, determine the requested
+ // property names
+ if (Property != null && Property.Length > 0)
+ {
+ try
+ {
+ namedProperties = CollectPropertyNames(Property);
+ }
+ catch (WildcardPatternException ex)
+ {
+ WriteError(new ErrorRecord(ex, "WildcardPattern", ErrorCategory.InvalidArgument, this));
+ }
+ }
+ }
+
+ ///
+ /// Performs the cmdlet's work
+ ///
+ protected override void ProcessRecord()
+ {
+ // if the user provided property names but no matching properties
+ // were found, return an empty custom object
+ if (namedProperties != null && namedProperties.Count == 0)
+ {
+ WriteObject(new PSObject());
+ return;
+ }
+
+ MiscInfoGroup miscInfo = null;
+ var osInfo = new OSInfoGroup();
+ var systemInfo = new SystemInfoGroup();
+ var now = DateTime.Now;
+
+ using (var session = CimSession.Create(machineName))
+ {
+ UpdateProgress(ComputerInfoResources.LoadingOperationSystemInfo);
+
+ osInfo.os = session.GetFirst(CIMHelper.ClassNames.OperatingSystem);
+ osInfo.pageFileUsage = session.GetAll(CIMHelper.ClassNames.PageFileUsage);
+
+ if (osInfo.os != null)
+ {
+ osInfo.halVersion = GetHalVersion(session, osInfo.os.SystemDirectory);
+
+ if (osInfo.os.LastBootUpTime != null)
+ osInfo.upTime = now - osInfo.os.LastBootUpTime.Value;
+ }
+
+ UpdateProgress(ComputerInfoResources.LoadingHotPatchInfo);
+ osInfo.hotFixes = session.GetAll(CIMHelper.ClassNames.HotFix);
+
+ UpdateProgress(ComputerInfoResources.LoadingRegistryInfo);
+ osInfo.regCurVer = RegistryInfo.GetWinNtCurrentVersion();
+
+ UpdateProgress(ComputerInfoResources.LoadingBiosInfo);
+ systemInfo.bios = session.GetFirst(CIMHelper.ClassNames.Bios);
+
+ UpdateProgress(ComputerInfoResources.LoadingMotherboardInfo);
+ systemInfo.baseboard = session.GetFirst(CIMHelper.ClassNames.BaseBoard);
+
+ UpdateProgress(ComputerInfoResources.LoadingComputerInfo);
+ systemInfo.computer = session.GetFirst(CIMHelper.ClassNames.ComputerSystem);
+ miscInfo = GetOtherInfo(session);
+
+ UpdateProgress(ComputerInfoResources.LoadingProcessorInfo);
+ systemInfo.processors = GetProcessors(session);
+
+ UpdateProgress(ComputerInfoResources.LoadingNetworkAdapterInfo);
+ systemInfo.networkAdapters = GetNetworkAdapters(session);
+
+ UpdateProgress(null); // close the progress bar
+ } // end of using(CimSession...)
+
+ var infoOutput = CreateFullOutputObject(systemInfo, osInfo, miscInfo);
+
+ if (namedProperties != null)
+ {
+ //var output = CreateCustomOutputObject(namedProperties, systemInfo, osInfo, miscInfo);
+ var output = CreateCustomOutputObject(infoOutput, namedProperties);
+
+ WriteObject(output);
+ }
+ else
+ {
+ WriteObject(infoOutput);
+ }
+ }
+ #endregion Cmdlet Overrides
+
+ #region Private Methods
+ ///
+ /// Display progress
+ ///
+ ///
+ /// Text to be displayed in status bar
+ ///
+ private void UpdateProgress(string status)
+ {
+ if (progress != null)
+ {
+ progress.RecordType = ProgressRecordType.Completed;
+ WriteProgress(progress);
+ }
+
+ if (status != null)
+ {
+ progress = new ProgressRecord(0, activity, status);
+ WriteProgress(progress);
+ }
+ }
+
+ ///
+ /// Retrieves the version of the system's hal.dll.
+ ///
+ ///
+ /// A object
+ /// representing the CIM session to query.
+ ///
+ ///
+ /// Path to the system directory, which should contain the hal.dll file.
+ ///
+ private static string GetHalVersion(CimSession session, string systemDirectory)
+ {
+ string halVersion = null;
+
+ try
+ {
+ var halPath = CIMHelper.EscapePath(System.IO.Path.Combine(systemDirectory, "hal.dll"));
+ var query = string.Format("SELECT * FROM CIM_DataFile Where Name='{0}'", halPath);
+ var instance = session.QueryFirstInstance(query);
+
+ if (instance != null)
+ halVersion = instance.CimInstanceProperties["Version"].Value.ToString();
+ }
+ catch (Exception)
+ {
+ // On any error, fall through to the return
+ }
+
+ return halVersion;
+ }
+
+ ///
+ /// Create an array of object from values in
+ /// Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration instances.
+ ///
+ ///
+ /// A object representing
+ /// a CIM session.
+ ///
+ ///
+ /// An array of NetworkAdapter objects.
+ ///
+ ///
+ /// This method matches network adapters associated network adapter configurations.
+ /// The returned array contains entries only for matched adapter/configuration objects.
+ ///
+ private static NetworkAdapter[] GetNetworkAdapters(CimSession session)
+ {
+ var adaptersMsft = session.GetAll(CIMHelper.MicrosoftNetworkAdapterNamespace, CIMHelper.ClassNames.MicrosoftNetworkAdapter);
+ var adapters = session.GetAll(CIMHelper.ClassNames.NetworkAdapter);
+ var configs = session.GetAll(CIMHelper.ClassNames.NetworkAdapterConfiguration);
+
+ var list = new List();
+
+ if (adapters != null && configs != null)
+ {
+ var configDict = new Dictionary();
+
+ foreach (var config in configs)
+ {
+ if (config.Index != null)
+ configDict[config.Index.Value] = config;
+ }
+
+ if (configDict.Count > 0)
+ {
+ foreach (var adapter in adapters)
+ {
+ // Only include adapters that have a non-null connection status
+ // and a non-null index
+ if ( adapter.NetConnectionStatus != null
+ && adapter.Index != null)
+ {
+ if (configDict.ContainsKey(adapter.Index.Value))
+ {
+ var config = configDict[adapter.Index.Value];
+ var nwAdapter = new NetworkAdapter
+ {
+ Description = adapter.Description,
+ ConnectionID = adapter.NetConnectionID
+ };
+
+ var status = EnumConverter.Convert(adapter.NetConnectionStatus);
+ nwAdapter.ConnectionStatus = status == null ? NetConnectionStatus.Other
+ : status.Value;
+
+ if (nwAdapter.ConnectionStatus == NetConnectionStatus.Connected)
+ {
+ nwAdapter.DHCPEnabled = config.DHCPEnabled;
+ nwAdapter.DHCPServer = config.DHCPServer;
+ nwAdapter.IPAddresses = config.IPAddress;
+ }
+
+ list.Add(nwAdapter);
+ }
+ }
+ }
+ }
+ }
+
+ return list.ToArray();
+ }
+
+ ///
+ /// Create an array of objects, using data acquired
+ /// from WMI via the Win32_Processor class.
+ ///
+ ///
+ ///
+ private static Processor[] GetProcessors(CimSession session)
+ {
+ var processors = session.GetAll(CIMHelper.ClassNames.Processor);
+
+ if (processors != null)
+ {
+ var list = new List();
+
+ foreach (var processor in processors)
+ {
+ var proc = new Processor();
+
+ proc.AddressWidth = processor.AddressWidth;
+ proc.Architecture = EnumConverter.Convert(processor.Architecture);
+ proc.Availability = EnumConverter.Convert(processor.Availability);
+ proc.CpuStatus = EnumConverter.Convert(processor.CpuStatus);
+ proc.CurrentClockSpeed = processor.CurrentClockSpeed;
+ proc.DataWidth = processor.DataWidth;
+ proc.Description = processor.Description;
+ proc.Manufacturer = processor.Manufacturer;
+ proc.MaxClockSpeed = processor.MaxClockSpeed;
+ proc.Name = processor.Name;
+ proc.NumberOfCores = processor.NumberOfCores;
+ proc.NumberOfLogicalProcessors = processor.NumberOfLogicalProcessors;
+ proc.ProcessorID = processor.ProcessorId;
+ proc.ProcessorType = EnumConverter.Convert(processor.ProcessorType);
+ proc.Role = processor.Role;
+ proc.SocketDesignation = processor.SocketDesignation;
+ proc.Status = processor.Status;
+
+ list.Add(proc);
+ }
+
+ return list.ToArray();
+ }
+
+ return null;
+ }
+
+ private static bool CheckDeviceGuardLicense()
+ {
+#if !CORECLR
+ const string propertyName = "CodeIntegrity-AllowConfigurablePolicy";
+
+ try
+ {
+ int policy = 0;
+
+ if (Native.SLGetWindowsInformationDWORD(propertyName, out policy) == Native.S_OK
+ && policy == 1)
+ {
+ return true;
+ }
+ }
+ catch (Exception)
+ {
+ // if we fail to load the native dll or if the call fails
+ // catastrophically there's not much we can do except to
+ // consider there to be no license.
+ }
+#endif
+ return false;
+ }
+
+ ///
+ /// Retrieve information related to Device Guard
+ ///
+ ///
+ /// A object representing
+ /// a CIM session.
+ ///
+ ///
+ /// A object containing information related to
+ /// the Device Guard feature
+ ///
+ private static DeviceGuardInfo GetDeviceGuard(CimSession session)
+ {
+ DeviceGuard guard = null;
+ var status = DeviceGuardSmartStatus.Off;
+
+ if (CheckDeviceGuardLicense())
+ {
+ var wmiGuard = session.GetFirst(CIMHelper.DeviceGuardNamespace,
+ CIMHelper.ClassNames.DeviceGuard);
+
+ if (wmiGuard != null)
+ guard = wmiGuard.AsOutputType;
+ }
+
+ return new DeviceGuardInfo
+ {
+ status = status,
+ deviceGuard = guard
+ };
+ }
+
+ ///
+ /// A helper method used by GetHyperVisorInfo to retrieve a boolean
+ /// property value.
+ ///
+ private static bool? GetBooleanProperty(CimInstance instance, string propertyName)
+ {
+ if (instance != null)
+ {
+ try
+ {
+ var property = instance.CimInstanceProperties[propertyName];
+
+ if (property != null && property.Value != null)
+ return (bool)property.Value;
+ }
+ catch (Exception)
+ {
+ // just in case the cast fails
+ // fall through to the null return
+ }
+ }
+
+ return null;
+ }
+
+ ///
+ /// Retrieve information related to HyperVisor
+ ///
+ ///
+ /// A object representing
+ /// a CIM session.
+ ///
+ ///
+ /// A object containing information related to
+ /// HyperVisor
+ ///
+ private static HyperVInfo GetHyperVisorInfo(CimSession session)
+ {
+ HyperVInfo info = new HyperVInfo();
+ bool ok = false;
+ CimInstance instance = null;
+
+ using (instance = session.QueryFirstInstance(CIMHelper.WqlQueryAll(CIMHelper.ClassNames.ComputerSystem)))
+ {
+ if (instance != null)
+ {
+ info.Present = GetBooleanProperty(instance, "HypervisorPresent");
+ ok = true;
+ }
+ }
+
+ // don't bother checking requirements if the HyperV in present
+ // when the HyperV is present, the requirements values are misleading
+ if (ok && info.Present != null && info.Present.Value)
+ return info;
+
+ using (instance = session.QueryFirstInstance(CIMHelper.WqlQueryAll(CIMHelper.ClassNames.OperatingSystem)))
+ {
+ if (instance != null)
+ {
+ info.DataExecutionPreventionAvailable = GetBooleanProperty(instance, "DataExecutionPrevention_Available");
+ ok = true;
+ }
+ }
+
+ using (instance = session.QueryFirstInstance(CIMHelper.WqlQueryAll(CIMHelper.ClassNames.Processor)))
+ {
+ if (instance != null)
+ {
+ info.SecondLevelAddressTranslation = GetBooleanProperty(instance, "SecondLevelAddressTranslationExtensions");
+ info.VirtualizationFirmwareEnabled = GetBooleanProperty(instance, "VirtualizationFirmwareEnabled");
+ info.VMMonitorModeExtensions = GetBooleanProperty(instance, "VMMonitorModeExtensions");
+ ok = true;
+ }
+ }
+
+ return ok ? info : null;
+ }
+
+ ///
+ /// Retrieve miscellaneous system information
+ ///
+ ///
+ /// A object representing
+ /// a CIM session.
+ ///
+ ///
+ /// A object containing miscellaneous
+ /// system information
+ ///
+ private static MiscInfoGroup GetOtherInfo(CimSession session)
+ {
+ var rv = new MiscInfoGroup();
+
+ // get platform role
+ try
+ {
+ //TODO: Local machine only. Check for that?
+ uint powerRole = Native.PowerDeterminePlatformRoleEx(Native.POWER_PLATFORM_ROLE_V2);
+ if (powerRole >= (uint)PowerPlatformRole.MaximumEnumValue)
+ rv.powerPlatformRole = PowerPlatformRole.Unspecified;
+ else
+ rv.powerPlatformRole = EnumConverter.Convert((int)powerRole);
+ }
+ catch (Exception)
+ {
+ // probably failed to load the DLL with PowerDeterminePlatformRoleEx
+ // either way, move on
+ }
+
+ // get secure-boot info
+ //TODO: Local machine only? Check for that?
+ FirmwareType fwType = FirmwareType.Unknown;
+ if (Native.GetFirmwareType(ref fwType))
+ rv.firmwareType = fwType;
+
+ // get amount of memory physically installed
+ //TODO: Local machine only. Check for that?
+ UInt64 memory;
+ if (Native.GetPhysicallyInstalledSystemMemory(out memory))
+ rv.physicallyInstalledMemory = memory;
+
+
+ // get time zone
+ // we'll use .Net's TimeZoneInfo for now. systeminfo uses Caption from Win32_TimeZone
+ var tzi = TimeZoneInfo.Local;
+ if (tzi != null)
+ rv.timeZone = tzi.DisplayName;
+
+ rv.logonServer = RegistryInfo.GetLogonServer();
+
+ rv.keyboards = session.GetAll(CIMHelper.ClassNames.Keyboard);
+
+ rv.hyperV = GetHyperVisorInfo(session);
+
+ var serverLevels = RegistryInfo.GetServerLevels();
+ uint value;
+
+ if (serverLevels.TryGetValue("NanoServer", out value) && value == 1)
+ {
+ rv.serverLevel = ServerLevel.NanoServer;
+ }
+ else if (serverLevels.TryGetValue("ServerCore", out value) && value == 1)
+ {
+ rv.serverLevel = ServerLevel.ServerCore;
+
+ if (serverLevels.TryGetValue("Server-Gui-Mgmt", out value) && value == 1)
+ {
+ rv.serverLevel = ServerLevel.ServerCoreWithManagementTools;
+
+ if (serverLevels.TryGetValue("Server-Gui-Shell", out value) && value == 1)
+ rv.serverLevel = ServerLevel.FullServer;
+ }
+ }
+
+ rv.deviceGuard = GetDeviceGuard(session);
+
+ return rv;
+ }
+
+ ///
+ /// Create a new ComputerInfo object populated with the specified data objects.
+ ///
+ ///
+ /// A object containing system-related info
+ /// such as BIOS, mother-board, computer system, etc.
+ ///
+ ///
+ /// An object containing operating-system information.
+ ///
+ ///
+ /// A object containing other information to be reported.
+ ///
+ ///
+ /// A new ComputerInfo object to be output to PowerShell.
+ ///
+ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, OSInfoGroup osInfo, MiscInfoGroup otherInfo)
+ {
+ var output = new ComputerInfo();
+
+ var regCurVer = osInfo.regCurVer;
+ if (regCurVer != null)
+ {
+ output.WindowsBuildLabEx = regCurVer.BuildLabEx;
+ output.WindowsCurrentVersion = regCurVer.CurrentVersion;
+ output.WindowsEditionId = regCurVer.EditionId;
+ output.WindowsInstallationType = regCurVer.InstallationType;
+ output.WindowsInstallDateFromRegistry = regCurVer.InstallDate;
+ output.WindowsProductId = regCurVer.ProductId;
+ output.WindowsProductName = regCurVer.ProductName;
+ output.WindowsRegisteredOrganization = regCurVer.RegisteredOrganization;
+ output.WindowsRegisteredOwner = regCurVer.RegisteredOwner;
+ output.WindowsSystemRoot = regCurVer.SystemRoot;
+ }
+
+ var os = osInfo.os;
+ if (os != null)
+ {
+ output.OsName = os.Caption;
+ output.OsBootDevice = os.BootDevice;
+ output.OsBuildNumber = os.BuildNumber;
+ output.OsBuildType = os.BuildType;
+ output.OsCodeSet = os.CodeSet;
+ output.OsCountryCode = os.CountryCode;
+ output.OsCSDVersion = os.CSDVersion;
+ output.OsCurrentTimeZone = os.CurrentTimeZone;
+ output.OsDataExecutionPreventionAvailable = os.DataExecutionPrevention_Available;
+ output.OsDataExecutionPrevention32BitApplications = os.DataExecutionPrevention_32BitApplications;
+ output.OsDataExecutionPreventionDrivers = os.DataExecutionPrevention_Drivers;
+ output.OsDataExecutionPreventionSupportPolicy =
+ EnumConverter.Convert(os.DataExecutionPrevention_SupportPolicy);
+ output.OsDebug = os.Debug;
+
+ output.OsDistributed = os.Distributed;
+ output.OsEncryptionLevel = EnumConverter.Convert((int?)os.EncryptionLevel);
+ output.OsForegroundApplicationBoost = EnumConverter.Convert(os.ForegroundApplicationBoost);
+ output.OsTotalSwapSpaceSize = os.TotalSwapSpaceSize;
+ output.OsTotalVisibleMemorySize = os.TotalVisibleMemorySize;
+ output.OsFreePhysicalMemory = os.FreePhysicalMemory;
+ output.OsFreeSpaceInPagingFiles = os.FreeSpaceInPagingFiles;
+ output.OsTotalVirtualMemorySize = os.TotalVirtualMemorySize;
+ output.OsFreeVirtualMemory = os.FreeVirtualMemory;
+ if (os.TotalVirtualMemorySize != null && os.FreeVirtualMemory != null)
+ output.OsInUseVirtualMemory = os.TotalVirtualMemorySize - os.FreeVirtualMemory;
+ output.OsInstallDate = os.InstallDate;
+ output.OsLastBootUpTime = os.LastBootUpTime;
+ output.OsLocalDateTime = os.LocalDateTime;
+ output.OsLocaleID = os.Locale;
+ output.OsManufacturer = os.Manufacturer;
+ output.OsMaxNumberOfProcesses = os.MaxNumberOfProcesses;
+ output.OsMaxProcessMemorySize = os.MaxProcessMemorySize;
+ output.OsMuiLanguages = os.MUILanguages;
+ output.OsNumberOfLicensedUsers = os.NumberOfLicensedUsers;
+ output.OsNumberOfProcesses = os.NumberOfProcesses;
+ output.OsNumberOfUsers = os.NumberOfUsers;
+ output.OsOperatingSystemSKU = EnumConverter.Convert((int?)os.OperatingSystemSKU);
+ output.OsOrganization = os.Organization;
+ output.OsArchitecture = os.OSArchitecture;
+ output.OsLanguage = os.LanguageName;
+ output.OsProductSuites = os.ProductSuites;
+ output.OsOtherTypeDescription = os.OtherTypeDescription;
+ output.OsPAEEnabled = os.PAEEnabled;
+ output.OsPortableOperatingSystem = os.PortableOperatingSystem;
+ output.OsPrimary = os.Primary;
+ output.OsProductType = EnumConverter.Convert((int?)os.ProductType);
+ output.OsRegisteredUser = os.RegisteredUser;
+ output.OsSerialNumber = os.SerialNumber;
+ output.OsServicePackMajorVersion = os.ServicePackMajorVersion;
+ output.OsServicePackMinorVersion = os.ServicePackMinorVersion;
+ output.OsSizeStoredInPagingFiles = os.SizeStoredInPagingFiles;
+ output.OsStatus = os.Status;
+ output.OsSuites = os.Suites;
+ output.OsSystemDevice = os.SystemDevice;
+ output.OsSystemDirectory = os.SystemDirectory;
+ output.OsSystemDrive = os.SystemDrive;
+ output.OsType = EnumConverter.Convert(os.OSType);
+ output.OsVersion = os.Version;
+ output.OsWindowsDirectory = os.WindowsDirectory;
+
+ output.OsHardwareAbstractionLayer = osInfo.halVersion;
+ output.OsLocale = os.GetLocale();
+ output.OsUptime = osInfo.upTime;
+ output.OsHotFixes = osInfo.hotFixes;
+
+ var pageFileUsage = osInfo.pageFileUsage;
+ if (pageFileUsage != null)
+ {
+ output.OsPagingFiles = new string[pageFileUsage.Length];
+
+ for (int i=0; i < pageFileUsage.Length; i++)
+ output.OsPagingFiles[i] = pageFileUsage[i].Caption;
+ }
+ }
+
+ var bios = systemInfo.bios;
+ if (bios != null)
+ {
+ output.BiosCharacteristics = bios.BiosCharacteristics;
+ output.BiosBuildNumber = bios.BuildNumber;
+ output.BiosBIOSVersion = bios.BIOSVersion;
+ output.BiosCaption = bios.Caption;
+ output.BiosCodeSet = bios.CodeSet;
+ output.BiosCurrentLanguage = bios.CurrentLanguage;
+ output.BiosDescription = bios.Description;
+ output.BiosEmbeddedControllerMajorVersion = bios.EmbeddedControllerMajorVersion;
+ output.BiosEmbeddedControllerMinorVersion = bios.EmbeddedControllerMinorVersion;
+ output.BiosIdentificationCode = bios.IdentificationCode;
+ output.BiosInstallableLanguages = bios.InstallableLanguages;
+ output.BiosInstallDate = bios.InstallDate;
+ output.BiosLanguageEdition = bios.LanguageEdition;
+ output.BiosListOfLanguages = bios.ListOfLanguages;
+ output.BiosManufacturer = bios.Manufacturer;
+ output.BiosName = bios.Name;
+ output.BiosOtherTargetOS = bios.OtherTargetOS;
+ output.BiosPrimaryBIOS = bios.PrimaryBIOS;
+ output.BiosReleaseDate = bios.ReleaseDate;
+ output.BiosSeralNumber = bios.SerialNumber;
+ output.BiosSMBIOSBIOSVersion = bios.SMBIOSBIOSVersion;
+ output.BiosSMBIOSMajorVersion = bios.SMBIOSMajorVersion;
+ output.BiosSMBIOSMinorVersion = bios.SMBIOSMinorVersion;
+ output.BiosSMBIOSPresent = bios.SMBIOSPresent;
+ output.BiosSoftwareElementState = EnumConverter.Convert(bios.SoftwareElementState);
+ output.BiosStatus = bios.Status;
+ output.BiosSystemBiosMajorVersion = bios.SystemBiosMajorVersion;
+ output.BiosSystemBiosMinorVersion = bios.SystemBiosMinorVersion;
+ output.BiosTargetOperatingSystem = bios.TargetOperatingSystem;
+ output.BiosVersion = bios.Version;
+
+ if (otherInfo != null)
+ output.BiosFirmwareType = otherInfo.firmwareType;
+ }
+
+ var computer = systemInfo.computer;
+ if (computer != null)
+ {
+ output.CsAdminPasswordStatus = EnumConverter.Convert(computer.AdminPasswordStatus);
+ output.CsAutomaticManagedPagefile = computer.AutomaticManagedPagefile;
+ output.CsAutomaticResetBootOption = computer.AutomaticResetBootOption;
+ output.CsAutomaticResetCapability = computer.AutomaticResetCapability;
+ output.CsBootOptionOnLimit = EnumConverter.Convert(computer.BootOptionOnLimit);
+ output.CsBootOptionOnWatchDog = EnumConverter.Convert(computer.BootOptionOnWatchDog);
+ output.CsBootROMSupported = computer.BootROMSupported;
+ output.CsBootStatus = computer.BootStatus;
+ output.CsBootupState = computer.BootupState;
+ output.CsCaption = computer.Caption;
+ output.CsChassisBootupState = EnumConverter.Convert(computer.ChassisBootupState);
+ output.CsChassisSKUNumber = computer.ChassisSKUNumber;
+ output.CsCurrentTimeZone = computer.CurrentTimeZone;
+ output.CsDaylightInEffect = computer.DaylightInEffect;
+ output.CsDescription = computer.Description;
+ output.CsDNSHostName = computer.DNSHostName;
+ output.CsDomain = computer.Domain;
+ output.CsDomainRole = EnumConverter.Convert(computer.DomainRole);
+ output.CsEnableDaylightSavingsTime = computer.EnableDaylightSavingsTime;
+ output.CsFrontPanelResetStatus = EnumConverter.Convert(computer.FrontPanelResetStatus);
+ output.CsHypervisorPresent = computer.HypervisorPresent;
+ output.CsInfraredSupported = computer.InfraredSupported;
+ output.CsInitialLoadInfo = computer.InitialLoadInfo;
+ output.CsInstallDate = computer.InstallDate;
+ output.CsKeyboardPasswordStatus = EnumConverter.Convert(computer.KeyboardPasswordStatus);
+ output.CsLastLoadInfo = computer.LastLoadInfo;
+ output.CsManufacturer = computer.Manufacturer;
+ output.CsModel = computer.Model;
+ output.CsName = computer.Name;
+ output.CsNetworkAdapters = systemInfo.networkAdapters;
+ output.CsNetworkServerModeEnabled = computer.NetworkServerModeEnabled;
+ output.CsNumberOfLogicalProcessors = computer.NumberOfLogicalProcessors;
+ output.CsNumberOfProcessors = computer.NumberOfProcessors;
+ output.CsProcessors = systemInfo.processors;
+ output.CsOEMStringArray = computer.OEMStringArray;
+ output.CsPartOfDomain = computer.PartOfDomain;
+ output.CsPauseAfterReset = computer.PauseAfterReset;
+ output.CsPCSystemType = EnumConverter.Convert(computer.PCSystemType);
+ output.CsPCSystemTypeEx = EnumConverter.Convert(computer.PCSystemTypeEx);
+ output.CsPowerManagementCapabilities = computer.GetPowerManagementCapabilities();
+ output.CsPowerManagementSupported = computer.PowerManagementSupported;
+ output.CsPowerOnPasswordStatus = EnumConverter.Convert(computer.PowerOnPasswordStatus);
+ output.CsPowerState = EnumConverter.Convert(computer.PowerState);
+ output.CsPowerSupplyState = EnumConverter.Convert(computer.PowerSupplyState);
+ output.CsPrimaryOwnerContact = computer.PrimaryOwnerContact;
+ output.CsPrimaryOwnerName = computer.PrimaryOwnerName;
+ output.CsResetCapability = EnumConverter.Convert(computer.ResetCapability);
+ output.CsResetCount = computer.ResetCount;
+ output.CsResetLimit = computer.ResetLimit;
+ output.CsRoles = computer.Roles;
+ output.CsStatus = computer.Status;
+ output.CsSupportContactDescription = computer.SupportContactDescription;
+ output.CsSystemFamily = computer.SystemFamily;
+ output.CsSystemSKUNumber = computer.SystemSKUNumber;
+ output.CsSystemType = computer.SystemType;
+ output.CsThermalState = EnumConverter.Convert(computer.ThermalState);
+ output.CsTotalPhysicalMemory = computer.TotalPhysicalMemory;
+ output.CsUserName = computer.UserName;
+ output.CsWakeUpType = EnumConverter.Convert(computer.WakeUpType);
+ output.CsWorkgroup = computer.Workgroup;
+
+ if (otherInfo != null)
+ {
+ output.CsPhyicallyInstalledMemory = otherInfo.physicallyInstalledMemory;
+ }
+ }
+
+ if (otherInfo != null)
+ {
+ output.TimeZone = otherInfo.timeZone;
+ output.LogonServer = otherInfo.logonServer;
+ output.PowerPlatformRole = otherInfo.powerPlatformRole;
+
+ if (otherInfo.keyboards.Length > 0)
+ {
+ //TODO: handle multiple keyboards?
+ // there might be several keyboards found. For the moment
+ // we display info for only one
+
+ string layout = otherInfo.keyboards[0].Layout;
+ var culture = Conversion.MakeLocale(layout);
+
+ output.KeyboardLayout = culture == null ? layout : culture.Name;
+ }
+
+ if (otherInfo.hyperV != null)
+ {
+ output.HyperVisorPresent = otherInfo.hyperV.Present;
+ output.HyperVRequirementDataExecutionPreventionAvailable = otherInfo.hyperV.DataExecutionPreventionAvailable;
+ output.HyperVRequirementSecondLevelAddressTranslation = otherInfo.hyperV.SecondLevelAddressTranslation;
+ output.HyperVRequirementVirtualizationFirmwareEnabled = otherInfo.hyperV.VirtualizationFirmwareEnabled;
+ output.HyperVRequirementVMMonitorModeExtensions = otherInfo.hyperV.VMMonitorModeExtensions;
+ }
+
+ output.OsServerLevel = otherInfo.serverLevel;
+
+ var deviceGuardInfo = otherInfo.deviceGuard;
+ if (deviceGuardInfo != null)
+ {
+ output.DeviceGuardSmartStatus = deviceGuardInfo.status;
+
+ var deviceGuard = deviceGuardInfo.deviceGuard;
+ if (deviceGuard != null)
+ {
+ output.DeviceGuardRequiredSecurityProperties = deviceGuard.RequiredSecurityProperties;
+ output.DeviceGuardAvailableSecurityProperties = deviceGuard.AvailableSecurityProperties;
+ output.DeviceGuardSecurityServicesConfigured = deviceGuard.SecurityServicesConfigured;
+ output.DeviceGuardSecurityServicesRunning = deviceGuard.SecurityServicesRunning;
+ output.DeviceGuardCodeIntegrityPolicyEnforcementStatus = deviceGuard.CodeIntegrityPolicyEnforcementStatus;
+ output.DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus = deviceGuard.UserModeCodeIntegrityPolicyEnforcementStatus;
+ }
+ }
+ }
+
+ return output;
+ }
+
+ ///
+ /// Create a new PSObject, containing only those properties named in the
+ /// namedProperties parameter
+ ///
+ ///
+ /// A containing all the acquired system information
+ ///
+ ///
+ /// A list of property names to be included in the returned object
+ ///
+ ///
+ /// A new PSObject with the properties specified in the
+ /// parameter
+ ///
+ private static PSObject CreateCustomOutputObject(ComputerInfo info, List namedProperties)
+ {
+ var rv = new PSObject();
+
+ if (info != null && namedProperties != null && namedProperties.Count > 0)
+ {
+ // Walk the list of named properties, find a matching property in the
+ // info object, and create a new property on the results object
+ // with the associated value.
+ var type = info.GetType();
+
+ foreach (var propertyName in namedProperties)
+ {
+ var propInfo = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
+
+ if (propInfo != null)
+ {
+ object value = propInfo.GetValue(info);
+ rv.Properties.Add(new PSNoteProperty(propertyName, value));
+ }
+ }
+ }
+
+ return rv;
+ }
+
+ ///
+ /// Get the names of all properties. This is
+ /// part of the processes of validating property names provided by the user.
+ ///
+ ///
+ private static List GetComputerInfoPropertyNames()
+ {
+ var rv = new List();
+ var type = typeof(ComputerInfo);
+
+ foreach (var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
+ rv.Add(prop.Name);
+
+ return rv;
+ }
+
+ ///
+ /// Expand any wild-card patterns into known property names
+ ///
+ ///
+ /// List of known property names
+ ///
+ ///
+ /// The wild-card pattern used to perform globbing
+ ///
+ ///
+ private static List ExpandWildcardPropertyNames(List propertyNames, string pattern)
+ {
+ var rv = new List();
+
+ var wcp = new WildcardPattern(pattern, WildcardOptions.Compiled | WildcardOptions.IgnoreCase);
+
+ foreach (var name in propertyNames)
+ if (wcp.IsMatch(name))
+ rv.Add(name);
+
+ return rv;
+ }
+
+ ///
+ /// Produce a list of known, valid property names from property-name
+ /// parameters. These parameter may use wild-card patterns and may
+ /// contain invalid property names. This method expands wild-card
+ /// patterns and filter out any invalid property names.
+ ///
+ ///
+ ///
+ ///
+ private static List CollectPropertyNames(string[] requestedProperties)
+ {
+ // A quick scan through the requested properties to make sure
+ // we want to use user-specified properties
+ foreach (var name in requestedProperties)
+ {
+ if (WildcardPattern.ContainsWildcardCharacters(name))
+ {
+ if (name == "*")
+ return null; // we treat a wild-card pattern of "*" as if no properties were named
+ }
+ }
+
+ var availableProperties = GetComputerInfoPropertyNames();
+ var rv = new List();
+
+ // walk though the requested properties again, expanding and collecting property names
+ foreach (var name in requestedProperties)
+ {
+ if (WildcardPattern.ContainsWildcardCharacters(name))
+ {
+ foreach (var matchedName in ExpandWildcardPropertyNames(availableProperties, name))
+ if (!rv.Contains(matchedName))
+ rv.Add(matchedName);
+ }
+ else
+ {
+ // find a matching property name via case-insensitive string comparison
+ Predicate pred = (s) =>
+ {
+ return string.Compare(s,
+ name,
+ StringComparison.CurrentCultureIgnoreCase) == 0;
+ };
+ var propertyName = availableProperties.Find(pred);
+
+ // add the properly-cased name, if found, to the list
+ if (propertyName != null && !rv.Contains(propertyName))
+ rv.Add(propertyName);
+ }
+ }
+
+ return rv;
+ }
+ #endregion Private Methods
+ }
+ #endregion GetComputerInfoCommand cmdlet implementation
+
+ #region Helper classes
+ internal static class Conversion
+ {
+ ///
+ /// Attempt to convert a string representation of a base-16 value
+ /// into an integer.
+ ///
+ ///
+ /// A string containing the text to be parsed.
+ ///
+ ///
+ /// An integer into which the parsed value is stored. If the string
+ /// cannot be converted, this parameter is set to 0.
+ ///
+ ///
+ /// Returns true if the conversion was successful, false otherwise.
+ ///
+ ///
+ /// The hexString parameter must contain a hexadecimal value, with no
+ /// base-indication prefix. For example, the string "0409" will be
+ /// parsed into the base-10 integer value 1033, while the string "0x0409"
+ /// will fail to parse due to the "0x" base-indication prefix.
+ ///
+ internal static bool TryParseHex(string hexString, out uint value)
+ {
+ try
+ {
+ value = Convert.ToUInt32(hexString, 16);
+ return true;
+ }
+ catch (Exception)
+ {
+ value = 0;
+ return false;
+ }
+ }
+
+ public static string LocaleIdToLocaleName(uint localeID)
+ {
+ // CoreCLR's System.Globalization.Culture does not appear to have a constructor
+ // that accepts an integer LocalID (LCID) value, so we'll PInvoke native code
+ // to get a locale name from an LCID value
+
+ var sbName = new System.Text.StringBuilder(Native.LOCALE_NAME_MAX_LENGTH);
+ var len = Native.LCIDToLocaleName(localeID, sbName, sbName.Capacity, 0);
+
+ if (len > 0 && sbName.Length > 0)
+ return sbName.ToString();
+
+ return null;
+ }
+
+ ///
+ /// Attempt to create a
+ /// object from a locale string as retrieved from WMI.
+ ///
+ ///
+ /// A string containing WMI's notion (usually) of a locale.
+ ///
+ ///
+ /// A CultureInfo object if successful, null otherwise.
+ ///
+ ///
+ /// This method first tries to convert the string to a hex value
+ /// and get the CultureInfo object from that value.
+ /// Failing that it attempts to retrieve the CultureInfo object
+ /// using the locale string as passed.
+ ///
+ internal static System.Globalization.CultureInfo MakeLocale(string locale)
+ {
+ System.Globalization.CultureInfo culture = null;
+
+ if (locale != null)
+ {
+ try
+ {
+ uint localeNum;
+
+ if (TryParseHex(locale, out localeNum))
+ {
+ string localeName = LocaleIdToLocaleName(localeNum);
+
+ if (localeName != null)
+ culture = new System.Globalization.CultureInfo(localeName);
+ }
+
+ if (culture == null)
+ {
+ // either the TryParseHex failed, or the LocaleIdToLocaleName
+ // failed, so we'll try using the original string
+ culture = new System.Globalization.CultureInfo(locale);
+ }
+ }
+ catch (Exception/* ex*/)
+ {
+ culture = null;
+ }
+ }
+
+ return culture;
+ }
+
+ ///
+ /// Convert a Unix time, expressed in seconds, to a .
+ ///
+ /// Number of seconds since the Unix epoch.
+ ///
+ /// A DateTime object representing the date and time represented by the
+ /// parameter.
+ ///
+ internal static DateTime UnixSecondsToDateTime(long seconds)
+ {
+#if false // requires .NET 4.6 or higher
+ return DateTimeOffset.FromUnixTimeSeconds(seconds).DateTime;
+#else
+ const int DaysPerYear = 365;
+ const int DaysPer4Years = DaysPerYear * 4 + 1;
+ const int DaysPer100Years = DaysPer4Years * 25 - 1;
+ const int DaysPer400Years = DaysPer100Years * 4 + 1;
+ const int DaysTo1970 = DaysPer400Years * 4 + DaysPer100Years * 3 + DaysPer4Years * 17 + DaysPerYear;
+ const long UnixEpochTicks = TimeSpan.TicksPerDay * DaysTo1970;
+
+ long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks;
+
+ return new DateTimeOffset(ticks, TimeSpan.Zero).DateTime;
+#endif
+ }
+ }
+
+ ///
+ /// The EnumConverter class contains a method
+ /// for converting an integer to a nullable enum of the type specified
+ /// in T.
+ ///
+ ///
+ /// The type of enum to be the destination of the conversion.
+ ///
+ internal static class EnumConverter where T : struct, IConvertible
+ {
+ // The converter object
+ private static readonly Func convert = MakeConverter();
+
+ ///
+ /// Convert an integer to a Nullable enum of type T
+ ///
+ ///
+ /// The integer value to be converted to the specified enum type.
+ ///
+ ///
+ /// A Nullable enum object. If the value
+ /// is convertable to a valid enum value, the returned object's
+ /// value will contain the converted value, otherwise the returned
+ /// object will be null.
+ ///
+ internal static T? Convert(int? value)
+ {
+ try
+ {
+ if (value.HasValue)
+ return convert(value.Value);
+ }
+ catch (Exception)
+ {
+ // nothing should go wrong, but just in case
+ // fall through to the return null below
+ }
+
+ return (T?)null;
+ }
+
+ ///
+ /// Create a converter using Linq Expression classes.
+ ///
+ ///
+ /// A generic Func{} object to convert an int to the specified enum type.
+ ///
+ static internal Func MakeConverter()
+ {
+ var param = Expression.Parameter(typeof(int));
+ var method = Expression.Lambda>
+ (Expression.Convert(param, typeof(T?)), param);
+
+ return method.Compile();
+ }
+ }
+
+ internal static class RegistryInfo
+ {
+ public static Dictionary GetServerLevels()
+ {
+ const string keyPath = @"Software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels";
+
+ var rv = new Dictionary();
+
+ using (var key = Registry.LocalMachine.OpenSubKey(keyPath))
+ {
+ if (key != null)
+ {
+ foreach (var name in key.GetValueNames())
+ {
+ if (key.GetValueKind(name) == RegistryValueKind.DWord)
+ {
+ var val = key.GetValue(name);
+ rv.Add(name, Convert.ToUInt32(val));
+ }
+ }
+ }
+ }
+
+ return rv;
+ }
+
+ public static string GetLogonServer()
+ {
+ const string valueName = "LOGONSERVER";
+ const string keyPath = "Volatile Environment";
+
+ using (var key = Registry.CurrentUser.OpenSubKey(keyPath))
+ {
+ if (key != null)
+ return (string)key.GetValue(valueName, null);
+ }
+
+ return null;
+ }
+
+ public static RegWinNtCurrentVersion GetWinNtCurrentVersion()
+ {
+ using (var key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion"))
+ {
+ if (key != null)
+ {
+ object temp = key.GetValue("InstallDate");
+
+ return new RegWinNtCurrentVersion()
+ {
+ BuildLabEx = (string)key.GetValue("BuildLabEx"),
+ CurrentVersion = (string)key.GetValue("CurrentVersion"),
+ EditionId = (string)key.GetValue("EditionID"),
+ InstallationType = (string)key.GetValue("InstallationType"),
+ InstallDate = temp == null ? (DateTime?)null
+ : Conversion.UnixSecondsToDateTime((long)(int)temp),
+ ProductId = (string)key.GetValue("ProductId"),
+ ProductName = (string)key.GetValue("ProductName"),
+ RegisteredOrganization = (string)key.GetValue("RegisteredOrganization"),
+ RegisteredOwner = (string)key.GetValue("RegisteredOwner"),
+ SystemRoot = (string)key.GetValue("SystemRoot")
+ };
+ }
+ }
+
+ return null;
+ }
+ }
+ #endregion Helper classes
+
+ #region Intermediate WMI classes
+ ///
+ /// Base class for some of the other Intermediate WMI classes,
+ /// providing some shared methods.
+ ///
+ internal abstract class WmiClassBase
+ {
+ ///
+ /// Get a language name from a language identifier.
+ ///
+ ///
+ /// A nullable integer containing the language ID for the desired language.
+ ///
+ ///
+ /// A string containing the display name of the language identified by
+ /// the language parameter. If the language parameter is null or has a
+ /// value that is not a valid language ID, the method returns null.
+ ///
+ protected static string GetLanguageName(UInt32? language)
+ {
+ if (language != null)
+ return Conversion.LocaleIdToLocaleName(language.Value);
+
+ return null;
+ }
+ }
+#pragma warning disable 649 // fields and properties in these class are assigned dynamically
+ internal class WmiBaseBoard
+ {
+ public string Caption;
+ public string[] ConfigOptions;
+ public float? Depth;
+ public string Description;
+ public float? Height;
+ public bool? HostingBoard;
+ public bool? HotSwappable;
+ public DateTime? InstallDate;
+ public string Manufacturer;
+ public string Model;
+ public string Name;
+ public string OtherIdentifyingInfo;
+ public string PartNumber;
+ public bool? PoweredOn;
+ public string Product;
+ public bool? Removable;
+ public bool? Replaceable;
+ public string RequirementsDescription;
+ public bool? RequiresDaughterBoard;
+ public string SerialNumber;
+ public string SKU;
+ public string SlotLayout;
+ public bool? SpecialRequirements;
+ public string Status;
+ public string Tag;
+ public string Version;
+ public float? Weight;
+ public float? Width;
+ }
+
+ internal class WmiBios : WmiClassBase
+ {
+ public UInt16[] BiosCharacteristics;
+ public string[] BIOSVersion;
+ public string BuildNumber;
+ public string Caption;
+ public string CodeSet;
+ public string CurrentLanguage;
+ public string Description;
+ public byte? EmbeddedControllerMajorVersion;
+ public byte? EmbeddedControllerMinorVersion;
+ public string IdentificationCode;
+ public UInt16? InstallableLanguages;
+ public DateTime? InstallDate;
+ public string LanguageEdition;
+ public string[] ListOfLanguages;
+ public string Manufacturer;
+ public string Name;
+ public string OtherTargetOS;
+ public bool? PrimaryBIOS;
+ public DateTime? ReleaseDate;
+ public string SerialNumber;
+ public string SMBIOSBIOSVersion;
+ public UInt16? SMBIOSMajorVersion;
+ public UInt16? SMBIOSMinorVersion;
+ public bool? SMBIOSPresent;
+ public UInt16? SoftwareElementState;
+ public string Status;
+ public byte? SystemBiosMajorVersion;
+ public byte? SystemBiosMinorVersion;
+ public UInt16? TargetOperatingSystem;
+ public string Version;
+ }
+
+ internal class WmiComputerSystem
+ {
+ public UInt16? AdminPasswordStatus;
+ public bool? AutomaticManagedPagefile;
+ public bool? AutomaticResetBootOption;
+ public bool? AutomaticResetCapability;
+ public UInt16? BootOptionOnLimit;
+ public UInt16? BootOptionOnWatchDog;
+ public bool? BootROMSupported;
+ public string BootupState;
+ public UInt16[] BootStatus;
+ public string Caption;
+ public UInt16? ChassisBootupState;
+ public string ChassisSKUNumber;
+ public Int16? CurrentTimeZone;
+ public bool? DaylightInEffect;
+ public string Description;
+ public string DNSHostName;
+ public string Domain;
+ public UInt16? DomainRole;
+ public bool? EnableDaylightSavingsTime;
+ public UInt16? FrontPanelResetStatus;
+ public bool? HypervisorPresent;
+ public bool? InfraredSupported;
+ public string InitialLoadInfo;
+ public DateTime? InstallDate;
+ public UInt16? KeyboardPasswordStatus;
+ public string LastLoadInfo;
+ public string Manufacturer;
+ public string Model;
+ public string Name;
+ public bool? NetworkServerModeEnabled;
+ public UInt32? NumberOfLogicalProcessors;
+ public UInt32? NumberOfProcessors;
+ public string[] OEMStringArray;
+ public bool? PartOfDomain;
+ public Int64? PauseAfterReset;
+ public UInt16? PCSystemType;
+ public UInt16? PCSystemTypeEx;
+ public UInt16[] PowerManagementCapabilities;
+ public bool? PowerManagementSupported;
+ public UInt16? PowerOnPasswordStatus;
+ public UInt16? PowerState;
+ public UInt16? PowerSupplyState;
+ public string PrimaryOwnerContact;
+ public string PrimaryOwnerName;
+ public UInt16? ResetCapability;
+ public Int16? ResetCount;
+ public Int16? ResetLimit;
+ public string[] Roles;
+ public string Status;
+ public string[] SupportContactDescription;
+ public string SystemFamily;
+ public string SystemSKUNumber;
+ public string SystemType;
+ public UInt16? ThermalState;
+ public UInt64? TotalPhysicalMemory;
+ public string UserName;
+ public UInt16? WakeUpType;
+ public string Workgroup;
+
+ public PowerManagementCapabilities[] GetPowerManagementCapabilities()
+ {
+ if (PowerManagementCapabilities != null)
+ {
+ var list = new List();
+
+ foreach (var cap in PowerManagementCapabilities)
+ {
+ var val = EnumConverter.Convert(cap);
+
+ if (val != null)
+ list.Add(val.Value);
+ }
+
+ return list.ToArray();
+ }
+
+ return null;
+ }
+ }
+
+ internal class WmiDeviceGuard
+ {
+ public UInt32[] AvailableSecurityProperties;
+ public UInt32? CodeIntegrityPolicyEnforcementStatus;
+ public UInt32? UsermodeCodeIntegrityPolicyEnforcementStatus;
+ public UInt32[] RequiredSecurityProperties;
+ public UInt32[] SecurityServicesConfigured;
+ public UInt32[] SecurityServicesRunning;
+ public UInt32? VirtualizationBasedSecurityStatus;
+
+ public DeviceGuard AsOutputType
+ {
+ get
+ {
+ var guard = new DeviceGuard();
+
+ var status = EnumConverter.Convert((int?)VirtualizationBasedSecurityStatus);
+ if (status != null && status != DeviceGuardSmartStatus.Off)
+ {
+ var listHardware = new List();
+ for (int i=0; i < RequiredSecurityProperties.Length; i++)
+ {
+ var temp = EnumConverter.Convert((int?)RequiredSecurityProperties[i]);
+
+ if (temp != null)
+ listHardware.Add(temp.Value);
+ }
+ guard.RequiredSecurityProperties = listHardware.ToArray();
+
+ listHardware.Clear();
+ for (int i=0; i < AvailableSecurityProperties.Length; i++)
+ {
+ var temp = EnumConverter.Convert((int?)AvailableSecurityProperties[i]);
+
+ if (temp != null)
+ listHardware.Add(temp.Value);
+ }
+ guard.AvailableSecurityProperties = listHardware.ToArray();
+
+ var listSoftware = new List();
+ for (int i=0; i < SecurityServicesConfigured.Length; i++)
+ {
+ var temp = EnumConverter.Convert((int?)SecurityServicesConfigured[i]);
+
+ if (temp != null)
+ listSoftware.Add(temp.Value);
+ }
+ guard.SecurityServicesConfigured = listSoftware.ToArray();
+
+ listSoftware.Clear();
+ for (int i=0; i < SecurityServicesRunning.Length; i++)
+ {
+ var temp = EnumConverter.Convert((int?)SecurityServicesRunning[i]);
+
+ if (temp != null)
+ listSoftware.Add(temp.Value);
+ }
+ guard.SecurityServicesRunning = listSoftware.ToArray();
+ }
+
+ var configCIStatus = EnumConverter.Convert((int?)CodeIntegrityPolicyEnforcementStatus);
+ var userModeCIStatus = EnumConverter.Convert((int?)UsermodeCodeIntegrityPolicyEnforcementStatus);
+ if (configCIStatus != null && configCIStatus != DeviceGuardConfigCodeIntegrityStatus.Off)
+ {
+ guard.CodeIntegrityPolicyEnforcementStatus = configCIStatus;
+ guard.UserModeCodeIntegrityPolicyEnforcementStatus = userModeCIStatus;
+ }
+
+ return guard;
+ }
+ }
+ }
+
+ internal class WmiKeyboard
+ {
+ public UInt16? Availability;
+ public string Caption;
+ public UInt32? ConfigManagerErrorCode;
+ public bool? ConfigManagerUserConfig;
+ public string Description;
+ public string DeviceID;
+ public bool? ErrorCleared;
+ public string ErrorDescription;
+ public DateTime? InstallDate;
+ public bool? IsLocked;
+ public UInt32? LastErrorCode;
+ public string Layout;
+ public string Name;
+ public UInt16? NumberOfFunctionKeys;
+ public UInt16? Password;
+ public string PNPDeviceID;
+ public UInt16[] PowerManagementCapabilities;
+ public bool? PowerManagementSupported;
+ public string Status;
+ public UInt16? StatusInfo;
+ public string SystemCreationClassName;
+ public string SystemName;
+ }
+
+ internal class WMiLogicalMemory
+ {
+ //TODO: fill this in!!!
+ public UInt32? TotalPhysicalMemory;
+ }
+
+ internal class WmiMsftNetAdapter
+ {
+ public string Caption;
+ public string Description;
+ public DateTime? InstallDate;
+ public string Name;
+ public string Status;
+ public UInt16? Availability;
+ public UInt32? ConfigManagerErrorCode;
+ public bool? ConfigManagerUserConfig;
+ public string DeviceID;
+ public bool? ErrorCleared;
+ public string ErrorDescription;
+ public UInt32? LastErrorCode;
+ public string PNPDeviceID;
+ public UInt16[] PowerManagementCapabilities;
+ public bool? PowerManagementSupported;
+ public UInt16? StatusInfo;
+ public string SystemCreationClassName;
+ public string SystemName;
+ public UInt64? Speed;
+ public UInt64? MaxSpeed;
+ public UInt64? RequestedSpeed;
+ public UInt16? UsageRestriction;
+ public UInt16? PortType;
+ public string OtherPortType;
+ public string OtherNetworkPortType;
+ public UInt16? PortNumber;
+ public UInt16? LinkTechnology;
+ public string OtherLinkTechnology;
+ public string PermanentAddress;
+ public string[] NetworkAddresses;
+ public bool? FullDuplex;
+ public bool? AutoSense;
+ public UInt64? SupportedMaximumTransmissionUnit;
+ public UInt64? ActiveMaximumTransmissionUnit;
+ public string InterfaceDescription;
+ public string InterfaceName;
+ public UInt64? NetLuid;
+ public string InterfaceGuid;
+ public UInt32? InterfaceIndex;
+ public string DeviceName;
+ public UInt32? NetLuidIndex;
+ public bool? Virtual;
+ public bool? Hidden;
+ public bool? NotUserRemovable;
+ public bool? IMFilter;
+ public UInt32? InterfaceType;
+ public bool? HardwareInterface;
+ public bool? WdmInterface;
+ public bool? EndPointInterface;
+ public bool? iSCSIInterface;
+ public UInt32? State;
+ public UInt32? NdisMedium;
+ public UInt32? NdisPhysicalMedium;
+ public UInt32? InterfaceOperationalStatus;
+ public bool? OperationalStatusDownDefaultPortNotAuthenticated;
+ public bool? OperationalStatusDownMediaDisconnected;
+ public bool? OperationalStatusDownInterfacePaused;
+ public bool? OperationalStatusDownLowPowerState;
+ public UInt32? InterfaceAdminStatus;
+ public UInt32? MediaConnectState;
+ public UInt32? MtuSize;
+ public UInt16? VlanID;
+ public UInt64? TransmitLinkSpeed;
+ public UInt64? ReceiveLinkSpeed;
+ public bool? PromiscuousMode;
+ public bool? DeviceWakeUpEnable;
+ public bool? ConnectorPresent;
+ public UInt32? MediaDuplexState;
+ public string DriverDate;
+ public UInt64? DriverDateData;
+ public string DriverVersionString;
+ public string DriverName;
+ public string DriverDescription;
+ public UInt16? MajorDriverVersion;
+ public UInt16? MinorDriverVersion;
+ public byte? DriverMajorNdisVersion;
+ public byte? DriverMinorNdisVersion;
+ public string PnPDeviceID;
+ public string DriverProvider;
+ public string ComponentID;
+ public UInt32[] LowerLayerInterfaceIndices;
+ public UInt32[] HigherLayerInterfaceIndices;
+ public bool? AdminLocked;
+ }
+
+ internal class WmiNetworkAdapter
+ {
+ public string AdapterType;
+ public UInt16? AdapterTypeID;
+ public bool? AutoSense;
+ public UInt16? Availability;
+ public string Caption;
+ public UInt32? ConfigManagerErrorCode;
+ public bool? ConfigManagerUserConfig;
+ public string Description;
+ public string DeviceID;
+ public bool? ErrorCleared;
+ public string ErrorDescription;
+ public string GUID;
+ public UInt32? Index;
+ public DateTime? InstallDate;
+ public bool? Installed;
+ public UInt32? InterfaceIndex;
+ public UInt32? LastErrorCode;
+ public string MACAddress;
+ public string Manufacturer;
+ public UInt32? MaxNumberControlled;
+ public UInt64? MaxSpeed;
+ public string Name;
+ public string NetConnectionID;
+ public UInt16? NetConnectionStatus;
+ public bool? NetEnabled;
+ public string[] NetworkAddresses;
+ public string PermanentAddress;
+ public bool? PhysicalAdapter;
+ public string PNPDeviceID;
+ public UInt16[] PowerManagementCapabilities;
+ public bool? PowerManagementSupported;
+ public string ProductName;
+ public string ServiceName;
+ public UInt64? Speed;
+ public string Status;
+ public UInt16? StatusInfo;
+ public string SystemCreationClassName;
+ public string SystemName;
+ public DateTime? TimeOfLastReset;
+ }
+
+ internal class WmiNetworkAdapterConfiguration
+ {
+ public bool? ArpAlwaysSourceRoute;
+ public bool? ArpUseEtherSNAP;
+ public string Caption;
+ public string DatabasePath;
+ public bool? DeadGWDetectEnabled;
+ public string[] DefaultIPGateway;
+ public byte? DefaultTOS;
+ public byte? DefaultTTL;
+ public string Description;
+ public bool? DHCPEnabled;
+ public DateTime? DHCPLeaseExpires;
+ public DateTime? DHCPLeaseObtained;
+ public string DHCPServer;
+ public string DNSDomain;
+ public string[] DNSDomainSuffixSearchOrder;
+ public bool? DNSEnabledForWINSResolution;
+ public string DNSHostName;
+ public string[] DNSServerSearchOrder;
+ public bool? DomainDNSRegistrationEnabled;
+ public UInt32? ForwardBufferMemory;
+ public bool? FullDNSRegistrationEnabled;
+ public UInt16[] GatewayCostMetric;
+ public byte? IGMPLevel;
+ public UInt32? Index;
+ public UInt32? InterfaceIndex;
+ public string[] IPAddress;
+ public UInt32? IPConnectionMetric;
+ public bool? IPEnabled;
+ public bool? IPFilterSecurityEnabled;
+ public bool? IPPortSecurityEnabled;
+ public string[] IPSecPermitIPProtocols;
+ public string[] IPSecPermitTCPPorts;
+ public string[] IPSecPermitUDPPorts;
+ public string[] IPSubnet;
+ public bool? IPUseZeroBroadcast;
+ public string IPXAddress;
+ public bool? IPXEnabled;
+ public UInt32[] IPXFrameType;
+ public UInt32? IPXMediaType;
+ public string[] IPXNetworkNumber;
+ public string IPXVirtualNetNumber;
+ public UInt32? KeepAliveInterval;
+ public UInt32? KeepAliveTime;
+ public string MACAddress;
+ public UInt32? MTU;
+ public UInt32? NumForwardPackets;
+ public bool? PMTUBHDetectEnabled;
+ public bool? PMTUDiscoveryEnabled;
+ public string ServiceName;
+ public string SettingID;
+ public UInt32? TcpipNetbiosOptions;
+ public UInt32? TcpMaxConnectRetransmissions;
+ public UInt32? TcpMaxDataRetransmissions;
+ public UInt32? TcpNumConnections;
+ public bool? TcpUseRFC1122UrgentPointer;
+ public UInt16? TcpWindowSize;
+ public bool? WINSEnableLMHostsLookup;
+ public string WINSHostLookupFile;
+ public string WINSPrimaryServer;
+ public string WINSScopeID;
+ public string WINSSecondaryServer;
+ }
+
+ internal class WmiOperatingSystem : WmiClassBase
+ {
+ #region Fields
+ public string BootDevice;
+ public string BuildNumber;
+ public string BuildType;
+ public string Caption;
+ public string CodeSet;
+ public string CountryCode;
+ public string CSDVersion;
+ public string CSName;
+ public Int16? CurrentTimeZone;
+ public bool? DataExecutionPrevention_Available;
+ public bool? DataExecutionPrevention_32BitApplications;
+ public bool? DataExecutionPrevention_Drivers;
+ public byte? DataExecutionPrevention_SupportPolicy;
+ public bool? Debug;
+ public string Description;
+ public bool? Distributed;
+ public UInt32? EncryptionLevel;
+ public byte? ForegroundApplicationBoost;
+ public UInt64? FreePhysicalMemory;
+ public UInt64? FreeSpaceInPagingFiles;
+ public UInt64? FreeVirtualMemory;
+ public DateTime? InstallDate;
+ public DateTime? LastBootUpTime;
+ public DateTime? LocalDateTime;
+ public string Locale;
+ public string Manufacturer;
+ public UInt32? MaxNumberOfProcesses;
+ public UInt64? MaxProcessMemorySize;
+ public string[] MUILanguages;
+ public string Name;
+ public UInt32? NumberOfLicensedUsers;
+ public UInt32? NumberOfProcesses;
+ public UInt32? NumberOfUsers;
+ public UInt32? OperatingSystemSKU;
+ public string Organization;
+ public string OSArchitecture;
+ public UInt32? OSLanguage;
+ public UInt32? OSProductSuite;
+ public UInt16? OSType;
+ public string OtherTypeDescription;
+ public bool? PAEEnabled;
+ public bool? PortableOperatingSystem;
+ public bool? Primary;
+ public UInt32? ProductType;
+ public string RegisteredUser;
+ public string SerialNumber;
+ public UInt16? ServicePackMajorVersion;
+ public UInt16? ServicePackMinorVersion;
+ public UInt64? SizeStoredInPagingFiles;
+ public string Status;
+ public UInt32? SuiteMask;
+ public string SystemDevice;
+ public string SystemDirectory;
+ public string SystemDrive;
+ public UInt64? TotalSwapSpaceSize;
+ public UInt64? TotalVirtualMemorySize;
+ public UInt64? TotalVisibleMemorySize;
+ public string Version;
+ public string WindowsDirectory;
+ #endregion Fields
+
+ #region Public Properties
+ public string LanguageName
+ {
+ get { return GetLanguageName(OSLanguage); }
+ }
+
+ public OSProductSuite[] ProductSuites
+ {
+ get { return MakeProductSuites(OSProductSuite); }
+ }
+
+ public OSProductSuite[] Suites
+ {
+ get { return MakeProductSuites(SuiteMask); }
+ }
+ #endregion Public Properties
+
+ #region Public Methods
+ public string GetLocale()
+ {
+ System.Globalization.CultureInfo culture = null;
+
+ if (Locale != null)
+ culture = Conversion.MakeLocale(Locale);
+
+ return culture == null ? null : culture.Name;
+ }
+ #endregion Public Methods
+
+ #region Private Methods
+ private OSProductSuite[] MakeProductSuites(UInt32? suiteMask)
+ {
+ if (suiteMask == null)
+ return null;
+
+ var mask = suiteMask.Value;
+ var list = new List();
+
+ foreach (OSProductSuite suite in Enum.GetValues(typeof(OSProductSuite)))
+ if ((mask & (UInt32)suite) != 0)
+ list.Add(suite);
+
+ return list.ToArray();
+ }
+ #endregion Private Methods
+ }
+
+ internal class WmiPageFileUsage
+ {
+ public UInt32? AllocatedBaseSize;
+ public string Caption;
+ public UInt32? CurrentUsage;
+ public string Description;
+ public DateTime? InstallDate;
+ public string Name;
+ public UInt32? PeakUsage;
+ public string Status;
+ public bool? TempPageFile;
+ }
+
+ internal class WmiProcessor
+ {
+ public UInt16? AddressWidth;
+ public UInt16? Architecture;
+ public string AssetTag;
+ public UInt16? Availability;
+ public string Caption;
+ public UInt32? Characteristics;
+ public UInt32? ConfigManagerErrorCode;
+ public bool? ConfigManagerUserConfig;
+ public UInt16? CpuStatus;
+ public UInt32? CurrentClockSpeed;
+ public UInt16? CurrentVoltage;
+ public UInt16? DataWidth;
+ public string Description;
+ public string DeviceID;
+ public bool? ErrorCleared;
+ public string ErrorDescription;
+ public UInt32? ExtClock;
+ public UInt16? Family;
+ public DateTime? InstallDate;
+ public UInt32? L2CacheSize;
+ public UInt32? L2CacheSpeed;
+ public UInt32? L3CacheSize;
+ public UInt32? L3CacheSpeed;
+ public UInt32? LastErrorCode;
+ public UInt16? Level;
+ public UInt16? LoadPercentage;
+ public string Manufacturer;
+ public UInt32? MaxClockSpeed;
+ public string Name;
+ public UInt32? NumberOfCores;
+ public UInt32? NumberOfEnabledCore;
+ public UInt32? NumberOfLogicalProcessors;
+ public string OtherFamilyDescription;
+ public string PartNumber;
+ public string PNPDeviceID;
+ public UInt16[] PowerManagementCapabilities;
+ public bool? PowerManagementSupported;
+ public string ProcessorId;
+ public UInt16? ProcessorType;
+ public UInt16? Revision;
+ public string Role;
+ public bool? SecondLevelAddressTranslationExtensions;
+ public string SerialNumber;
+ public string SocketDesignation;
+ public string Status;
+ public UInt16? StatusInfo;
+ public string Stepping;
+ public string SystemName;
+ public UInt32? ThreadCount;
+ public string UniqueId;
+ public UInt16? UpgradeMethod;
+ public string Version;
+ public bool? VirtualizationFirmwareEnabled;
+ public bool? VMMonitorModeExtensions;
+ public UInt32? VoltageCaps;
+ }
+
+#pragma warning restore 649
+ #endregion Intermediate WMI classes
+
+ #region Other Imtermediate classes
+ internal class RegWinNtCurrentVersion
+ {
+ public string BuildLabEx;
+ public string CurrentVersion;
+ public string EditionId;
+ public string InstallationType;
+ public DateTime? InstallDate;
+ public string ProductId;
+ public string ProductName;
+ public string RegisteredOrganization;
+ public string RegisteredOwner;
+ public string SystemRoot;
+ }
+ #endregion Other Intermediage classes
+
+ #region Output components
+ #region Classes comprising the output object
+ ///
+ /// Provides information about Device Guard
+ ///
+ public class DeviceGuard
+ {
+ ///
+ /// Array of required security properties
+ ///
+ public DeviceGuardHardwareSecure[] RequiredSecurityProperties { get; internal set; }
+ ///
+ /// Array of available security properties
+ ///
+ public DeviceGuardHardwareSecure[] AvailableSecurityProperties { get; internal set; }
+ ///
+ /// Indicates which security services have been configured
+ ///
+ public DeviceGuardSoftwareSecure[] SecurityServicesConfigured { get; internal set; }
+ ///
+ /// Indicates which security services are running
+ ///
+ public DeviceGuardSoftwareSecure[] SecurityServicesRunning;
+ ///
+ /// Indicates the status of the Device Guard Code Integrity policy
+ ///
+ public DeviceGuardConfigCodeIntegrityStatus? CodeIntegrityPolicyEnforcementStatus;
+ ///
+ /// Indicates the status of the Device Guard user mode Code Integrity policy
+ ///
+ public DeviceGuardConfigCodeIntegrityStatus? UserModeCodeIntegrityPolicyEnforcementStatus;
+ }
+
+ ///
+ /// Describes a Quick-Fix Engineering update
+ ///
+ public class HotFix
+ {
+ ///
+ /// Unique identifier associated with a particular update.
+ ///
+ public string HotFixID { get; internal set; }
+ ///
+ /// Description of the update
+ ///
+ public string Description { get; internal set; }
+ ///
+ /// String containing the date that the update was installed
+ ///
+ public string InstalledOn { get; internal set; }
+ ///
+ /// Additional comments that relate to the update
+ ///
+ public string FixComments { get; internal set; }
+ }
+
+ ///
+ /// Provides information about a network adapter
+ ///
+ public class NetworkAdapter
+ {
+ ///
+ /// Description of the network adapter
+ ///
+ public string Description { get; internal set; }
+ ///
+ /// Name of the network connection as it appears in the Network
+ /// Connections Control Panel program
+ ///
+ public string ConnectionID { get; internal set; }
+ ///
+ /// Indicates whether the DHCP server automatically assigns an IP address
+ /// to the computer system when establishing a network connection
+ ///
+ public bool? DHCPEnabled { get; internal set; }
+ ///
+ /// IP Address of the DHCP server
+ ///
+ public string DHCPServer { get; internal set; }
+ ///
+ /// State of the network adapter connection to the network
+ ///
+ public NetConnectionStatus ConnectionStatus { get; internal set; }
+ ///
+ /// Array of all of the IP addresses associated with the current network adapter.
+ ///
+ public string[] IPAddresses { get; internal set; }
+ }
+
+ ///
+ /// Describes a processor on the computer
+ ///
+ public class Processor
+ {
+ ///
+ /// Name of the processor
+ ///
+ public string Name { get; internal set; }
+ ///
+ /// Name of the processor manufacturer
+ ///
+ public string Manufacturer { get; internal set; }
+ ///
+ /// Description of the processor
+ ///
+ public string Description { get; internal set; }
+ ///
+ /// Processor architecture used by the platform
+ ///
+ public CpuArchitecture? Architecture { get; internal set; }
+ ///
+ /// Address width of the processor
+ ///
+ public UInt16? AddressWidth { get; internal set; }
+ ///
+ /// Data width of the processor
+ ///
+ public UInt16? DataWidth { get; internal set; }
+ ///
+ /// Maximum speed of the processor, in MHz
+ ///
+ public UInt32? MaxClockSpeed { get; internal set; }
+ ///
+ /// Current speed of the processor, in MHz
+ ///
+ public UInt32? CurrentClockSpeed { get; internal set; }
+ ///
+ /// Number of cores for the current instance of the processor.
+ ///
+ ///
+ /// A core is a physical processor on the integrated circuit
+ ///
+ public UInt32? NumberOfCores { get; internal set; }
+ ///
+ /// Number of logical processors for the current instance of the processor.
+ ///
+ ///
+ /// For processors capable of hyperthreading, this value includes only the
+ /// processors which have hyperthreading enabled
+ ///
+ public UInt32? NumberOfLogicalProcessors { get; internal set; }
+ ///
+ /// Processor information that describes the processor features.
+ ///
+ ///
+ /// For an x86 class CPU, the field format depends on the processor support
+ /// of the CPUID instruction. If the instruction is supported, the property
+ /// contains 2 (two) DWORD formatted values. The first is an offset of 08h-0Bh,
+ /// which is the EAX value that a CPUID instruction returns with input EAX set
+ /// to 1. The second is an offset of 0Ch-0Fh, which is the EDX value that the
+ /// instruction returns. Only the first two bytes of the property are significant
+ /// and contain the contents of the DX register at CPU reset—all others are set
+ /// to 0 (zero), and the contents are in DWORD format
+ ///
+ public string ProcessorID { get; internal set; }
+ ///
+ /// Type of chip socket used on the circuit
+ ///
+ public string SocketDesignation { get; internal set; }
+ ///
+ /// Primary function of the processor
+ ///
+ public ProcessorType? ProcessorType { get; internal set; }
+ ///
+ /// Role of the processor
+ ///
+ public string Role { get; internal set; }
+ ///
+ /// Current status of the processor
+ ///
+ public string Status { get; internal set; }
+ ///
+ /// Current status of the processor.
+ /// Status changes indicate processor usage, but not the physical
+ /// condition of the processor
+ ///
+ public CpuStatus? CpuStatus { get; internal set; }
+ ///
+ /// Availability and status of the processor
+ ///
+ public CpuAvailability? Availability { get; internal set; }
+ }
+
+ ///
+ /// The ComputerInfo class is output to the PowerShell pipeline.
+ ///
+ public class ComputerInfo
+ {
+ #region Registry
+ ///
+ /// Windows build lab information, from the Windows Registry.
+ ///
+ public string WindowsBuildLabEx { get; internal set; }
+
+ ///
+ /// Windows version number, from the Windows Registry.
+ ///
+ public string WindowsCurrentVersion { get; internal set; }
+
+ ///
+ /// Windows edition, from the Windows Registry.
+ ///
+ public string WindowsEditionId { get; internal set; }
+
+ ///
+ /// Windows installation type, from the Windows Registry.
+ ///
+ public string WindowsInstallationType { get; internal set; }
+
+ ///
+ /// The data Windows was installed, from the Windows Registry.
+ ///
+ public DateTime? WindowsInstallDateFromRegistry { get; internal set; }
+
+ ///
+ /// The Windows product ID, from the Windows Registry.
+ ///
+ public string WindowsProductId { get; internal set; }
+
+ ///
+ /// The Windows product name, from the Windows Registry.
+ ///
+ public string WindowsProductName { get; internal set; }
+
+ ///
+ /// Name of the organization that this installation of Windows is registered to, from the Windows Registry.
+ ///
+ public string WindowsRegisteredOrganization { get; internal set; }
+
+ ///
+ /// Name of the registered owner of this installation of Windows, from the Windows Registry.
+ ///
+ public string WindowsRegisteredOwner { get; internal set; }
+
+ ///
+ /// Path to the operating system's root directory, from the Windows Registry.
+ ///
+ public string WindowsSystemRoot { get; internal set; }
+ #endregion Registry
+
+ #region BIOS
+ ///
+ /// Array of BIOS characteristics supported by the system as defined by
+ /// the System Management BIOS Reference Specification
+ ///
+ public UInt16[] BiosCharacteristics { get; internal set; }
+
+ ///
+ /// Array of the complete system BIOS information. In many computers
+ /// there can be several version strings that are stored in the registry
+ /// and represent the system BIOS information
+ ///
+ public string[] BiosBIOSVersion { get; internal set; }
+
+ ///
+ /// Internal identifier for this compilation of the BIOS firmware
+ ///
+ public string BiosBuildNumber { get; internal set; }
+
+ ///
+ /// Short description of the BIOS.
+ ///
+ public string BiosCaption { get; internal set; }
+
+ ///
+ /// Code set used by the BIOS
+ ///
+ public string BiosCodeSet { get; internal set; }
+
+ ///
+ /// Name of the current BIOS language
+ ///
+ public string BiosCurrentLanguage { get; internal set; }
+
+ ///
+ /// Description of the BIOS
+ ///
+ public string BiosDescription { get; internal set; }
+
+ ///
+ /// Major version of the embedded controller firmware
+ ///
+ public Int16? BiosEmbeddedControllerMajorVersion { get; internal set; }
+
+ ///
+ /// Minor version of the embedded controller firmware
+ ///
+ public Int16? BiosEmbeddedControllerMinorVersion { get; internal set; }
+
+ ///
+ /// Firmware type of the local computer.
+ ///
+ ///
+ /// This is acquired via the GetFirmwareType Windows API function
+ ///
+ public FirmwareType? BiosFirmwareType { get; internal set; }
+
+ ///
+ /// Manufacturer's identifier for this software element.
+ /// Often this will be a stock keeping unit (SKU) or a part number
+ ///
+ public string BiosIdentificationCode { get; internal set; }
+
+ ///
+ /// Number of languages available for installation on this system.
+ /// Language may determine properties such as the need for Unicode and bidirectional text
+ ///
+ public UInt16? BiosInstallableLanguages {get; internal set; }
+
+ ///
+ /// Date and time the object was installed.
+ ///
+ //TODO: do we want this? On my system this is null
+ public DateTime? BiosInstallDate { get; internal set; }
+
+ ///
+ /// Language edition of the BIOS firmware.
+ /// The language codes defined in ISO 639 should be used.
+ /// Where the software element represents a multilingual or international
+ /// version of a product, the string "multilingual" should be used
+ ///
+ public string BiosLanguageEdition { get; internal set; }
+
+ ///
+ /// Array of names of available BIOS-installable languages
+ ///
+ public string[] BiosListOfLanguages { get; internal set; }
+
+ ///
+ /// Manufacturer of the BIOS
+ ///
+ public string BiosManufacturer { get; internal set; }
+
+ ///
+ /// Name used to identify the BIOS
+ ///
+ public string BiosName { get; internal set; }
+
+ ///
+ /// Records the manufacturer and operating system type for the BIOS when
+ /// the BiosTargetOperatingSystem property has a value of 1 (Other).
+ /// When TargetOperatingSystem has a value of 1, BiosOtherTargetOS must
+ /// have a nonnull value. For all other values of BiosTargetOperatingSystem,
+ /// BiosOtherTargetOS is NULL
+ ///
+ public string BiosOtherTargetOS { get; internal set; }
+
+ ///
+ /// If true, this is the primary BIOS of the computer system
+ ///
+ public bool? BiosPrimaryBIOS { get; internal set; }
+
+ ///
+ /// Release date of the Windows BIOS
+ ///
+ public DateTime? BiosReleaseDate { get; internal set; }
+
+ ///
+ /// Assigned serial number of the BIOS
+ ///
+ public string BiosSeralNumber { get; internal set; }
+
+ ///
+ /// BIOS version as reported by SMBIOS
+ ///
+ public string BiosSMBIOSBIOSVersion { get; internal set; }
+
+ ///
+ /// SMBIOS major version number. This property is null if SMBIOS is not found
+ ///
+ public UInt16? BiosSMBIOSMajorVersion { get; internal set; }
+
+ ///
+ /// SMBIOS minor version number. This property is null if SMBIOS is not found
+ ///
+ public UInt16? BiosSMBIOSMinorVersion { get; internal set; }
+
+ ///
+ /// If true, the SMBIOS is available on this computer system
+ ///
+ public bool? BiosSMBIOSPresent { get; internal set; }
+
+ ///
+ /// State of a BIOS software element
+ ///
+ public SoftwareElementState? BiosSoftwareElementState { get; internal set; }
+
+ ///
+ /// Status of the BIOS
+ ///
+ public string BiosStatus { get; internal set; }
+
+ ///
+ /// Major elease of the System BIOS
+ ///
+ public UInt16? BiosSystemBiosMajorVersion { get; internal set; }
+
+ ///
+ /// Minor release of the System BIOS
+ ///
+ public UInt16? BiosSystemBiosMinorVersion { get; internal set; }
+
+ ///
+ /// Target operating system
+ ///
+ public UInt16? BiosTargetOperatingSystem { get; internal set; }
+
+ ///
+ /// Version of the BIOS.
+ /// This string is created by the BIOS manufacturer
+ ///
+ public string BiosVersion { get; internal set; }
+ #endregion BIOS
+
+ #region Computer System
+ ///
+ /// System hardware security settings for administrator password status
+ ///
+ //public AdminPasswordStatus? CsAdminPasswordStatus { get; internal set; }
+ public HardwareSecurity? CsAdminPasswordStatus { get; internal set; }
+
+ ///
+ /// If true, the system manages the page file
+ ///
+ public bool? CsAutomaticManagedPagefile { get; internal set; }
+
+ ///
+ /// If True, the automatic reset boot option is enabled
+ ///
+ public bool? CsAutomaticResetBootOption { get; internal set; }
+
+ ///
+ /// If True, the automatic reset is enabled
+ ///
+ public bool? CsAutomaticResetCapability { get; internal set; }
+
+ ///
+ /// Boot option limit is ON. Identifies the system action when the
+ /// CsResetLimit value is reached
+ ///
+ public BootOptionAction? CsBootOptionOnLimit { get; internal set; }
+
+ ///
+ /// Type of reboot action after the time on the watchdog timer is elapsed
+ ///
+ public BootOptionAction? CsBootOptionOnWatchDog { get; internal set; }
+
+ ///
+ /// If true, indicates whether a boot ROM is supported
+ ///
+ public bool? CsBootROMSupported { get; internal set; }
+
+ ///
+ /// Status and Additional Data fields that identify the boot status
+ ///
+ public UInt16[] CsBootStatus { get; internal set; }
+
+ ///
+ /// System is started. Fail-safe boot bypasses the user startup files—also called SafeBoot
+ ///
+ public string CsBootupState { get; internal set; }
+
+ ///
+ /// The name of this computer
+ ///
+ public string CsCaption { get; internal set; } //TODO: remove this? Same as CsName???
+
+ ///
+ /// Boot up state of the chassis
+ ///
+ //public ChassisBootupState? CsChassisBootupState { get; internal set; }
+ public SystemElementState? CsChassisBootupState { get; internal set; }
+
+ ///
+ /// The chassis or enclosure SKU number as a string
+ ///
+ public string CsChassisSKUNumber { get; internal set; }
+
+ ///
+ /// Amount of time the unitary computer system is offset from Coordinated
+ /// Universal Time (UTC).
+ ///
+ public Int16? CsCurrentTimeZone { get; internal set; }
+
+ ///
+ /// If True, the daylight savings mode is ON
+ ///
+ public bool? CsDaylightInEffect { get; internal set; }
+
+ ///
+ /// Description of the computer system
+ ///
+ public string CsDescription { get; internal set; }
+
+ ///
+ /// Name of local computer according to the domain name server
+ ///
+ public string CsDNSHostName { get; internal set; }
+
+ ///
+ /// Name of the domain to which a computer belongs.
+ ///
+ ///
+ /// If the computer is not part of a domain, then the name of the workgroup is returned
+ ///
+ public string CsDomain { get; internal set; }
+
+ ///
+ /// Role of a computer in an assigned domain workgroup. A domain workgroup
+ /// is a collection of computers on the same network. For example,
+ /// a DomainRole property may show that a computer is a member workstation
+ ///
+ public DomainRole? CsDomainRole { get; internal set; }
+
+ ///
+ /// Enables daylight savings time on a computer. A value of True indicates
+ /// that the system time changes to an hour ahead or behind when DST starts
+ /// or ends. A value of False indicates that the system time does not change
+ /// to an hour ahead or behind when DST starts or ends. A value of NULL
+ /// indicates that the DST status is unknown on a system.
+ ///
+ public bool? CsEnableDaylightSavingsTime { get; internal set; }
+
+ ///
+ /// Hardware security setting for the reset button on a computer
+ ///
+ //public FrontPanelResetStatus? CsFrontPanelResetStatus { get; internal set; }
+ public HardwareSecurity? CsFrontPanelResetStatus { get; internal set; }
+
+ ///
+ /// If True, a hypervisor is present
+ ///
+ public bool? CsHypervisorPresent { get; internal set; }
+
+ ///
+ /// If True, an infrared port exists on a computer system
+ ///
+ public bool? CsInfraredSupported { get; internal set; }
+
+ ///
+ /// Data required to find the initial load device or boot service to request that the operating system start up
+ ///
+ public string CsInitialLoadInfo { get; internal set; }
+
+ ///
+ /// Object is installed. An object does not need a value to indicate that it is installed
+ ///
+ public DateTime? CsInstallDate { get; internal set; }
+
+ ///
+ /// System hardware security setting for Keyboard Password Status
+ ///
+ //public KeyboardPasswordStatus? CsKeyboardPasswordStatus { get; internal set; }
+ public HardwareSecurity? CsKeyboardPasswordStatus { get; internal set; }
+
+ ///
+ /// Array entry of the CsInitialLoadInfo property that contains the data
+ /// to start the loaded operating system
+ ///
+ public string CsLastLoadInfo { get; internal set; }
+
+ ///
+ /// Name of the computer manufacturer
+ ///
+ public string CsManufacturer { get; internal set; }
+
+ ///
+ /// Product name that a manufacturer gives to a computer
+ ///
+ public string CsModel { get; internal set; }
+
+ ///
+ /// Key of a CIM_System instance in an enterprise environment
+ ///
+ public string CsName { get; internal set; } //TODO: get rid of this? Is this about CIM rather than about the computer?
+
+ ///
+ /// An array of objects describing any
+ /// network adapters on the system.
+ ///
+ public NetworkAdapter[] CsNetworkAdapters { get; internal set; }
+
+ ///
+ /// If True, the network Server Mode is enabled
+ ///
+ public bool? CsNetworkServerModeEnabled { get; internal set; }
+
+ ///
+ /// Number of logical processors available on the computer
+ ///
+ public UInt32? CsNumberOfLogicalProcessors { get; internal set; }
+
+ ///
+ /// Number of physical processors currently available on a system.
+ ///
+ ///
+ /// This is the number of enabled processors for a system, which
+ /// does not include the disabled processors. If a computer system
+ /// has two physical processors each containing two logical processors,
+ /// then the value of CsNumberOfProcessors is 2 and CsNumberOfLogicalProcessors
+ /// is 4. The processors may be multicore or they may be hyperthreading processors
+ ///
+ public UInt32? CsNumberOfProcessors { get; internal set; }
+
+ ///
+ /// Array of objects describing each processor on the system.
+ ///
+ public Processor[] CsProcessors { get; internal set; }
+
+ ///
+ /// Array of free-form strings that an OEM defines.
+ /// For example, an OEM defines the part numbers for system reference
+ /// documents, manufacturer contact information, and so on
+ ///
+ public string[] CsOEMStringArray { get; internal set; }
+
+ ///
+ /// If True, the computer is part of a domain.
+ /// If the value is NULL, the computer is not in a domain or the status is unknown
+ ///
+ public bool? CsPartOfDomain { get; internal set; }
+
+ ///
+ /// Time delay before a reboot is initiated, in milliseconds.
+ /// It is used after a system power cycle, local or remote system reset,
+ /// and automatic system reset. A value of –1 (minus one) indicates that
+ /// the pause value is unknown
+ ///
+ public Int64? CsPauseAfterReset { get; internal set; }
+
+ ///
+ /// Type of the computer in use, such as laptop, desktop, or tablet
+ ///
+ public PCSystemType? CsPCSystemType { get; internal set; }
+
+ ///
+ /// Type of the computer in use, such as laptop, desktop, or tablet.
+ ///
+ public PCSystemTypeEx? CsPCSystemTypeEx { get; internal set; }
+
+ ///
+ /// Array of the specific power-related capabilities of a logical device
+ ///
+ public PowerManagementCapabilities[] CsPowerManagementCapabilities { get; internal set; }
+
+ ///
+ /// If True, device can be power-managed, for example, a device can be
+ /// put into suspend mode, and so on.
+ ///
+ ///
+ /// This property does not indicate that power management features are
+ /// enabled currently, but it does indicate that the logical device is
+ /// capable of power management
+ ///
+ public bool? CsPowerManagementSupported { get; internal set; }
+
+ ///
+ /// System hardware security setting for Power-On Password Status
+ ///
+ //public PowerOnPasswordStatus? CsPowerOnPasswordStatus { get; internal set; }
+ public HardwareSecurity? CsPowerOnPasswordStatus { get; internal set; }
+
+ ///
+ /// Current power state of a computer and its associated operating system.
+ ///
+ public PowerState? CsPowerState { get; internal set; }
+
+ ///
+ /// State of the power supply or supplies when last booted
+ ///
+ //public PowerSupplyState? CsPowerSupplyState { get; internal set; }
+ public SystemElementState? CsPowerSupplyState { get; internal set; }
+
+ ///
+ /// Contact information for the primary system owner.
+ /// For example, phone number, email address, and so on
+ ///
+ public string CsPrimaryOwnerContact { get; internal set; }
+
+ ///
+ /// Name of the primary system owner
+ ///
+ public string CsPrimaryOwnerName { get; internal set; }
+
+ ///
+ /// Indicates if the computer system can be resut.
+ ///
+ public ResetCapability? CsResetCapability { get; internal set; }
+
+ ///
+ /// Number of automatic resets since the last reset.
+ /// A value of –1 (minus one) indicates that the count is unknown
+ ///
+ public Int16? CsResetCount { get; internal set; }
+
+ ///
+ /// Number of consecutive times a system reset is attempted.
+ /// A value of –1 (minus one) indicates that the limit is unknown
+ ///
+ public Int16? CsResetLimit { get; internal set; }
+
+ ///
+ /// Array that specifies the roles of a system in the information
+ /// technology environment
+ ///
+ public string[] CsRoles { get; internal set; }
+
+ ///
+ /// Statis pf the computer system
+ ///
+ public string CsStatus { get; internal set; }
+
+ ///
+ /// Array of the support contact information for the Windows operating system
+ ///
+ public string[] CsSupportContactDescription { get; internal set; }
+
+ ///
+ /// The family to which a particular computer belongs.
+ /// A family refers to a set of computers that are similar but not
+ /// identical from a hardware or software point of view
+ ///
+ public string CsSystemFamily { get; internal set; }
+
+ ///
+ /// Identifies a particular computer configuration for sale.
+ /// It is sometimes also called a product ID or purchase order number
+ ///
+ public string CsSystemSKUNumber { get; internal set; }
+
+ ///
+ /// System running on the Windows-based computer
+ ///
+ public string CsSystemType { get; internal set; }
+
+ ///
+ /// Thermal state of the system when last booted
+ ///
+ //public ThermalState? CsThermalState { get; internal set; }
+ public SystemElementState? CsThermalState { get; internal set; }
+
+ ///
+ /// Total size of physical memory.
+ ///
+ ///
+ /// Be aware that, under some circumstances, this property may not
+ /// return an accurate value for the physical memory. For example,
+ /// it is not accurate if the BIOS is using some of the physical memory
+ ///
+ public UInt64? CsTotalPhysicalMemory { get; internal set; }
+
+ ///
+ /// Size of physically installed memory, as reported by the Windows API
+ /// function GetPhysicallyInstalledSystemMemory
+ ///
+ public UInt64? CsPhyicallyInstalledMemory { get; internal set; }
+
+ ///
+ /// Name of a user that is logged on currently.
+ ///
+ ///
+ /// In a terminal services session, CsUserName is the name of the user
+ /// that is logged on to the console—not the user logged on during the
+ /// terminal service session
+ ///
+ public string CsUserName { get; internal set; }
+
+ ///
+ /// Event that causes the system to power up
+ ///
+ public WakeUpType? CsWakeUpType { get; internal set; }
+
+ ///
+ /// Name of the workgroup for this computer
+ ///
+ public string CsWorkgroup { get; internal set; }
+ #endregion Computer System
+
+ #region Operating System
+ ///
+ /// Name of the operating system
+ ///
+ public string OsName { get; internal set; }
+
+ ///
+ /// Type of operating system
+ ///
+ public OSType? OsType { get; internal set; }
+
+ ///
+ /// SKU number for the operating system
+ ///
+ public OperatingSystemSKU? OsOperatingSystemSKU { get; internal set; }
+
+ ///
+ /// Version number of the operating system
+ ///
+ public string OsVersion { get; internal set; }
+
+ ///
+ /// String that indicates the latest service pack installed on a computer.
+ /// If no service pack is installed, the string is NULL
+ ///
+ public string OsCSDVersion { get; internal set; }
+
+ ///
+ /// Build number of the operating system
+ ///
+ public string OsBuildNumber { get; internal set; }
+
+ ///
+ /// Array of objects containing information about
+ /// any Quick-Fix Enginnering patches (Hot Fixes) applied to the operating
+ /// system
+ ///
+ public HotFix[] OsHotFixes { get; internal set; }
+
+ ///
+ /// Name of the disk drive from which the Windows operating system starts
+ ///
+ public string OsBootDevice { get; internal set; }
+
+ ///
+ /// Physical disk partition on which the operating system is installed
+ ///
+ public string OsSystemDevice { get; internal set; }
+
+ ///
+ /// System directory of the operating system
+ ///
+ public string OsSystemDirectory { get; internal set; }
+
+ ///
+ /// Letter of the disk drive on which the operating system resides
+ ///
+ public string OsSystemDrive { get; internal set; }
+
+ ///
+ /// Windows directory of the operating system
+ ///
+ public string OsWindowsDirectory { get; internal set; }
+
+ ///
+ /// Code for the country/region that an operating system uses
+ ///
+ ///
+ /// Values are based on international phone dialing prefixes—also
+ /// referred to as IBM country/region codes
+ ///
+ public string OsCountryCode { get; internal set; }
+
+ ///
+ /// Number, in minutes, an operating system is offset from Greenwich
+ /// mean time (GMT). The number is positive, negative, or zero
+ ///
+ public Int16? OsCurrentTimeZone { get; internal set; }
+
+ ///
+ /// Language identifier used by the operating system.
+ ///
+ ///
+ /// A language identifier is a standard international numeric abbreviation
+ /// for a country/region. Each language has a unique language identifier (LANGID),
+ /// a 16-bit value that consists of a primary language identifier and a secondary
+ /// language identifier
+ ///
+ public string OsLocaleID { get; internal set; } // From Win32_OperatingSystem.Locale
+
+ ///
+ /// The culture name, such as "en-US", derived from the property
+ ///
+ public string OsLocale { get; internal set; }
+
+ ///
+ /// Operating system version of the local date and time-of-day
+ ///
+ public DateTime? OsLocalDateTime { get; internal set; }
+
+ ///
+ /// Date and time the operating system was last restarted
+ ///
+ public DateTime? OsLastBootUpTime { get; internal set; }
+
+ ///
+ /// The interval between the time the operating system was last
+ /// restarted and the current time
+ ///
+ public TimeSpan? OsUptime { get; internal set; }
+
+ ///
+ /// Type of build used for the operating system
+ ///
+ public string OsBuildType { get; internal set; }
+
+ ///
+ /// Code page value the operating system uses
+ ///
+ public string OsCodeSet { get; internal set; }
+
+ ///
+ /// If true, then the data execution prevention hardware feature is available
+ ///
+ public bool? OsDataExecutionPreventionAvailable { get; internal set; }
+
+ ///
+ /// When the data execution prevention hardware feature is available,
+ /// this property indicates that the feature is set to work for 32-bit
+ /// applications if true
+ ///
+ public bool? OsDataExecutionPrevention32BitApplications { get; internal set; }
+
+ ///
+ /// When the data execution prevention hardware feature is available,
+ /// this property indicates that the feature is set to work for drivers
+ /// if true
+ ///
+ public bool? OsDataExecutionPreventionDrivers { get; internal set; }
+
+ ///
+ /// Indicates which Data Execution Prevention (DEP) setting is applied.
+ /// The DEP setting specifies the extent to which DEP applies to 32-bit
+ /// applications on the system. DEP is always applied to the Windows kernel
+ ///
+ public DataExecutionPreventionSupportPolicy? OsDataExecutionPreventionSupportPolicy { get; internal set; }
+
+ ///
+ /// If true, the operating system is a checked (debug) build
+ ///
+ public bool? OsDebug { get; internal set; }
+
+ ///
+ /// If True, the operating system is distributed across several computer
+ /// system nodes. If so, these nodes should be grouped as a cluster
+ ///
+ public bool? OsDistributed { get; internal set; }
+
+ ///
+ /// Encryption level for secure transactions: 40-bit, 128-bit, or n-bit.
+ ///
+ public OSEncryptionLevel? OsEncryptionLevel { get; internal set; }
+
+ ///
+ /// Increased priority given to the foreground application
+ ///
+ public ForegroundApplicationBoost? OsForegroundApplicationBoost { get; internal set; }
+
+ ///
+ /// Total amount, in kilobytes, of physical memory available to the
+ /// operating system.
+ ///
+ ///
+ /// This value does not necessarily indicate the true amount of
+ /// physical memory, but what is reported to the operating system
+ /// as available to it.
+ ///
+ public UInt64? OsTotalVisibleMemorySize { get; internal set; }
+
+ ///
+ /// Number, in kilobytes, of physical memory currently unused and available
+ ///
+ public UInt64? OsFreePhysicalMemory { get; internal set; }
+
+ ///
+ /// Number, in kilobytes, of virtual memory
+ ///
+ public UInt64? OsTotalVirtualMemorySize { get; internal set; }
+
+ ///
+ /// Number, in kilobytes, of virtual memory currently unused and available
+ ///
+ public UInt64? OsFreeVirtualMemory { get; internal set; }
+
+ ///
+ /// Number, in kilobytes, of virtual memory currently in use
+ ///
+ public UInt64? OsInUseVirtualMemory { get; internal set; }
+
+ ///
+ /// Total swap space in kilobytes
+ ///
+ ///
+ /// This value may be NULL (unspecified) if the swap space is not
+ /// distinguished from page files. However, some operating systems
+ /// distinguish these concepts. For example, in UNIX, whole processes
+ /// can be swapped out when the free page list falls and remains below
+ /// a specified amount
+ ///
+ public UInt64? OsTotalSwapSpaceSize { get; internal set; }
+
+ ///
+ /// Total number of kilobytes that can be stored in the operating system
+ /// paging files—0 (zero) indicates that there are no paging files.
+ /// Be aware that this number does not represent the actual physical
+ /// size of the paging file on disk
+ ///
+ public UInt64? OsSizeStoredInPagingFiles { get; internal set; }
+
+ ///
+ /// Number, in kilobytes, that can be mapped into the operating system
+ /// paging files without causing any other pages to be swapped out
+ ///
+ public UInt64? OsFreeSpaceInPagingFiles { get; internal set; }
+
+ ///
+ /// Array of fiel paths to the operating system's paging files
+ ///
+ public string[] OsPagingFiles { get; internal set; }
+
+ ///
+ /// Version of the operating system's Hardware Abstraction Layer (HAL)
+ ///
+ public string OsHardwareAbstractionLayer { get; internal set; }
+
+ ///
+ /// Indicates the install date
+ ///
+ public DateTime? OsInstallDate { get; internal set; }
+
+ ///
+ /// Name of the operating system manufacturer.
+ /// For Windows-based systems, this value is "Microsoft Corporation"
+ ///
+ public string OsManufacturer { get; internal set; }
+
+ ///
+ /// Maximum number of process contexts the operating system can support
+ ///
+ public UInt32? OsMaxNumberOfProcesses { get; internal set; }
+
+ ///
+ /// Maximum number, in kilobytes, of memory that can be allocated to a process
+ ///
+ public UInt64? OsMaxProcessMemorySize { get; internal set; }
+
+ ///
+ /// Array of Multilingual User Interface Pack (MUI Pack) languages installed
+ /// on the computer
+ ///
+ public string[] OsMuiLanguages { get; internal set; }
+
+ ///
+ /// Number of user licenses for the operating system.
+ ///
+ public UInt32? OsNumberOfLicensedUsers { get; internal set; }
+
+ ///
+ /// Number of process contexts currently loaded or running on the operating system
+ ///
+ public UInt32? OsNumberOfProcesses { get; internal set; }
+
+ ///
+ /// Number of user sessions for which the operating system is storing
+ /// state information currently
+ ///
+ public UInt32? OsNumberOfUsers { get; internal set; }
+
+ ///
+ /// Company name for the registered user of the operating system
+ ///
+ public string OsOrganization { get; internal set; }
+
+ ///
+ /// Architecture of the operating system, as opposed to the processor
+ ///
+ public string OsArchitecture { get; internal set; }
+
+ ///
+ /// Language version of the operating system installed
+ ///
+ public string OsLanguage { get; internal set; }
+
+ ///
+ /// Array of objects indicating installed
+ /// and licensed product additions to the operating system
+ ///
+ public OSProductSuite[] OsProductSuites { get; internal set; }
+
+ ///
+ /// Additional description for the current operating system version
+ ///
+ public string OsOtherTypeDescription { get; internal set; }
+
+ ///
+ /// If True, the physical address extensions (PAE) are enabled by the
+ /// operating system running on Intel processors
+ ///
+ public bool? OsPAEEnabled { get; internal set; }
+
+ ///
+ /// Specifies whether the operating system booted from an external USB device.
+ /// If true, the operating system has detected it is booting on a supported
+ /// locally connected storage device
+ ///
+ public bool? OsPortableOperatingSystem { get; internal set; }
+
+ ///
+ /// Specifies whether this is the primary operating system
+ ///
+ public bool? OsPrimary { get; internal set; }
+
+ ///
+ /// Additional system information
+ ///
+ public ProductType? OsProductType { get; internal set; }
+
+ ///
+ /// Name of the registered user of the operating system
+ ///
+ public string OsRegisteredUser { get; internal set; }
+
+ ///
+ /// Operating system product serial identification number
+ ///
+ public string OsSerialNumber { get; internal set; }
+
+ ///
+ /// Major version of the service pack installed on the computer system
+ ///
+ public UInt16? OsServicePackMajorVersion { get; internal set; }
+
+ ///
+ /// Minor version of the service pack installed on the computer system
+ ///
+ public UInt16? OsServicePackMinorVersion { get; internal set; }
+
+ ///
+ /// Current status
+ ///
+ public string OsStatus { get; internal set; }
+
+ ///
+ /// Product suites available on the operating system
+ ///
+ public OSProductSuite[] OsSuites { get; internal set; }
+
+ ///
+ /// Server level of the operating system, if the operating system is a server
+ ///
+ public ServerLevel? OsServerLevel { get; internal set; }
+ #endregion Operating System
+
+ #region Misc Info
+ ///
+ /// Layout of the (first) keyboard attached to the system
+ ///
+ public string KeyboardLayout { get; internal set; }
+
+ ///
+ /// Name of the system's current time zone
+ ///
+ public string TimeZone { get; internal set; }
+
+ ///
+ /// Path to the system's logon server
+ ///
+ public string LogonServer { get; internal set; }
+
+ ///
+ /// Power platform role
+ ///
+ public PowerPlatformRole? PowerPlatformRole { get; internal set; }
+
+ ///
+ /// If true, a HyperVisor was detected
+ ///
+ public bool? HyperVisorPresent { get; internal set; }
+
+ ///
+ /// If a HyperVisor is not present, indicates the state of the
+ /// requirement that the Data Execution Prevention feature is available
+ ///
+ public bool? HyperVRequirementDataExecutionPreventionAvailable { get; internal set; }
+
+ ///
+ /// If a HyperVisor is not present, indicates the state of the
+ /// requirement that the processor supports address translation
+ /// extensions used for virtualization
+ ///
+ public bool? HyperVRequirementSecondLevelAddressTranslation { get; internal set; }
+
+ ///
+ /// If a HyperVisor is not present, indicates the state of the
+ /// requirement that the firmware has enabled virtualization
+ /// extensions
+ ///
+ public bool? HyperVRequirementVirtualizationFirmwareEnabled { get; internal set; }
+
+ ///
+ /// If a HyperVisor is not present, indicates the state of the
+ /// requirement that the processor supports Intel or AMD Virtual
+ /// Machine Monitor extensions
+ ///
+ public bool? HyperVRequirementVMMonitorModeExtensions { get; internal set; }
+
+ ///
+ /// Indicates the status of the Device Guard features
+ ///
+ public DeviceGuardSmartStatus? DeviceGuardSmartStatus { get; internal set; }
+
+ ///
+ /// Required Device Guard security properties
+ ///
+ public DeviceGuardHardwareSecure[] DeviceGuardRequiredSecurityProperties { get; internal set; }
+
+ ///
+ /// Available Device Guard security properties
+ ///
+ public DeviceGuardHardwareSecure[] DeviceGuardAvailableSecurityProperties { get; internal set; }
+
+ ///
+ /// Configured Device Guard security services
+ ///
+ public DeviceGuardSoftwareSecure[] DeviceGuardSecurityServicesConfigured { get; internal set; }
+
+ ///
+ /// Running Device Guard security services
+ ///
+ public DeviceGuardSoftwareSecure[] DeviceGuardSecurityServicesRunning { get; internal set; }
+
+ ///
+ /// Status of the Device Guard Code Integrity policy enforcement
+ ///
+ public DeviceGuardConfigCodeIntegrityStatus? DeviceGuardCodeIntegrityPolicyEnforcementStatus { get; internal set; }
+
+ ///
+ /// Status of the Device Guard user mode Code Integrity policy enforcement
+ ///
+ public DeviceGuardConfigCodeIntegrityStatus? DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus { get; internal set; }
+ #endregion Misc Info
+ }
+ #endregion Classes comprising the output object
+
+ #region Enums used in the output objects
+ ///
+ /// System hardware security settings for administrator password status
+ ///
+ public enum AdminPasswordStatus
+ {
+ ///
+ /// Feature is disabled
+ ///
+ Disabled = 0,
+
+ ///
+ /// Feature is Enabled
+ ///
+ Enabled = 1,
+
+ ///
+ /// Feature is not implemented
+ ///
+ NotImplemented = 2,
+
+ ///
+ /// Status is unknown
+ ///
+ Unknown = 3
+ }
+
+ ///
+ /// Actions related to the BootOptionOn* properties of the Win32_ComputerSystem
+ /// CIM class
+ ///
+ public enum BootOptionAction
+ {
+ ///
+ /// This value is reserved
+ ///
+ Reserved = 0,
+
+ ///
+ /// Boot into operating system
+ ///
+ OperatingSystem = 1,
+
+ ///
+ /// Boot into system utilities
+ ///
+ SystemUtilities = 2,
+
+ ///
+ /// Do not reboot
+ ///
+ DoNotReboot = 3
+ }
+
+ ///
+ /// Indicates the state of a system element
+ ///
+ public enum SystemElementState
+ {
+ ///
+ /// The element state is something other than those in this Enum
+ ///
+ Other = 1,
+
+ ///
+ /// The element state is unknown
+ ///
+ Unknown = 2,
+
+ ///
+ /// The element is in Safe state
+ ///
+ Safe = 3,
+
+ ///
+ /// The element is in Warning state
+ ///
+ Warning = 4,
+
+ ///
+ /// The element is in Critical state
+ ///
+ Critical = 5,
+
+ ///
+ /// The element is in Non-Recoverable state
+ ///
+ NonRecoverable = 6
+ }
+
+ ///
+ /// Specifies the processor architecture
+ ///
+ public enum CpuArchitecture
+ {
+ ///
+ /// Architecture is Intel x86
+ ///
+ x86 = 0,
+
+ ///
+ /// Architecture is MIPS
+ ///
+ MIPs = 1,
+
+ ///
+ /// Architecture is DEC Alpha
+ ///
+ Alpha = 2,
+
+ ///
+ /// Architecture is Motorolla PowerPC
+ ///
+ PowerPC = 3,
+
+ ///
+ /// Architecture is ARM
+ ///
+ ARM = 5,
+
+ ///
+ /// Architecture is Itanium-based 64-bit
+ ///
+ ia64 = 6,
+
+ ///
+ /// Architecture is Intel 64-bit
+ ///
+ x64 = 9
+ }
+
+ ///
+ /// Specifies a CPU's availability and status
+ ///
+ public enum CpuAvailability
+ {
+ ///
+ /// A state other than those specified in CpuAvailability
+ ///
+ Other = 1,
+
+ ///
+ /// Availability status is unknown
+ ///
+ Unknown = 2,
+
+ ///
+ /// The device is running or at full power
+ ///
+ RunningOrFullPower = 3,
+
+ ///
+ /// Device is in a Warning state
+ ///
+ Warning = 4,
+
+ ///
+ /// Availability status is In Test
+ ///
+ InTest = 5,
+
+ ///
+ /// Status is not applicable to this device
+ ///
+ NotApplicable = 6,
+
+ ///
+ /// The device is powered off
+ ///
+ PowerOff = 7,
+
+ ///
+ /// Availability status is Offline
+ ///
+ OffLine = 8,
+
+ ///
+ /// Availability status is Off-Duty
+ ///
+ OffDuty = 9,
+
+ ///
+ /// Availability status is Degraded
+ ///
+ Degraded = 10,
+
+ ///
+ /// Availability status is Not Installed
+ ///
+ NotIntalled = 11,
+
+ ///
+ /// Availability status is Install Error
+ ///
+ InstallError = 12,
+
+ ///
+ /// The device is known to be in a power save state, but its exact status is unknown
+ ///
+ PowerSaveUnknown = 13,
+
+ ///
+ /// The device is in a power save state, but is still functioning,
+ /// and may exhibit decreased performance
+ ///
+ PowerSaveLowPowerMode = 14,
+
+ ///
+ /// The device is not functioning, but can be brought to full power quickly
+ ///
+ PowerSaveStandby = 15,
+
+ ///
+ /// The device is in a power-cycle state
+ ///
+ PowerCycle = 16,
+
+ ///
+ /// The device is in a warning state, though also in a power save state
+ ///
+ PowerSaveWarning = 17,
+
+ ///
+ /// The device is paused
+ ///
+ Paused = 18,
+
+ ///
+ /// The device is not ready
+ ///
+ NotReady = 19,
+
+ ///
+ /// The device is not configured
+ ///
+ NotConfigured = 20,
+
+ ///
+ /// The device is quiet
+ ///
+ Quiesced = 21
+ }
+
+ ///
+ /// Specifies that current status of the processor
+ ///
+ public enum CpuStatus
+ {
+ ///
+ /// CPU status is Unknown
+ ///
+ Unknown = 0,
+
+ ///
+ /// CPU status is Enabled
+ ///
+ Enabled = 1,
+
+ ///
+ /// CPU status is Disabled by User via BIOS Setup
+ ///
+ DisabledByUser = 2,
+
+ ///
+ /// CPU status is Disabled by BIOS
+ ///
+ DisabledByBIOS = 3,
+
+ ///
+ /// CPU is Idle
+ ///
+ Idle = 4,
+
+ ///
+ /// This value is reserved
+ ///
+ Reserved_5 = 5,
+
+ ///
+ /// This value is reserved
+ ///
+ Reserved_6 = 6,
+
+ ///
+ /// CPU is in another state
+ ///
+ Other = 7
+ }
+
+ ///
+ /// Data Execution Prevention (DEP) settings
+ ///
+ public enum DataExecutionPreventionSupportPolicy
+ {
+ //Unknown = -1,
+
+ ///
+ /// DEP is turned off for all 32-bit applications on the computer with no exceptions
+ ///
+ AlwaysOff = 0,
+
+ ///
+ /// DEP is enabled for all 32-bit applications on the computer
+ ///
+ AlwaysOn = 1,
+
+ ///
+ /// DEP is enabled for a limited number of binaries, the kernel, and all
+ /// Windows-based services. However, it is off by default for all 32-bit
+ /// applications. A user or administrator must explicitly choose either
+ /// the Always On or the Opt Out setting before DEP can be applied to
+ /// 32-bit applications
+ ///
+ OptIn = 2,
+
+ ///
+ /// DEP is enabled by default for all 32-bit applications. A user or
+ /// administrator can explicitly remove support for a 32-bit
+ /// application by adding the application to an exceptions list
+ ///
+ OptOut = 3
+ }
+
+ ///
+ /// Status of the Device Guard feature
+ ///
+ public enum DeviceGuardSmartStatus
+ {
+ ///
+ /// Device Guard is off
+ ///
+ Off = 0,
+
+ ///
+ /// Device Guard is Configured
+ ///
+ Configured = 1,
+
+ ///
+ /// Device Guard is Running
+ ///
+ Running = 2
+ }
+
+ ///
+ /// Configuration status of the Device Guard Code Integrity
+ ///
+ public enum DeviceGuardConfigCodeIntegrityStatus
+ {
+ ///
+ /// Code Integrity is off
+ ///
+ Off = 0,
+
+ ///
+ /// Code Integrity uses Audit mode
+ ///
+ AuditMode = 1,
+
+ ///
+ /// Code Integrity uses Enforcement mode
+ ///
+ EnforcementMode = 2
+ }
+
+ ///
+ /// Device Guard hardware security properties
+ ///
+ public enum DeviceGuardHardwareSecure
+ {
+ ///
+ /// Base Virtualization Support
+ ///
+ BaseVirtualizationSupport = 1,
+
+ ///
+ /// Secure Boot
+ ///
+ SecureBoot = 2,
+
+ ///
+ /// DMA Protection
+ ///
+ DMAProtection = 3,
+
+ ///
+ /// Secure Memory Overwrite
+ ///
+ SecureMemoryOverwrite = 4
+ }
+
+ ///
+ /// Device Guard software security properties
+ ///
+ public enum DeviceGuardSoftwareSecure
+ {
+ ///
+ /// Credential Guard
+ ///
+ CredentialGuard = 1,
+
+ ///
+ /// Hypervisor enforced Code Integrity
+ ///
+ HypervisorEnforcedCodeIntegrity = 2
+ }
+
+ ///
+ /// Role of a computer in an assigned domain workgroup
+ ///
+ public enum DomainRole
+ {
+ ///
+ /// Standalone Workstation
+ ///
+ StandaloneWorkstation = 0,
+
+ ///
+ /// Member Workstation
+ ///
+ MemberWorkstation = 1,
+
+ ///
+ /// Standalone Server
+ ///
+ StandaloneServer = 2,
+
+ ///
+ /// Member Server
+ ///
+ MemberServer = 3,
+
+ ///
+ /// Backup Domain Controller
+ ///
+ BackupDomainController = 4,
+
+ ///
+ /// Primary Domain Controller
+ ///
+ PrimaryDomainController = 5
+ }
+
+ ///
+ /// Specifies a firmware type
+ ///
+ public enum FirmwareType
+ {
+ ///
+ /// The firmware type is unknown
+ ///
+ Unknown = 0,
+
+ ///
+ /// The computer booted in legacy BIOS mode
+ ///
+ Bios = 1,
+
+ ///
+ /// The computer booted in UEFI mode
+ ///
+ Uefi = 2,
+
+ ///
+ /// Not implemented
+ ///
+ Max = 3
+ }
+
+ ///
+ /// Increase in priority given to the foreground application
+ ///
+ public enum ForegroundApplicationBoost
+ {
+ ///
+ /// The system boosts the quantum length by 6
+ ///
+ None = 0,
+
+ ///
+ /// The system boosts the quantum length by 12
+ ///
+ Minimum = 1,
+
+ ///
+ /// The system boosts the quantum length by 18
+ ///
+ Maximum = 2
+ }
+
+ ///
+ /// hardware security settings for the reset button on a computer
+ ///
+ public enum FrontPanelResetStatus
+ {
+ ///
+ /// Reset button is disabled
+ ///
+ Disabled = 0,
+
+ ///
+ /// Reset button is enabled
+ ///
+ Enabled = 1,
+
+ ///
+ /// Hardware security settings are not implement
+ ///
+ NotImplemented = 2,
+
+ ///
+ /// Unknown security setting
+ ///
+ Unknown = 3
+ }
+
+ ///
+ /// Indicates a hardware security setting
+ ///
+ public enum HardwareSecurity
+ {
+ ///
+ /// Hardware security is disabled
+ ///
+ Disabled = 0,
+
+ ///
+ /// Hardware security is enabled
+ ///
+ Enabled = 1,
+
+ ///
+ /// Hardware security is not implemented
+ ///
+ NotImplemented = 2,
+
+ ///
+ /// Hardware security setting is unknown
+ ///
+ Unknown = 3
+ }
+
+ ///
+ /// State of the network adapter connection to the network
+ ///
+ public enum NetConnectionStatus
+ {
+ ///
+ /// Adapter is disconnected
+ ///
+ Disconnected = 0,
+
+ ///
+ /// Adapter is connecting
+ ///
+ Connecting = 1,
+
+ ///
+ /// Adapter is connected
+ ///
+ Connected = 2,
+
+ ///
+ /// Adapter is disconnecting
+ ///
+ Disconnecting = 3,
+
+ ///
+ /// Adapter hardware is not present
+ ///
+ HardwareNotPresent = 4,
+
+ ///
+ /// Adapter hardware is disabled
+ ///
+ HardwareDisabled = 5,
+
+ ///
+ /// Adapter has a hardware malfunction
+ ///
+ HardwareMalfunction = 6,
+
+ ///
+ /// Media is disconnected
+ ///
+ MediaDisconnected = 7,
+
+ ///
+ /// Adapter is authenticating
+ ///
+ Authenticating = 8,
+
+ ///
+ /// Authentication has succeeded
+ ///
+ AuthenticationSucceeded = 9,
+
+ ///
+ /// Authentication has failed
+ ///
+ AuthenticationFailed = 10,
+
+ ///
+ /// Address is invalid
+ ///
+ InvalidAddress = 11,
+
+ ///
+ /// Credentials are required
+ ///
+ CredentialsRequired = 12,
+
+ ///
+ /// Other unspecified state
+ ///
+ Other = 13
+ }
+
+ ///
+ /// Encryption level for secure transactions: 40-bit, 128-bit, or n-bit.
+ ///
+ public enum OSEncryptionLevel
+ {
+ ///
+ /// 40-bit encription
+ ///
+ Encrypt40Bits = 0,
+
+ ///
+ /// 128-bit encription
+ ///
+ Encrypt128Bits = 1,
+
+ ///
+ /// n-bit encription
+ ///
+ EncryptNBits = 2
+ }
+
+ ///
+ /// Indicates installed and licensed system product additions to the operating system
+ ///
+ public enum OSProductSuite
+ {
+ ///
+ /// Microsoft Small Business Server was once installed, but may have
+ /// been upgraded to another version of Windows
+ ///
+ SmallBusinessServer = 0x0001,
+
+ ///
+ /// Windows Server 2008 Enterprise is installed
+ ///
+ Server2008Enterprise = 0x0002,
+
+ ///
+ /// Windows BackOffice components are installed
+ ///
+ BackOfficeComponents = 0x0004,
+
+ ///
+ /// Communication Server is installed
+ ///
+ CommunicationsServer = 0x0008,
+
+ ///
+ /// Terminal Services is installed
+ ///
+ TerminalServices = 0x0010,
+
+ ///
+ /// Microsoft Small Business Server is installed with the restrictive
+ /// client license
+ ///
+ SmallBusinessServerRestricted = 0x0020,
+
+ ///
+ /// Windows Embedded is installed
+ ///
+ WindowsEmbedded = 0x0040,
+
+ ///
+ /// A Datacenter edition is installed
+ ///
+ DatacenterEdition = 0x0080,
+
+ ///
+ /// Terminal Services is installed, but only one interactive session is supported
+ ///
+ TerminalServicesSingleSession = 0x0100,
+
+ ///
+ /// Windows Home Edition is installed
+ ///
+ HomeEdition = 0x0200,
+
+ ///
+ /// Web Server Edition is installed
+ ///
+ WebServerEdition = 0x0400,
+
+ ///
+ /// Storage Server Edition is installed
+ ///
+ StorageServerEdition = 0x2000,
+
+ ///
+ /// Compute Cluster Edition is installed
+ ///
+ ComputeClusterEdition = 0x4000
+ }
+
+ ///
+ /// Indicates the operating system Stock Keeping Unit (SKU)
+ ///
+ public enum OperatingSystemSKU
+ {
+ ///
+ /// The SKU is undefined
+ ///
+ Undefined = 0,
+
+ ///
+ /// SKU is Ultimate Edition
+ ///
+ UltimateEdition = 1,
+
+ ///
+ /// SKU is Home Basic Edition
+ ///
+ HomeBasicEdition = 2,
+
+ ///
+ /// SKU is Home Premium Edition
+ ///
+ HomePremiumEdition = 3,
+
+ ///
+ /// SKU is Enterprise Edition
+ ///
+ EnterpriseEdition = 4,
+
+ ///
+ /// SKU is Home Basic N Edition
+ ///
+ HomeBasicNEdition = 5,
+
+ ///
+ /// SKU is Business Edition
+ ///
+ BusinessEdition = 6,
+
+ ///
+ /// SKU is Standard Server Edition
+ ///
+ StandardServerEdition = 7,
+
+ ///
+ /// SKU is Datacenter Server Edition
+ ///
+ DatacenterServerEdition = 8,
+
+ ///
+ /// SKU is Small Business Server Edition
+ ///
+ SmallBusinessServerEdition = 9,
+
+ ///
+ /// SKU is Enterprise Server Edition
+ ///
+ EnterpriseServerEdition = 10,
+
+ ///
+ /// SKU is Starter Edition
+ ///
+ StarterEdition = 11,
+
+ ///
+ /// SKU is Datacenter Server Core Edition
+ ///
+ DatacenterServerCoreEdition = 12,
+
+ ///
+ /// SKU is Standard Server Core Edition
+ ///
+ StandardServerCoreEdition = 13,
+
+ ///
+ /// SKU is Enterprise Server Core Edition
+ ///
+ EnterpriseServerCoreEdition = 14,
+
+ ///
+ /// SKU is Enterprise Server IA64 Edition
+ ///
+ EnterpriseServerIA64Edition = 15,
+
+ ///
+ /// SKU is Business N Edition
+ ///
+ BusinessNEdition = 16,
+
+ ///
+ /// SKU is Web Server Edition
+ ///
+ WebServerEdition = 17,
+
+ ///
+ /// SKU is Cluster Server Edition
+ ///
+ ClusterServerEdition = 18,
+
+ ///
+ /// SKU is Home Server Edition
+ ///
+ HomeServerEdition = 19,
+
+ ///
+ /// SKU is Storage Express Server Edition
+ ///
+ StorageExpressServerEdition = 20,
+
+ ///
+ /// SKU is Storage Standard Server Edition
+ ///
+ StorageStandardServerEdition = 21,
+
+ ///
+ /// SKU is Storage Workgroup Server Edition
+ ///
+ StorageWorkgroupServerEdition = 22,
+
+ ///
+ /// SKU is Storage Enterprise Server Edition
+ ///
+ StorageEnterpriseServerEdition = 23,
+
+ ///
+ /// SKU is Server For Small Business Edition
+ ///
+ ServerForSmallBusinessEdition = 24,
+
+ ///
+ /// SKU is Small Business Server Premium Edition
+ ///
+ SmallBusinessServerPremiumEdition = 25,
+
+ ///
+ /// SKU is to be determined
+ ///
+ TBD = 26,
+
+ ///
+ /// SKU is Windows Enterprise
+ ///
+ WindowsEnterprise = 27,
+
+ ///
+ /// SKU is Windows Ultimate
+ ///
+ WindowsUltimate = 28,
+
+ ///
+ /// SKU is Web Server (core installation)
+ ///
+ WebServerCore = 29,
+
+ ///
+ /// SKU is Server Foundation
+ ///
+ ServerFoundation = 33,
+
+ ///
+ /// SKU is Windows Home Server
+ ///
+ WindowsHomeServer = 34,
+
+ ///
+ /// SKU is Windows Server Standard without Hyper-V
+ ///
+ WindowsServerStandardNoHyperVFull = 36,
+
+ ///
+ /// SKU is Windows Server Datacenter without Hyper-V (full installation)
+ ///
+ WindowsServerDatacenterNoHyperVFull = 37,
+
+ ///
+ /// SKU is Windows Server Enterprise without Hyper-V (full installation)
+ ///
+ WindowsServerEnterpriseNoHyperVFull = 38,
+
+ ///
+ /// SKU is Windows Server Datacenter without Hyper-V (core installation)
+ ///
+ WindowsServerDatacenterNoHyperVCore = 39,
+
+ ///
+ /// SKU is Windows Server Standard without Hyper-V (core installation)
+ ///
+ WindowsServerStandardNoHyperVCore = 40,
+
+ ///
+ /// SKU is Windows Server Enterprise without Hyper-V (core installation)
+ ///
+ WindowsServerEnterpriseNoHyperVCore = 41,
+
+ ///
+ /// SKU is Microsoft Hyper-V Server
+ ///
+ MicrosoftHyperVServer = 42,
+
+ ///
+ /// SKU is Storage Server Express (core installation)
+ ///
+ StorageServerExpressCore = 43,
+
+ ///
+ /// SKU is Storage Server Standard (core installation)
+ ///
+ StorageServerStandardCore = 44,
+
+ ///
+ /// SKU is Storage Server Workgroup (core installation)
+ ///
+ StorageServerWorkgroupCore = 45,
+
+ ///
+ /// SKU is Storage Server Enterprise (core installation)
+ ///
+ StorageServerEnterpriseCore = 46,
+
+ ///
+ /// SKU is Windows Small Business Server 2011 Essentials
+ ///
+ WindowsSmallBusinessServer2011Essentials = 50,
+
+ ///
+ /// SKU is Small Business Server Premium (core installation)
+ ///
+ SmallBusinessServerPremiumCore = 63,
+
+ ///
+ /// SKU is Windows Server Hyper Core V
+ ///
+ WindowsServerHyperCoreV = 64,
+
+ ///
+ /// SKU is Windows Thin PC
+ ///
+ WindowsThinPC = 87,
+
+ ///
+ /// SKU is Windows Embedded Industry
+ ///
+ WindowsEmbeddedIndustry = 89,
+
+ ///
+ /// SKU is Windows RT
+ ///
+ WindowsRT = 97,
+
+ ///
+ /// SKU is Windows Home
+ ///
+ WindowsHome = 101,
+
+ ///
+ /// SKU is Windows Professional with Media Center
+ ///
+ WindowsProfessionalWithMediaCenter = 103,
+
+ ///
+ /// SKU is Windows Mobile
+ ///
+ WindowsMobile = 104,
+
+ ///
+ /// SKU is Windows Embedded Handheld
+ ///
+ WindowsEmbeddedHandheld = 118,
+
+ ///
+ /// SKU is Windows IoT (Internet of Things) Core
+ ///
+ WindowsIotCore = 123
+ }
+
+ ///
+ /// Type of operating system
+ ///
+ public enum OSType
+ {
+ ///
+ /// OS is unknown
+ ///
+ Unknown = 0,
+
+ ///
+ /// OS is one other than covered by this Enum
+ ///
+ Other = 1,
+
+ ///
+ /// OS is MacOS
+ ///
+ MACROS = 2,
+
+ ///
+ /// OS is AT&T UNIX
+ ///
+ ATTUNIX = 3,
+
+ ///
+ /// OS is DG/UX
+ ///
+ DGUX = 4,
+
+ ///
+ /// OS is DECNT
+ ///
+ DECNT = 5,
+
+ ///
+ /// OS is Digital UNIX
+ ///
+ DigitalUNIX = 6,
+
+ ///
+ /// OS is OpenVMS
+ ///
+ OpenVMS = 7,
+
+ ///
+ /// OS is HP-UX
+ ///
+ HPUX = 8,
+
+ ///
+ /// OS is AIX
+ ///
+ AIX = 9,
+
+ ///
+ /// OS is MVS
+ ///
+ MVS = 10,
+
+ ///
+ /// OS is OS/400
+ ///
+ OS400 = 11,
+
+ ///
+ /// OS is OS/2
+ ///
+ OS2 = 12,
+
+ ///
+ /// OS is Java Virtual Machine
+ ///
+ JavaVM = 13,
+
+ ///
+ /// OS is MS-DOS
+ ///
+ MSDOS = 14,
+
+ ///
+ /// OS is Windows 3x
+ ///
+ WIN3x = 15,
+
+ ///
+ /// OS is Windows 95
+ ///
+ WIN95 = 16,
+
+ ///
+ /// OS is Windows 98
+ ///
+ WIN98 = 17,
+
+ ///
+ /// OS is Windows NT
+ ///
+ WINNT = 18,
+
+ ///
+ /// OS is Windows CE
+ ///
+ WINCE = 19,
+
+ ///
+ /// OS is NCR System 3000
+ ///
+ NCR3000 = 20,
+
+ ///
+ /// OS is NetWare
+ ///
+ NetWare = 21,
+
+ ///
+ /// OS is OSF
+ ///
+ OSF = 22,
+
+ ///
+ /// OS is DC/OS
+ ///
+ DC_OS = 23,
+
+ ///
+ /// OS is Reliant UNIX
+ ///
+ ReliantUNIX = 24,
+
+ ///
+ /// OS is SCO UnixWare
+ ///
+ SCOUnixWare = 25,
+
+ ///
+ /// OS is SCO OpenServer
+ ///
+ SCOOpenServer = 26,
+
+ ///
+ /// OS is Sequent
+ ///
+ Sequent = 27,
+
+ ///
+ /// OS is IRIX
+ ///
+ IRIX = 28,
+
+ ///
+ /// OS is Solaris
+ ///
+ Solaris = 29,
+
+ ///
+ /// OS is SunOS
+ ///
+ SunOS = 30,
+
+ ///
+ /// OS is U6000
+ ///
+ U6000 = 31,
+
+ ///
+ /// OS is ASERIES
+ ///
+ ASERIES = 32,
+
+ ///
+ /// OS is Tandem NSK
+ ///
+ TandemNSK = 33,
+
+ ///
+ /// OS is Tandem NT
+ ///
+ TandemNT = 34,
+
+ ///
+ /// OS is BS2000
+ ///
+ BS2000 = 35,
+
+ ///
+ /// OS is Linux
+ ///
+ LINUX = 36,
+
+ ///
+ /// OS is Lynx
+ ///
+ Lynx = 37,
+
+ ///
+ /// OS is XENIX
+ ///
+ XENIX = 38,
+
+ ///
+ /// OS is VM/ESA
+ ///
+ VM_ESA = 39,
+
+ ///
+ /// OS is Interactive UNIX
+ ///
+ InteractiveUNIX = 40,
+
+ ///
+ /// OS is BSD UNIX
+ ///
+ BSDUNIX = 41,
+
+ ///
+ /// OS is FreeBSD
+ ///
+ FreeBSD = 42,
+
+ ///
+ /// OS is NetBSD
+ ///
+ NetBSD = 43,
+
+ ///
+ /// OS is GNU Hurd
+ ///
+ GNUHurd = 44,
+
+ ///
+ /// OS is OS 9
+ ///
+ OS9 = 45,
+
+ ///
+ /// OS is Mach Kernel
+ ///
+ MACHKernel = 46,
+
+ ///
+ /// OS is Inferno
+ ///
+ Inferno = 47,
+
+ ///
+ /// OS is QNX
+ ///
+ QNX = 48,
+
+ ///
+ /// OS is EPOC
+ ///
+ EPOC = 49,
+
+ ///
+ /// OS is IxWorks
+ ///
+ IxWorks = 50,
+
+ ///
+ /// OS is VxWorks
+ ///
+ VxWorks = 51,
+
+ ///
+ /// OS is MiNT
+ ///
+ MiNT = 52,
+
+ ///
+ /// OS is BeOS
+ ///
+ BeOS = 53,
+
+ ///
+ /// OS is HP MPE
+ ///
+ HP_MPE = 54,
+
+ ///
+ /// OS is NextStep
+ ///
+ NextStep = 55,
+
+ ///
+ /// OS is PalmPilot
+ ///
+ PalmPilot = 56,
+
+ ///
+ /// OS is Rhapsody
+ ///
+ Rhapsody = 57,
+
+ ///
+ /// OS is Windows 2000
+ ///
+ Windows2000 = 58,
+
+ ///
+ /// OS is Dedicated
+ ///
+ Dedicated = 59,
+
+ ///
+ /// OS is OS/390
+ ///
+ OS_390 = 60,
+
+ ///
+ /// OS is VSE
+ ///
+ VSE = 61,
+
+ ///
+ /// OS is TPF
+ ///
+ TPF = 62
+ }
+
+ ///
+ /// Specifies the type of the computer in use, such as laptop, desktop, or Tablet
+ ///
+ public enum PCSystemType
+ {
+ ///
+ /// System type is unspecified
+ ///
+ Unspecified = 0,
+
+ ///
+ /// System is a desktop
+ ///
+ Desktop = 1,
+
+ ///
+ /// System is a mobile device
+ ///
+ Mobile = 2,
+
+ ///
+ /// System is a workstation
+ ///
+ Workstation = 3,
+
+ ///
+ /// System is an Enterprise Server
+ ///
+ EnterpriseServer = 4,
+
+ ///
+ /// System is a Small Office and Home Office (SOHO) Server
+ ///
+ SOHOServer = 5,
+
+ ///
+ /// System is an appliance PC
+ ///
+ AppliancePC = 6,
+
+ ///
+ /// System is a performance server
+ ///
+ PerformanceServer = 7,
+
+ ///
+ /// Maximum enum value
+ ///
+ Maximum = 8
+ }
+
+ ///
+ /// Specifies the type of the computer in use, such as laptop, desktop, or Tablet.
+ /// This is an extended verion of PCSystemType
+ ///
+ //TODO: conflate these two enums???
+ public enum PCSystemTypeEx
+ {
+ ///
+ /// System type is unspecified
+ ///
+ Unspecified = 0,
+
+ ///
+ /// System is a desktop
+ ///
+ Desktop = 1,
+
+ ///
+ /// System is a mobile device
+ ///
+ Mobile = 2,
+
+ ///
+ /// System is a workstation
+ ///
+ Workstation = 3,
+
+ ///
+ /// System is an Enterprise Server
+ ///
+ EnterpriseServer = 4,
+
+ ///
+ /// System is a Small Office and Home Office (SOHO) Server
+ ///
+ SOHOServer = 5,
+
+ ///
+ /// System is an appliance PC
+ ///
+ AppliancePC = 6,
+
+ ///
+ /// System is a performance server
+ ///
+ PerformanceServer = 7,
+
+ ///
+ /// System is a Slate
+ ///
+ Slate = 8,
+
+ ///
+ /// Maximum enum value
+ ///
+ Maximum = 9
+ }
+
+ ///
+ /// Specifies power-related capabilities of a logical device
+ ///
+ public enum PowerManagementCapabilities
+ {
+ ///
+ /// Unknown capability
+ ///
+ Unknown = 0,
+
+ ///
+ /// Power management not supported
+ ///
+ NotSupported = 1,
+
+ ///
+ /// Power management features are currently disabled
+ ///
+ Disabled = 2,
+
+ ///
+ /// The power management features are currently enabled,
+ /// but the exact feature set is unknown or the information is unavailable
+ ///
+ Enabled = 3,
+
+ ///
+ /// The device can change its power state based on usage or other criteria
+ ///
+ PowerSavingModesEnteredAutomatically = 4,
+
+ ///
+ /// The power state may be set through the Win32_LogicalDevice class
+ ///
+ PowerStateSettable = 5,
+
+ ///
+ /// Power may be done through the Win32_LogicalDevice class
+ ///
+ PowerCyclingSupported = 6,
+
+ ///
+ /// Timed power-on is supported
+ ///
+ TimedPowerOnSupported = 7
+ }
+
+ ///
+ /// Specified power states
+ ///
+ public enum PowerState
+ {
+ ///
+ /// Power state is unknown
+ ///
+ Unknown = 0,
+
+ ///
+ /// Full power
+ ///
+ FullPower = 1,
+
+ ///
+ /// Power Save - Low Power mode
+ ///
+ PowerSaveLowPowerMode = 2,
+
+ ///
+ /// Power Save - Standby
+ ///
+ PowerSaveStandby = 3,
+
+ ///
+ /// Unknown Power Save mode
+ ///
+ PowerSaveUnknown = 4,
+
+ ///
+ /// Power Cycle
+ ///
+ PowerCycle = 5,
+
+ ///
+ /// Power Off
+ ///
+ PowerOff = 6,
+
+ ///
+ /// Power Save - Warning
+ ///
+ PowerSaveWarning = 7,
+
+ ///
+ /// Power Save - Hibernate
+ ///
+ PowerSaveHibernate = 8,
+
+ ///
+ /// Power Save - Soft off
+ ///
+ PowerSaveSoftOff = 9
+ }
+
+ ///
+ /// Specifies the primary function of a processor
+ ///
+ public enum ProcessorType
+ {
+ ///
+ /// Processor ype is other than provided in these enumeration values
+ ///
+ Other = 1,
+
+ ///
+ /// Proccessor type is
+ ///
+ Unknown = 2,
+
+ ///
+ /// Proccessor is a Central Processing Unit (CPU)
+ ///
+ CentralProcessor = 3,
+
+ ///
+ /// Proccessor is a Math processor
+ ///
+ MathProcessor = 4,
+
+ ///
+ /// Proccessor is a Digital Signal processor (DSP)
+ ///
+ DSPProcessor = 5,
+
+ ///
+ /// Proccessor is a Video processor
+ ///
+ VideoProcessor = 6
+ }
+
+ ///
+ /// Specifies a computer's reset capability
+ ///
+ public enum ResetCapability
+ {
+ ///
+ /// Capability is a value other than provided in these enumerated values
+ ///
+ Other = 1,
+
+ ///
+ /// Reset capability is unknown
+ ///
+ Unknown = 2,
+
+ ///
+ /// Capability is disabled
+ ///
+ Disabled = 3,
+
+ ///
+ /// Capability is enabled
+ ///
+ Enabled = 4,
+
+ ///
+ /// Capability is not implemented
+ ///
+ NotImplemented = 5
+ }
+
+ ///
+ /// Specifies the kind of event that causes a computer to power up
+ ///
+ public enum WakeUpType
+ {
+ ///
+ /// This value is reserved
+ ///
+ Reserved = 0,
+
+ ///
+ /// An event other than specified in this enumeration
+ ///
+ Other = 1,
+
+ ///
+ /// Event type is unknown
+ ///
+ Unknown = 2,
+
+ ///
+ /// Event is APM timer
+ ///
+ APMTimer = 3,
+
+ ///
+ /// Event is a Modem Ring
+ ///
+ ModemRing = 4,
+
+ ///
+ /// Event is a LAN Remove
+ ///
+ LANRemote = 5,
+
+ ///
+ /// Event is a power switch
+ ///
+ PowerSwitch = 6,
+
+ ///
+ /// Event is a PCI PME# signal
+ ///
+ PCIPME = 7,
+
+ ///
+ /// AC power was restored
+ ///
+ ACPowerRestored = 8
+ }
+
+ ///
+ /// Indicates the OEM's preferred power management profile
+ ///
+ public enum PowerPlatformRole
+ {
+ ///
+ /// The OEM did not specify a specific role
+ ///
+ Unspecified = 0,
+
+ ///
+ /// The OEM specified a desktop role
+ ///
+ Desktop = 1,
+
+ ///
+ /// The OEM specified a mobile role (for example, a laptop)
+ ///
+ Mobile = 2,
+
+ ///
+ /// The OEM specified a workstation role
+ ///
+ Workstation = 3,
+
+ ///
+ /// The OEM specified an enterprise server role
+ ///
+ EnterpriseServer = 4,
+
+ ///
+ /// The OEM specified a single office/home office (SOHO) server role
+ ///
+ SOHOServer = 5,
+
+ ///
+ /// The OEM specified an appliance PC role
+ ///
+ AppliancePC = 6,
+
+ ///
+ /// The OEM specified a performance server role
+ ///
+ PerformanceServer = 7, // v1 last supported
+
+ ///
+ /// The OEM specified a tablet form factor role
+ ///
+ Slate = 8, // v2 last supported
+
+ ///
+ /// Max enum value
+ ///
+ MaximumEnumValue
+ }
+
+ ///
+ /// Additional system information, from Win32_OperatingSystem
+ ///
+ public enum ProductType
+ {
+ ///
+ /// Product type is unknown
+ ///
+ Unknown = 0, // this value is not specified in Win32_OperatingSystem, but may prove useful
+
+ ///
+ /// System is a workstation
+ ///
+ WorkStation = 1,
+
+ ///
+ /// System is a domain controller
+ ///
+ DomainController = 2,
+
+ ///
+ /// System is a server
+ ///
+ Server = 3
+ }
+
+ ///
+ /// Specifies the system server level
+ ///
+ public enum ServerLevel
+ {
+ ///
+ /// An unknown or unrecognized level was dected
+ ///
+ Unknown = 0,
+
+ ///
+ /// Nano server
+ ///
+ NanoServer,
+
+ ///
+ /// Server core
+ ///
+ ServerCore,
+
+ ///
+ /// Server core with management tools
+ ///
+ ServerCoreWithManagementTools,
+
+ ///
+ /// Full server
+ ///
+ FullServer
+ }
+
+ ///
+ /// State of a software element
+ ///
+ public enum SoftwareElementState : UInt16
+ {
+ ///
+ /// Software element is deployable
+ ///
+ Deployable = 0,
+
+ ///
+ /// Software element is installable
+ ///
+ Installable = 1,
+
+ ///
+ /// Software element is executable
+ ///
+ Executable = 2,
+
+ ///
+ /// Software element is running
+ ///
+ Running = 3
+ }
+ #endregion Enums used in the output objects
+ #endregion Output components
+
+ #region Native
+ internal static class Native
+ {
+ private static class PInvokeDllNames
+ {
+#if CORECLR
+ public const string GetPhysicallyInstalledSystemMemoryDllName = "api-ms-win-core-sysinfo-l1-2-1.dll";
+ public const string LCIDToLocaleNameDllName = "kernelbase.dll";
+ public const string PowerDeterminePlatformRoleExDllName = "api-ms-win-power-base-l1-1-0.dll";
+ public const string GetFirmwareTypeDllName = "api-ms-win-core-kernel32-legacy-l1-1-1";
+#else
+ public const string GetPhysicallyInstalledSystemMemoryDllName = "kernel32.dll";
+ public const string LCIDToLocaleNameDllName = "kernel32.dll";
+ public const string PowerDeterminePlatformRoleExDllName = "Powrprof.dll";
+ public const string GetFirmwareTypeDllName = "kernel32.dll";
+#endif
+ }
+
+ public const int LOCALE_NAME_MAX_LENGTH = 85;
+ public const uint POWER_PLATFORM_ROLE_V1 = 0x1;
+ public const uint POWER_PLATFORM_ROLE_V2 = 0x2;
+
+ public const UInt32 S_OK = 0;
+
+
+ ///
+ /// Import WINAPI function PowerDeterminePlatformRoleEx
+ ///
+ /// The version of the POWER_PLATFORM_ROLE enumeration for the platform
+ /// POWER_PLATFORM_ROLE enumeration
+ [DllImport(PInvokeDllNames.PowerDeterminePlatformRoleExDllName, EntryPoint = "PowerDeterminePlatformRoleEx", CharSet = CharSet.Ansi)]
+ public static extern uint PowerDeterminePlatformRoleEx(uint version);
+
+ ///
+ /// Retrieve the amount of RAM physically installed in the computer
+ ///
+ ///
+ ///
+ [DllImport(PInvokeDllNames.GetPhysicallyInstalledSystemMemoryDllName, SetLastError=true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool GetPhysicallyInstalledSystemMemory(out ulong MemoryInKilobytes);
+
+ ///
+ /// Retrieve the firmware type of the local computer
+ ///
+ ///
+ /// A reference to a enumeration to contain
+ /// the resultant firmware type
+ ///
+ ///
+ [DllImport(PInvokeDllNames.GetFirmwareTypeDllName, SetLastError=true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool GetFirmwareType(ref FirmwareType firmwareType);
+
+ ///
+ /// Convert a Local Identifier to a Locale name
+ ///
+ /// The Locale ID (LCID) to be converted
+ /// Destination of the Locale name
+ /// Capacity of
+ ///
+ ///
+ [DllImport(PInvokeDllNames.LCIDToLocaleNameDllName, SetLastError = true, CharSet = CharSet.Unicode)]
+ public static extern int LCIDToLocaleName(uint localeID, System.Text.StringBuilder localeName, int localeNameSize, int flags);
+
+#if !CORECLR
+ ///
+ /// Gets the data specified for the passed in property name from the
+ /// Software Licensing API
+ ///
+ /// Name of the licensing property to get.
+ /// Out parameter for the value.
+ /// An hresult indicating success or failure.
+ [DllImport("slc.dll", CharSet = CharSet.Unicode)]
+ internal static extern int SLGetWindowsInformationDWORD(string licenseProperty, out int propertyValue);
+ /*
+ * SLGetWindowsInformationDWORD function returns
+ * S_OK (0x00000000): If the method succeeds
+ * SL_E_RIGHT_NOT_GRANTED (0xC004F013): The caller does not have the permissions necessary to call this function.
+ * SL_E_DATATYPE_MISMATCHED (0xC004F013): The value portion of the name-value pair is not a DWORD.
+ [DllImport("Slc.dll", EntryPoint = "SLGetWindowsInformationDWORD", CharSet = CharSet.Unicode)]
+ public static extern UInt32 SLGetWindowsInformationDWORD(string pwszValueName, ref int pdwValue);
+ */
+#endif
+ }
+ #endregion Native
+}
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs
index cea0a87317..6c61c44b53 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs
@@ -1364,7 +1364,12 @@ namespace Microsoft.PowerShell.Commands
///
[Parameter(ParameterSetName = "FromSource")]
[Parameter(ParameterSetName = "FromMember")]
- [Alias("Provider")]
+ [Alias("Provider")]
+ // Disabling OACR warning 26506 and 26505, which complains that there could be null pointer.
+ // Since we are using [ValidateNotNullOrEmpty], PowerShell will throw an error if CodeDomProvider is null or empty.
+ [SuppressMessage("Microsoft.Usage", "#pw26506")]
+ [SuppressMessage("Microsoft.Usage", "#pw26505")]
+ [ValidateNotNullOrEmpty]
public CodeDomProvider CodeDomProvider
{
get
diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs
index ada15734b3..f1c993950f 100644
--- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs
+++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs
@@ -1930,9 +1930,9 @@ namespace Microsoft.PowerShell.Commands
private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePath)
{
//if recurse is true, remove every cert in the store
- string localName = Security.NativeMethods.CryptFindLocalizedName(storeName);
+ IntPtr localName = Security.NativeMethods.CryptFindLocalizedName(storeName);
string[] pathElements = GetPathElements(sourcePath);
- if (null == localName)//not find, we can remove
+ if (IntPtr.Zero == localName)//not find, we can remove
{
X509NativeStore store = null;
diff --git a/src/Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 b/src/Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1
index 425e64b78b..cfe1a89e6d 100644
--- a/src/Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1
+++ b/src/Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1
@@ -8,7 +8,7 @@ PowerShellVersion="3.0"
CLRVersion="4.0"
NestedModules="Microsoft.PowerShell.Commands.Management.dll"
HelpInfoURI = 'http://go.microsoft.com/fwlink/?linkid=390785'
-AliasesToExport = @("gcb", "scb")
+AliasesToExport = @("gcb", "scb","gin")
FunctionsToExport = @()
CmdletsToExport=@("Add-Content",
"Clear-Content",
@@ -95,5 +95,6 @@ CmdletsToExport=@("Add-Content",
"Show-ControlPanelItem",
"Clear-Recyclebin",
"Get-Clipboard",
- "Set-Clipboard")
+ "Set-Clipboard",
+ "Get-ComputerInfo")
}
diff --git a/src/Modules/PSDiagnostics/PSDiagnostics.psm1 b/src/Modules/PSDiagnostics/PSDiagnostics.psm1
index d36168f27d..7df91bb795 100644
Binary files a/src/Modules/PSDiagnostics/PSDiagnostics.psm1 and b/src/Modules/PSDiagnostics/PSDiagnostics.psm1 differ
diff --git a/src/Modules/PSGet/PSGet.psd1 b/src/Modules/PSGet/PSGet.psd1
index 9fa416ac98..e1b86328db 100644
Binary files a/src/Modules/PSGet/PSGet.psd1 and b/src/Modules/PSGet/PSGet.psd1 differ
diff --git a/src/Modules/PSGet/PSModule.psm1 b/src/Modules/PSGet/PSModule.psm1
index 35c2b88ccc..060456bb9e 100644
--- a/src/Modules/PSGet/PSModule.psm1
+++ b/src/Modules/PSGet/PSModule.psm1
@@ -2001,6 +2001,11 @@ function Find-DscResource
[ValidateNotNull()]
[Version]
$MinimumVersion,
+
+ [Parameter()]
+ [ValidateNotNull()]
+ [Version]
+ $MaximumVersion,
[Parameter()]
[ValidateNotNull()]
@@ -2104,6 +2109,11 @@ function Find-Command
[ValidateNotNull()]
[Version]
$MinimumVersion,
+
+ [Parameter()]
+ [ValidateNotNull()]
+ [Version]
+ $MaximumVersion,
[Parameter()]
[ValidateNotNull()]
@@ -2210,6 +2220,11 @@ function Find-RoleCapability
[Version]
$MinimumVersion,
+ [Parameter()]
+ [ValidateNotNull()]
+ [Version]
+ $MaximumVersion,
+
[Parameter()]
[ValidateNotNull()]
[Version]
@@ -3729,6 +3744,11 @@ function Register-PSRepository
[Uri]
$ScriptPublishLocation,
+ [Parameter(ValueFromPipelineByPropertyName=$true,
+ ParameterSetName='NameParameterSet')]
+ [PSCredential]
+ $Credential,
+
[Parameter(Mandatory=$true,
ParameterSetName='PSGalleryParameterSet')]
[Switch]
@@ -3834,6 +3854,7 @@ function Register-PSRepository
# Ping and resolve the specified location
$SourceLocation = Resolve-Location -Location (Get-LocationString -LocationUri $SourceLocation) `
-LocationParameterName 'SourceLocation' `
+ -Credential $Credential `
-Proxy $Proxy `
-ProxyCredential $ProxyCredential `
-CallerPSCmdlet $PSCmdlet
@@ -3929,6 +3950,10 @@ function Set-PSRepository
[Uri]
$ScriptPublishLocation,
+ [Parameter(ValueFromPipelineByPropertyName=$true)]
+ [PSCredential]
+ $Credential,
+
[Parameter()]
[ValidateSet('Trusted','Untrusted')]
[string]
@@ -4015,6 +4040,7 @@ function Set-PSRepository
# Ping and resolve the specified location
$SourceLocation = Resolve-Location -Location (Get-LocationString -LocationUri $SourceLocation) `
-LocationParameterName 'SourceLocation' `
+ -Credential $Credential `
-Proxy $Proxy `
-ProxyCredential $ProxyCredential `
-CallerPSCmdlet $PSCmdlet
@@ -5746,13 +5772,14 @@ function Check-PSGalleryApiAvailability
# check internet availability first
$connected = $false
+ $microsoftDomain = 'www.microsoft.com'
if(Get-Command Microsoft.PowerShell.Management\Test-Connection -ErrorAction SilentlyContinue)
{
- $connected = Microsoft.PowerShell.Management\Test-Connection -ComputerName "www.microsoft.com" -Count 1 -Quiet
+ $connected = Microsoft.PowerShell.Management\Test-Connection -ComputerName $microsoftDomain -Count 1 -Quiet
}
else
{
- $connected = NetTCPIP\Test-NetConnection -ComputerName "www.microsoft.com" -InformationLevel Quiet
+ $connected = NetTCPIP\Test-NetConnection -ComputerName $microsoftDomain -InformationLevel Quiet
}
if ( -not $connected)
{
@@ -5876,6 +5903,9 @@ function Ping-Endpoint
[string]
$Endpoint,
+ [Parameter()]
+ $Credential,
+
[Parameter()]
$Proxy,
@@ -5907,7 +5937,15 @@ function Ping-Endpoint
try
{
$handler = New-Object System.Net.Http.HttpClientHandler
- $handler.UseDefaultCredentials = $true
+
+ if($Credential)
+ {
+ $handler.Credentials = $Credential.GetNetworkCredential()
+ }
+ else
+ {
+ $handler.UseDefaultCredentials = $true
+ }
if($WebProxy)
{
@@ -5935,14 +5973,22 @@ function Ping-Endpoint
$iss.LanguageMode = "FullLanguage"
$WebRequestcmd = @'
- param($WebProxy)
+ param($Credential, $WebProxy)
try
{{
$request = [System.Net.WebRequest]::Create("{0}")
$request.Method = 'GET'
$request.Timeout = 30000
- $request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
+ if($Credential)
+ {{
+ $request.Credentials = $Credential.GetNetworkCredential()
+ }}
+ else
+ {{
+ $request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
+ }}
+
$request.AllowAutoRedirect = ${1}
if($WebProxy)
@@ -5971,7 +6017,12 @@ function Ping-Endpoint
if($WebProxy)
{
- $ps.AddParameter($WebProxy)
+ $null = $ps.AddParameter('WebProxy', $WebProxy)
+ }
+
+ if($Credential)
+ {
+ $null = $ps.AddParameter('Credential', $Credential)
}
$response = $ps.Invoke()
@@ -8373,6 +8424,8 @@ function Add-PackageSource
{
return
}
+
+ $Credential = $request.Credential
$IsNewModuleSource = $false
$Options = $request.Options
@@ -8615,6 +8668,7 @@ function Add-PackageSource
# Ping and resolve the specified location
$Location = Resolve-Location -Location $Location `
-LocationParameterName 'Location' `
+ -Credential $Credential `
-Proxy $Proxy `
-ProxyCredential $ProxyCredential `
-CallerPSCmdlet $PSCmdlet
@@ -8663,7 +8717,7 @@ function Add-PackageSource
-ExceptionObject $Name
}
- $LocationString = Get-ValidModuleLocation -LocationString $Location -ParameterName "Location" -Proxy $Proxy -ProxyCredential $ProxyCredential
+ $LocationString = Get-ValidModuleLocation -LocationString $Location -ParameterName "Location" -Proxy $Proxy -ProxyCredential $ProxyCredential -Credential $Credential
# Check if Location is already registered with another Name
$existingSourceName = Get-SourceName -Location $LocationString
@@ -8866,7 +8920,7 @@ function Add-PackageSource
if(-not $ScriptSourceLocation)
{
- $ScriptSourceLocation = Get-ScriptSourceLocation -Location $LocationString -Proxy $Proxy -ProxyCredential $ProxyCredential
+ $ScriptSourceLocation = Get-ScriptSourceLocation -Location $LocationString -Proxy $Proxy -ProxyCredential $ProxyCredential -Credential $Credential
}
elseif($Options.ContainsKey($script:ScriptSourceLocation))
{
@@ -11726,6 +11780,9 @@ function Get-ValidModuleLocation
[string]
$ParameterName,
+ [Parameter()]
+ $Credential,
+
[Parameter()]
$Proxy,
@@ -11764,6 +11821,7 @@ function Get-ValidModuleLocation
# Ping and resolve the specified location
$tempLocation = Resolve-Location -Location $tempLocation `
-LocationParameterName $ParameterName `
+ -Credential $Credential `
-Proxy $Proxy `
-ProxyCredential $ProxyCredential `
-ErrorAction SilentlyContinue `
@@ -11779,6 +11837,7 @@ function Get-ValidModuleLocation
# Ping and resolve the specified location
$LocationString = Resolve-Location -Location $LocationString `
-LocationParameterName $ParameterName `
+ -Credential $Credential `
-Proxy $Proxy `
-ProxyCredential $ProxyCredential `
-CallerPSCmdlet $PSCmdlet
@@ -13306,6 +13365,9 @@ function Get-ScriptSourceLocation
[String]
$Location,
+ [Parameter()]
+ $Credential,
+
[Parameter()]
$Proxy,
@@ -13340,6 +13402,7 @@ function Get-ScriptSourceLocation
# Ping and resolve the specified location
$scriptLocation = Resolve-Location -Location $tempScriptLocation `
-LocationParameterName 'ScriptSourceLocation' `
+ -Credential $Credential `
-Proxy $Proxy `
-ProxyCredential $ProxyCredential `
-ErrorAction SilentlyContinue `
@@ -13407,6 +13470,9 @@ function Resolve-Location
[string]
$LocationParameterName,
+ [Parameter()]
+ $Credential,
+
[Parameter()]
$Proxy,
@@ -13438,7 +13504,7 @@ function Resolve-Location
}
else
{
- $pingResult = Ping-Endpoint -Endpoint $Location -Proxy $Proxy -ProxyCredential $ProxyCredential
+ $pingResult = Ping-Endpoint -Endpoint $Location -Credential $Credential -Proxy $Proxy -ProxyCredential $ProxyCredential
$statusCode = $null
$exception = $null
$resolvedLocation = $null
diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs
index 319e359ffa..185cdc172b 100644
--- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs
+++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs
@@ -1753,41 +1753,6 @@ namespace System.Management.Automation.Tracing
#endif
-namespace Microsoft.PowerShell.Commands
-{
- using System.Management.Automation;
-
- ///
- ///
- ///
- public sealed class GetPSSnapinCommand : PSCmdlet
- {
- ///
- /// Name(s) of PSSnapIn(s).
- ///
- [Parameter(Position = 0, Mandatory = false)]
- public string[] Name
- {
- get
- {
- return _pssnapins;
- }
- set
- {
- _pssnapins = value;
- }
- }
- private string[] _pssnapins;
-
- ///
- ///
- ///
- protected override void EndProcessing()
- {
- }
- }
-}
-
namespace Microsoft.PowerShell
{
internal static class NativeCultureResolver
diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs
index 37abd6bbac..f12bbdd6fb 100644
--- a/src/System.Management.Automation/engine/InitialSessionState.cs
+++ b/src/System.Management.Automation/engine/InitialSessionState.cs
@@ -6132,6 +6132,7 @@ if($paths) {
{"New-PSSession", new SessionStateCmdletEntry("New-PSSession", typeof(NewPSSessionCommand), helpFile) },
{"New-PSSessionConfigurationFile", new SessionStateCmdletEntry("New-PSSessionConfigurationFile", typeof(NewPSSessionConfigurationFileCommand), helpFile) },
{"New-PSSessionOption", new SessionStateCmdletEntry("New-PSSessionOption", typeof(NewPSSessionOptionCommand), helpFile) },
+ {"New-PSTransportOption", new SessionStateCmdletEntry("New-PSTransportOption", typeof(NewPSTransportOptionCommand), helpFile) },
{"Out-Default", new SessionStateCmdletEntry("Out-Default", typeof(OutDefaultCommand), helpFile) },
{"Out-Host", new SessionStateCmdletEntry("Out-Host", typeof(OutHostCommand), helpFile) },
{"Out-Null", new SessionStateCmdletEntry("Out-Null", typeof(OutNullCommand), helpFile) },
@@ -6160,7 +6161,6 @@ if($paths) {
{"Enable-PSRemoting", new SessionStateCmdletEntry("Enable-PSRemoting", typeof(EnablePSRemotingCommand), helpFile) },
{"Export-Console", new SessionStateCmdletEntry("Export-Console", typeof(ExportConsoleCommand), helpFile) },
{"Get-PSSnapin", new SessionStateCmdletEntry("Get-PSSnapin", typeof(GetPSSnapinCommand), helpFile) },
- {"New-PSTransportOption", new SessionStateCmdletEntry("New-PSTransportOption", typeof(NewPSTransportOptionCommand), helpFile) },
{"Remove-PSSnapin", new SessionStateCmdletEntry("Remove-PSSnapin", typeof(RemovePSSnapinCommand), helpFile) },
{"Resume-Job", new SessionStateCmdletEntry("Resume-Job", typeof(ResumeJobCommand), helpFile) },
{"Suspend-Job", new SessionStateCmdletEntry("Suspend-Job", typeof(SuspendJobCommand), helpFile) },
diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs
index dcb967760f..28669cb69f 100644
--- a/src/System.Management.Automation/engine/LanguagePrimitives.cs
+++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs
@@ -482,7 +482,6 @@ namespace System.Management.Automation
}
#if !CORECLR
- // .NET Core does not have a full DataTable type
static IEnumerable DataTableEnumerable(object obj)
{
return (((DataTable)obj).Rows);
@@ -526,7 +525,6 @@ namespace System.Management.Automation
static GetEnumerableDelegate CalculateGetEnumerable(Type objectType)
{
#if !CORECLR
- // .NET Core does not have a full DataTable type
if (typeof(DataTable).IsAssignableFrom(objectType))
{
return LanguagePrimitives.DataTableEnumerable;
diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs
index aea5ad8921..2e5562d38d 100644
--- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs
+++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs
@@ -672,44 +672,19 @@ namespace Microsoft.PowerShell.Commands
// Check if module could be a snapin. This was the case for PowerShell version 2 engine modules.
if (InitialSessionState.IsEngineModule(name))
{
- CmdletInfo cmdletInfo = Context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-PSSnapIn");
- if (cmdletInfo != null && cmdletInfo.Visibility == SessionStateEntryVisibility.Public)
+ PSSnapInInfo snapin = ModuleCmdletBase.GetEngineSnapIn(Context, name);
+
+ // Return the command if we found a module
+ if (snapin != null)
{
- CommandInfo commandInfo = new CmdletInfo("Get-PSSnapIn",
- typeof(Microsoft.PowerShell.Commands.GetPSSnapinCommand),
- null, null, Context);
- Command getPSSnapInCommand = new Command(commandInfo);
-
- Collection matchingSnapins = null;
-
- try
- {
- using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
- {
- powerShell.AddCommand(getPSSnapInCommand)
- .AddParameter("Name", name)
- .AddParameter("ErrorAction", ActionPreference.Ignore);
- matchingSnapins = powerShell.Invoke();
- }
- }
- catch (Exception e)
- {
- // Call-out to user code, catch-all OK
- CommandProcessorBase.CheckForSevereException(e);
- }
-
- // Return the command if we found a module
- if (matchingSnapins != null && matchingSnapins.Count == 1)
- {
- // warn that this module already exists as a snapin
- string warningMessage = string.Format(
- CultureInfo.InvariantCulture,
- Modules.ModuleLoadedAsASnapin,
- matchingSnapins[0].Name);
- WriteWarning(warningMessage);
- found = true;
- return foundModule;
- }
+ // warn that this module already exists as a snapin
+ string warningMessage = string.Format(
+ CultureInfo.InvariantCulture,
+ Modules.ModuleLoadedAsASnapin,
+ snapin.Name);
+ WriteWarning(warningMessage);
+ found = true;
+ return foundModule;
}
}
diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs
index ac692127da..fb6c1c372b 100644
--- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs
+++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs
@@ -4089,27 +4089,10 @@ namespace Microsoft.PowerShell.Commands
// If the RequiredModule is one of the Engine modules, then they could have been loaded as snapins (using RunspaceConfiguration or InitialSessionState.CreateDefault())
if (result == null && InitialSessionState.IsEngineModule(requiredModule.Name))
{
- using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
+ result = ModuleCmdletBase.GetEngineSnapIn(context, requiredModule.Name);
+ if (result != null)
{
- Collection loadedSnapins = null;
- powerShell.AddCommand("Get-PSSnapin");
- powerShell.AddParameter("Name", requiredModule.Name);
- try
- {
- loadedSnapins = powerShell.Invoke();
- }
- catch (Exception e)
- {
- // Catch-all OK, third-party call-out.
- CommandProcessorBase.CheckForSevereException(e);
- }
-
- if (loadedSnapins != null && loadedSnapins.Count > 0)
- {
- Dbg.Assert(loadedSnapins.Count == 1, " There should only be one snapin by name " + requiredModule.Name);
- result = loadedSnapins[0];
- loaded = true;
- }
+ loaded = true;
}
}
@@ -7814,6 +7797,30 @@ namespace Microsoft.PowerShell.Commands
return;
}
}
+
+ ///
+ /// Search a PSSnapin with the specified name
+ ///
+ internal static PSSnapInInfo GetEngineSnapIn(ExecutionContext context, string name)
+ {
+ HashSet snapinSet = new HashSet();
+ List cmdlets = context.SessionState.InvokeCommand.GetCmdlets();
+ foreach (CmdletInfo cmdlet in cmdlets)
+ {
+ PSSnapInInfo snapin = cmdlet.PSSnapIn;
+ if (snapin != null && !snapinSet.Contains(snapin))
+ snapinSet.Add(snapin);
+ }
+
+ foreach (PSSnapInInfo snapin in snapinSet)
+ {
+ if (string.Equals(snapin.Name, name, StringComparison.OrdinalIgnoreCase))
+ return snapin;
+ }
+
+ return null;
+ }
+
} // end ModuleCmdletBase
///
diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs
index 66246e747c..5cc6d8134c 100644
--- a/src/System.Management.Automation/engine/SessionStateContainer.cs
+++ b/src/System.Management.Automation/engine/SessionStateContainer.cs
@@ -5008,12 +5008,13 @@ namespace System.Management.Automation
null);
string providerPath = null;
+ bool pathNotFoundOnClient = false;
try
{
Collection providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
- !RemoteCopyOperation(context),
+ true,
newContext,
out provider,
out providerInstance);
@@ -5021,13 +5022,26 @@ namespace System.Management.Automation
if (providerPaths.Count > 0)
providerPath = providerPaths[0];
}
+
catch (DriveNotFoundException)
{
// This exception is expected for remote sessions where drives exist in a remote session but not
- // on the client. But we don't know if this is a remote use of copy-item because the FromSession
+ // on the client.
+ pathNotFoundOnClient = true;
+ }
+ catch (ItemNotFoundException)
+ {
+ // This exception is expected for remote sessions where item exist in a remote session but not
+ // on the client.
+ pathNotFoundOnClient = true;
+ }
+
+ if (pathNotFoundOnClient)
+ {
+ // At this point, we don't know if this is a remote use of copy-item because the FromSession
// and ToSession dynamic parameters have not been retrieved yet.
- // Ignore the exception and use the FileSystem provider as default. If this is a real drive issue
- // it will be caught later when the drive path is used.
+ // Ignore these exceptions and use the FileSystem provider as default. If this is a real drive
+ // issue, or if the item does not exist, it will be caught later when the drive or item path is used.
var fileSystemProviders = Providers["FileSystem"];
if (fileSystemProviders.Count > 0)
{
@@ -5283,17 +5297,6 @@ namespace System.Management.Automation
return true;
}
- private bool RemoteCopyOperation(CmdletProviderContext context)
- {
- Microsoft.PowerShell.Commands.CopyItemDynamicParameters dynamicParams = context.DynamicParameters as Microsoft.PowerShell.Commands.CopyItemDynamicParameters;
-
- if (dynamicParams != null)
- {
- return ((dynamicParams.FromSession != null) || (dynamicParams.ToSession != null));
- }
-
- return false;
- }
#endregion CopyItem
#endregion ContainerCmdletProvider accessors
diff --git a/src/System.Management.Automation/engine/Types_Ps1Xml.generated.cs b/src/System.Management.Automation/engine/Types_Ps1Xml.generated.cs
index 5f0e7a90f1..f7e8b80742 100644
--- a/src/System.Management.Automation/engine/Types_Ps1Xml.generated.cs
+++ b/src/System.Management.Automation/engine/Types_Ps1Xml.generated.cs
@@ -53,7 +53,7 @@ namespace System.Management.Automation.Runspaces
[Microsoft.PowerShell.Commands.FileSystemProvider])
{
$driveRoot = ([System.IO.DirectoryInfo] $this.Root).Name.Replace('\','')
- $drive = Get-WmiObject Win32_LogicalDisk -Filter ""DeviceId='$driveRoot'""
+ $drive = Get-CimInstance Win32_LogicalDisk -Filter ""DeviceId='$driveRoot'""
$drive.Size - $drive.FreeSpace
}"), null));
td4.Members.Add("Free",
@@ -62,7 +62,7 @@ namespace System.Management.Automation.Runspaces
[Microsoft.PowerShell.Commands.FileSystemProvider])
{
$driveRoot = ([System.IO.DirectoryInfo] $this.Root).Root.Name.Replace('\','')
- $drive = Get-WmiObject Win32_LogicalDisk -Filter ""DeviceId='$driveRoot'""
+ $drive = Get-CimInstance Win32_LogicalDisk -Filter ""DeviceId='$driveRoot'""
$drive.FreeSpace
}"), null));
yield return td4;
diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs
index c66853dbb7..25ec05acca 100644
--- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs
+++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs
@@ -746,6 +746,8 @@ namespace System.Management.Automation.Runspaces
throw initError;
}
}
+
+ TelemetryAPI.ReportLocalSessionCreated(InitialSessionState, TranscriptionData);
}
///
diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs
index edefc1874e..3b2d70a608 100644
--- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs
+++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs
@@ -14,6 +14,7 @@ using System.Management.Automation.Runspaces.Internal;
using System.Management.Automation.Host;
using System.Collections.ObjectModel;
using System.Management.Automation.Remoting.Client;
+using Microsoft.PowerShell.Telemetry.Internal;
namespace System.Management.Automation.Runspaces.Internal
{
@@ -884,6 +885,8 @@ namespace System.Management.Automation.Runspaces.Internal
PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolOpen, PSOpcode.Open,
PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational);
+ TelemetryAPI.ReportRemoteSessionCreated(connectionInfo);
+
lock (syncObject)
{
AssertIfStateIsBeforeOpen();
diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs
index 44c3b41d92..a1e7b64ac3 100644
--- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs
+++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs
@@ -248,7 +248,7 @@ function Register-PSSessionConfiguration
if ($?){{
try{{
$s = New-PSSession -ComputerName localhost -ConfigurationName $pluginName -ErrorAction Stop
- # session is ok, no need to restart WinRM service
+ # session is ok, no need to restart WinRM service
Remove-PSSession $s -Confirm:$false
}}catch{{
# session is NOT ok, we need to restart winrm if -Force was specified, otherwise show a warning
@@ -577,6 +577,15 @@ else
ArrayList errorList = (ArrayList)Context.DollarErrorVariable;
int errorCountBefore = errorList.Count;
+ if (force &&
+ this.Context != null &&
+ this.Context.EngineHostInterface != null &&
+ this.Context.EngineHostInterface.ExternalHost != null &&
+ this.Context.EngineHostInterface.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost)
+ {
+ WriteWarning(RemotingErrorIdStrings.WinRMForceRestartWarning);
+ }
+
newPluginSb.InvokeUsingCmdlet(
contextCmdlet: this,
useLocalScope: true,
diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs
index 5172c87d86..6bc09b8b90 100644
--- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs
+++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs
@@ -402,10 +402,8 @@ namespace Microsoft.PowerShell.Commands
///
/// Command to create an object for WSManConfigurationOption
///
-#if !CORECLR
[Cmdlet(VerbsCommon.New, "PSTransportOption", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=210608", RemotingCapability = RemotingCapability.None)]
[OutputType(typeof(WSManConfigurationOption))]
-#endif
public sealed class NewPSTransportOptionCommand : PSCmdlet
{
private WSManConfigurationOption option = new WSManConfigurationOption();
diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs
index 48cae60f6b..87106f6ede 100644
--- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs
+++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs
@@ -96,9 +96,11 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
- [Parameter(ValueFromPipelineByPropertyName = true,
+ [Parameter(Mandatory = true,
+ ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
- [Parameter(ValueFromPipelineByPropertyName = true,
+ [Parameter(Mandatory = true,
+ ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
[Credential()]
public override PSCredential Credential
@@ -156,7 +158,9 @@ namespace Microsoft.PowerShell.Commands
/// i.e., allows going off box. When this property is true and a PSSession is disconnected,
/// reconnection is allowed only if reconnecting from a PowerShell session on the same box.
///
- [Parameter()]
+ [Parameter(ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)]
+ [Parameter(ParameterSetName = NewPSSessionCommand.SessionParameterSet)]
+ [Parameter(ParameterSetName = NewPSSessionCommand.UriParameterSet)]
public SwitchParameter EnableNetworkAccess
{
get { return enableNetworkAccess; }
diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs
index 044d7e5403..202bc4304e 100644
--- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs
+++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs
@@ -278,6 +278,18 @@ namespace System.Management.Automation.Remoting
_streamReader = new StreamReader(_networkStream);
_streamWriter = new StreamWriter(_networkStream);
_streamWriter.AutoFlush = true;
+
+ //
+ // listenSocket is not closed when it goes out of scope here. Sometimes it is
+ // closed later in this thread, while other times it is not closed at all. This will
+ // cause problem when we set up a second PowerShell Direct session. Let's
+ // explicitly close listenSocket here for safe.
+ //
+ if (listenSocket != null)
+ {
+ try { listenSocket.Dispose(); }
+ catch (ObjectDisposedException) { }
+ }
}
catch (Exception e)
{
@@ -533,6 +545,15 @@ namespace System.Management.Automation.Remoting
bool isFirstConnection)
{
bool result = false;
+
+ //
+ // Check invalid input and throw exception before setting up socket connection.
+ //
+ if (String.IsNullOrEmpty(networkCredential.UserName))
+ {
+ throw new PSDirectException(
+ PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidUsername));
+ }
_socket.Connect(_endPoint);
@@ -550,16 +571,6 @@ namespace System.Management.Automation.Remoting
networkCredential.Domain = "localhost";
}
- if (String.IsNullOrEmpty(networkCredential.UserName))
- {
- throw new PSInvalidOperationException(
- PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidUsername),
- null,
- PSRemotingErrorId.InvalidUsername.ToString(),
- ErrorCategory.InvalidOperation,
- null);
- }
-
bool emptyPassword = String.IsNullOrEmpty(networkCredential.Password);
bool emptyConfiguration = String.IsNullOrEmpty(configurationName);
diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs
index 89bfdf8784..c39c53b5fe 100644
--- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs
+++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs
@@ -1217,25 +1217,20 @@ namespace System.Management.Automation.Remoting
#region Constructors
///
- /// Constructor. Creates Named Pipe based on process Id, app domain name and container id.
+ /// Constructor. Creates Named Pipe based on process Id, app domain name and container Guid.
///
/// Target process Id for pipe.
/// AppDomain name or null for default AppDomain
- /// Container Id.
+ /// Container Guid.
public ContainerSessionNamedPipeClient(
int procId,
string appDomainName,
- string containerId)
+ Guid containerGuid)
{
- if (String.IsNullOrEmpty(containerId))
- {
- throw new PSArgumentNullException("containerId");
- }
-
//
// Named pipe inside Windows Server container is under different name space.
//
- _pipeName = @"\\.\Containers\" + containerId + @"\Device\NamedPipe\" +
+ _pipeName = @"\\.\Containers\" + containerGuid.ToString() + @"\Device\NamedPipe\" +
NamedPipeUtils.CreateProcessPipeName(procId, appDomainName);
}
diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs
index 516591e21e..48bfc628c5 100644
--- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs
+++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs
@@ -2240,7 +2240,7 @@ namespace System.Management.Automation.Runspaces
bool runAsAdmin,
string configurationName)
{
- ContainerProcess containerProc = new ContainerProcess(containerId, null, 0, runAsAdmin, configurationName);
+ ContainerProcess containerProc = new ContainerProcess(containerId, null, Guid.Empty, 0, runAsAdmin, configurationName);
return new ContainerConnectionInfo(containerProc);
}
@@ -2253,7 +2253,7 @@ namespace System.Management.Automation.Runspaces
bool runAsAdmin,
string configurationName)
{
- ContainerProcess containerProc = new ContainerProcess(null, containerName, 0, runAsAdmin, configurationName);
+ ContainerProcess containerProc = new ContainerProcess(null, containerName, Guid.Empty, 0, runAsAdmin, configurationName);
return new ContainerConnectionInfo(containerProc);
}
@@ -2288,8 +2288,9 @@ namespace System.Management.Automation.Runspaces
#region Private Data
private Guid runtimeId;
+ private Guid containerGuid = Guid.Empty;
private string containerId;
- private string containerName;
+ private string containerName;
private int processId;
private bool runAsAdmin = false;
private string configurationName;
@@ -2318,6 +2319,15 @@ namespace System.Management.Automation.Runspaces
set { runtimeId = value; }
}
+ ///
+ /// Guid of the container.
+ ///
+ public Guid ContainerGuid
+ {
+ get { return containerGuid; }
+ set { containerGuid = value; }
+ }
+
///
/// ID of the container.
///
@@ -2413,10 +2423,11 @@ namespace System.Management.Automation.Runspaces
///
/// Creates an instance used for PowerShell Direct for container.
///
- public ContainerProcess(string containerId, string containerName, int processId, bool runAsAdmin, string configurationName)
+ public ContainerProcess(string containerId, string containerName, Guid containerGuid, int processId, bool runAsAdmin, string configurationName)
{
this.ContainerId = containerId;
this.ContainerName = containerName;
+ this.ContainerGuid = containerGuid;
this.ProcessId = processId;
this.RunAsAdmin = runAsAdmin;
this.ConfigurationName = configurationName;
@@ -2425,12 +2436,12 @@ namespace System.Management.Automation.Runspaces
{
if (String.IsNullOrEmpty(containerName))
{
- GetContainerNameFromContainerId();
+ GetContainerPropertiesFromContainerId();
}
}
else if (!String.IsNullOrEmpty(containerName))
{
- GetContainerIdFromContainerName();
+ GetContainerPropertiesFromContainerName();
}
else
{
@@ -2486,11 +2497,11 @@ namespace System.Management.Automation.Runspaces
}
///
- /// Get container name based on given container id.
+ /// Get container name and Guid based on given container id.
///
- public void GetContainerNameFromContainerId()
+ public void GetContainerPropertiesFromContainerId()
{
- RunOnMTAThread(GetContainerNameFromContainerIdInternal);
+ RunOnMTAThread(GetContainerPropertiesFromContainerIdInternal);
//
// Report error.
@@ -2509,11 +2520,11 @@ namespace System.Management.Automation.Runspaces
}
///
- /// Get container id based on given container name.
+ /// Get container id and Guid based on given container name.
///
- public void GetContainerIdFromContainerName()
+ public void GetContainerPropertiesFromContainerName()
{
- RunOnMTAThread(GetContainerIdFromContainerNameInternal);
+ RunOnMTAThread(GetContainerPropertiesFromContainerNameInternal);
//
// Report error.
@@ -2611,7 +2622,9 @@ namespace System.Management.Automation.Runspaces
}
}
catch (Exception e)
- {
+ {
+ CommandProcessorBase.CheckForSevereException(e);
+
if (e is FileNotFoundException || e is FileLoadException)
{
//
@@ -2646,9 +2659,9 @@ namespace System.Management.Automation.Runspaces
}
///
- /// Get container name based on given container id.
+ /// Get container name and Guid based on given container id.
///
- private void GetContainerNameFromContainerIdInternal()
+ private void GetContainerPropertiesFromContainerIdInternal()
{
try
{
@@ -2661,8 +2674,16 @@ namespace System.Management.Automation.Runspaces
var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[]{ ContainerId });
- ContainerName = (string)computeSystemPropertiesType.GetProperty("SiloGuid").GetValue(computeSystemPropertiesHandle);
+ ContainerName = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(computeSystemPropertiesHandle);
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
+
+ //
+ // Get container Guid for Windows Server container.
+ //
+ if (RuntimeId == Guid.Empty)
+ {
+ ContainerGuid = new Guid((string)computeSystemPropertiesType.GetProperty("SiloGuid").GetValue(computeSystemPropertiesHandle));
+ }
}
catch (FileNotFoundException)
{
@@ -2674,6 +2695,8 @@ namespace System.Management.Automation.Runspaces
}
catch (Exception e)
{
+ CommandProcessorBase.CheckForSevereException(e);
+
if (e.InnerException != null &&
StringComparer.Ordinal.Equals(
e.InnerException.GetType().FullName,
@@ -2690,9 +2713,9 @@ namespace System.Management.Automation.Runspaces
}
///
- /// Get container id based on given container name.
+ /// Get container id and Guid based on given container name.
///
- private void GetContainerIdFromContainerNameInternal()
+ private void GetContainerPropertiesFromContainerNameInternal()
{
try
{
@@ -2734,6 +2757,14 @@ namespace System.Management.Automation.Runspaces
ContainerId = (string)computeSystemPropertiesType.GetProperty("Id").GetValue(computeSystemPropertiesHandle);
ContainerName = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(computeSystemPropertiesHandle);
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
+
+ //
+ // Get container Guid for Windows Server container.
+ //
+ if (RuntimeId == Guid.Empty)
+ {
+ ContainerGuid = new Guid((string)computeSystemPropertiesType.GetProperty("SiloGuid").GetValue(computeSystemPropertiesHandle));
+ }
}
catch (FileNotFoundException)
{
@@ -2745,6 +2776,8 @@ namespace System.Management.Automation.Runspaces
}
catch (Exception e)
{
+ CommandProcessorBase.CheckForSevereException(e);
+
ErrorCode = OtherError;
ErrorMessage = GetErrorMessageFromException(e);
}
diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs
index cf7e5d7eab..793df88f07 100644
--- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs
+++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs
@@ -1636,7 +1636,7 @@ namespace System.Management.Automation.Remoting.Client
_clientPipe = new ContainerSessionNamedPipeClient(
_connectionInfo.ContainerProc.ProcessId,
string.Empty, // AppDomainName
- _connectionInfo.ContainerProc.ContainerId);
+ _connectionInfo.ContainerProc.ContainerGuid);
// Wait for named pipe to connect.
_clientPipe.Connect(_connectionInfo.OpenTimeout);
diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs
index 9a9ef31e83..16acec3253 100644
--- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs
+++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs
@@ -556,7 +556,7 @@ namespace System.Management.Automation.Language
}
#if !CORECLR
- // .NET Core does not have a full DataTable type
+ // In CORECLR System.Data.DataTable does not have the DataRowCollection IEnumerable, so disabling code.
if (targetValue is DataTable)
{
// Generate:
diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs
index 7b28678604..b7e9816758 100644
--- a/src/System.Management.Automation/help/CommandHelpProvider.cs
+++ b/src/System.Management.Automation/help/CommandHelpProvider.cs
@@ -566,7 +566,7 @@ namespace System.Management.Automation
// This is the path to the help file.
string location = null;
- if (helpFile.EndsWith(".ni.dll-Help.xml"))
+ if (helpFile.EndsWith(".ni.dll-Help.xml", StringComparison.OrdinalIgnoreCase))
{
// For PowerShell on OneCore, we ship Ngen binaries. As a result, the name of the assembly now contains '.ni' on it,
// e.g., .ni.dll as supposed to .dll.
diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs
index 6dc033623b..65541d578a 100644
--- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs
+++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs
@@ -1896,11 +1896,8 @@ namespace Microsoft.PowerShell.Commands
}
// Verify that the target doesn't represent a device name
- if (Utils.IsReservedDeviceName(newName))
+ if (PathIsReservedDeviceName(newName, "RenameError"))
{
- String error = StringUtil.Format(FileSystemProviderStrings.TargetCannotContainDeviceName, newName);
- Exception e = new IOException(error);
- WriteError(new ErrorRecord(e, "RenameError", ErrorCategory.WriteError, newName));
return;
}
@@ -3787,11 +3784,8 @@ namespace Microsoft.PowerShell.Commands
}
// Verify that the target doesn't represent a device name
- if (Utils.IsReservedDeviceName(destinationPath))
+ if (PathIsReservedDeviceName(destinationPath, "CopyError"))
{
- String error = StringUtil.Format(FileSystemProviderStrings.TargetCannotContainDeviceName, destinationPath);
- Exception e = new IOException(error);
- WriteError(new ErrorRecord(e, "CopyError", ErrorCategory.WriteError, destinationPath));
return;
}
}
@@ -4110,15 +4104,20 @@ namespace Microsoft.PowerShell.Commands
{
Dbg.Diagnostics.Assert(sourceFileFullName != null, "The caller should verify file.");
- // If the destination directory does not exist, error out.
- if(!Utils.NativeDirectoryExists(destinationPath))
+ // If the destination is a container, add the file name
+ // to the destination path.
+ if (IsItemContainer(destinationPath))
+ {
+ destinationPath = MakePath(destinationPath, sourceFileName);
+ }
+
+ // Verify that the target doesn't represent a device name
+ if (PathIsReservedDeviceName(destinationPath, "CopyError"))
{
- Exception e = new IOException(String.Format(CultureInfo.InvariantCulture, FileSystemProviderStrings.CopyItemDirectoryNotFound, destinationPath));
- WriteError(new ErrorRecord(e, "DirectoryNotFound", ErrorCategory.WriteError, destinationPath));
return;
}
- FileInfo destinationFile = new FileInfo(Path.Combine(destinationPath, sourceFileName));
+ FileInfo destinationFile = new FileInfo(destinationPath);
string action = FileSystemProviderStrings.CopyItemActionFile;
string resource = StringUtil.Format(FileSystemProviderStrings.CopyItemResourceFileTemplate, sourceFileFullName, destinationPath);
@@ -4350,6 +4349,61 @@ namespace Microsoft.PowerShell.Commands
return supportsAlternateStreams;
}
+ // Validate that the given remotePath exists, and do the following:
+ // 1) If the remotePath is a FileInfo, then just return the remotePath.
+ // 2) If the remotePath is a DirectoryInfo, then return the remotePath + the given filename.
+ // 3) If the remote path does not exist, but its parent does, and it is a DirectoryInfo, then return the remotePath.
+ // 4) If the remotePath or its parent do not exist, return null.
+ private string MakeRemotePath(System.Management.Automation.PowerShell ps, string remotePath, string filename)
+ {
+ bool isFileInfo = false;
+ bool isDirectoryInfo = false;
+ bool parentIsDirectoryInfo = false;
+ string path = null;
+
+ ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName);
+ ps.AddParameter("remotePath", remotePath);
+ Hashtable op = SafeInvokeCommand.Invoke(ps, this, null);
+
+ if (op != null)
+ {
+ if (op["IsDirectoryInfo"] != null)
+ {
+ isDirectoryInfo = (bool) op["IsDirectoryInfo"];
+ }
+ if (op["IsFileInfo"] != null)
+ {
+ isFileInfo = (bool) op["IsFileInfo"];
+ }
+ if (op["ParentIsDirectoryInfo"] != null)
+ {
+ parentIsDirectoryInfo = (bool)op["ParentIsDirectoryInfo"];
+ }
+ }
+
+ if (isFileInfo)
+ {
+ // The destination is a file, so we are going to overwrite it.
+ path = remotePath;
+ }
+ else if (isDirectoryInfo)
+ {
+ // The destination is a directory, so append the file name to the path.
+ path = Path.Combine(remotePath, filename);
+ }
+ else if (parentIsDirectoryInfo)
+ {
+ // At this point we know that the remotePath is neither a file or a directory on the remote target.
+ // However, if the parent of the remotePath exists, then we are doing a copy-item operation in which
+ // the destination file name is already being passed, e.g.,
+ // copy-item -path c:\localDir\foo.txt -destination d:\remoteDir\bar.txt -toSession $s
+ // Note that d:\remoteDir is a directory that exists on the remote target machine.
+ path = remotePath;
+ }
+
+ return path;
+ }
+
private bool RemoteDirectoryExist(System.Management.Automation.PowerShell ps, string path)
{
bool pathExists = false;
@@ -4378,9 +4432,6 @@ namespace Microsoft.PowerShell.Commands
"localhost",
ps.Runspace.ConnectionInfo.ComputerName);
- // The destinationPath was verified by the caller so we can create the final filePath here.
- var filePath = Path.Combine(destinationPath, file.Name);
-
ProgressRecord progress = new ProgressRecord(0, activity, statusDescription);
progress.PercentComplete = 0;
progress.RecordType = ProgressRecordType.Processing;
@@ -4441,14 +4492,31 @@ namespace Microsoft.PowerShell.Commands
if (!isAlternateStream)
{
ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName);
- ps.AddParameter("copyToFilePath", filePath);
- ps.AddParameter("b64Fragment", b64Fragment);
- ps.AddParameter("createFile", (iteration == 1) ? true : false);
+ ps.AddParameter("copyToFilePath", destinationPath);
+ ps.AddParameter("createFile", (iteration == 1));
+
+ if ((iteration == 1) && (b64Fragment.Length == 0))
+ {
+ // This fixes the case in which the user tries to copy an empty file between sessions.
+ // Scenario 1: The user creates an empty file using the Out-File cmdlet.
+ // In this case the file length is 6.
+ // "" | out-file test.txt
+ // Scenario 2: The user generates an empty file using the New-Item cmdlet.
+ // In this case the file length is 0.
+ // New-Item -Path test.txt -Type File
+ // Because of this, when we create the file on the remote session, we need to check
+ // the length of b64Fragment to figure out if we are creating an empty file.
+ ps.AddParameter("emptyFile", true);
+ }
+ else
+ {
+ ps.AddParameter("b64Fragment", b64Fragment);
+ }
}
else
{
ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName);
- ps.AddParameter("copyToFilePath", filePath);
+ ps.AddParameter("copyToFilePath", destinationPath);
ps.AddParameter("b64Fragment", b64Fragment);
ps.AddParameter("streamName", streamName);
}
@@ -4540,17 +4608,19 @@ namespace Microsoft.PowerShell.Commands
private bool PerformCopyFileToRemoteSession(FileInfo file, string destinationPath, System.Management.Automation.PowerShell ps)
{
- // Validate the the destination directory exist on the remote target.
- if (!RemoteDirectoryExist(ps, destinationPath))
+ // Make the remote path
+ var remoteFilePath = MakeRemotePath(ps, destinationPath, file.Name);
+
+ if (String.IsNullOrEmpty(remoteFilePath))
{
- Exception e = new IOException(String.Format(CultureInfo.InvariantCulture, FileSystemProviderStrings.CopyItemDirectoryNotFound, destinationPath));
- WriteError(new ErrorRecord(e, "RemoteDirectoryNotFound", ErrorCategory.WriteError, destinationPath));
+ Exception e = new ArgumentException(String.Format(CultureInfo.InvariantCulture, SessionStateStrings.PathNotFound, destinationPath));
+ WriteError(new ErrorRecord(e, "RemotePathNotFound", ErrorCategory.WriteError, destinationPath));
return false;
}
- bool result = CopyFileStreamToRemoteSession(file, destinationPath, ps, false, null);
+ bool result = CopyFileStreamToRemoteSession(file, remoteFilePath, ps, false, null);
- bool targetSupportsAlternateStreams = RemoteTargetSupportsAlternateStreams(ps, Path.Combine(destinationPath, file.Name));
+ bool targetSupportsAlternateStreams = RemoteTargetSupportsAlternateStreams(ps, remoteFilePath);
// Once the file is copied sucessfully, check if the file has any alternate data streams
if (result && targetSupportsAlternateStreams)
@@ -4559,7 +4629,7 @@ namespace Microsoft.PowerShell.Commands
{
if (!(String.Equals(":$DATA", stream.Stream, StringComparison.OrdinalIgnoreCase)))
{
- result = CopyFileStreamToRemoteSession(file, destinationPath, ps, true, stream.Stream);
+ result = CopyFileStreamToRemoteSession(file, remoteFilePath, ps, true, stream.Stream);
if (!result)
{
break;
@@ -4635,6 +4705,21 @@ namespace Microsoft.PowerShell.Commands
return path;
} // CreateDirectoryOnRemoteSession
+ // Returns true if the destination path represents a device name, and write an error to the user.
+ private bool PathIsReservedDeviceName(string destinationPath, string errorId)
+ {
+ bool pathIsReservedDeviceName = false;
+ if (Utils.IsReservedDeviceName(destinationPath))
+ {
+ pathIsReservedDeviceName = true;
+ String error = StringUtil.Format(FileSystemProviderStrings.TargetCannotContainDeviceName, destinationPath);
+ Exception e = new IOException(error);
+ WriteError(new ErrorRecord(e, errorId, ErrorCategory.WriteError, destinationPath));
+ }
+
+ return pathIsReservedDeviceName;
+ }
+
#endregion CopyItem
#endregion ContainerCmdletProvider members
@@ -5573,15 +5658,11 @@ namespace Microsoft.PowerShell.Commands
destination = NormalizePath(destination);
// Verify that the target doesn't represent a device name
- if (Utils.IsReservedDeviceName(destination))
+ if (PathIsReservedDeviceName(destination, "MoveError"))
{
- String error = StringUtil.Format(FileSystemProviderStrings.TargetCannotContainDeviceName, destination);
- Exception e = new IOException(error);
- WriteError(new ErrorRecord(e, "MoveError", ErrorCategory.WriteError, destination));
return;
}
-
try
{
bool isContainer = IsItemContainer(path);
@@ -8772,7 +8853,7 @@ namespace System.Management.Automation.Internal
{0}
[string] $copyToFilePath,
- [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"", Mandatory=$true)]
+ [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"", Mandatory=$false)]
[Parameter(ParameterSetName=""PSCopyAlternateStreamToRemoteSession"")]
[ValidateNotNullOrEmpty()]
[string] $b64Fragment,
@@ -8780,6 +8861,9 @@ namespace System.Management.Automation.Internal
[Parameter(ParameterSetName=""PSCopyFileToRemoteSession"")]
[switch] $createFile = $false,
+ [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"")]
+ [switch] $emptyFile = $false,
+
[Parameter(ParameterSetName=""PSCopyAlternateStreamToRemoteSession"", Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string] $streamName,
@@ -8800,6 +8884,10 @@ namespace System.Management.Automation.Internal
{0}
[string] $isFilePath,
+ [Parameter(ParameterSetName=""PSGetRemotePathInfo"", Mandatory=$true)]
+ {0}
+ [string] $remotePath,
+
[Parameter(ParameterSetName=""PSCreateDirectoryOnRemoteSession"", Mandatory=$true)]
{0}
[string] $createDirectoryPath,
@@ -8840,9 +8928,10 @@ namespace System.Management.Automation.Internal
param(
[string] $copyToFilePath,
[string] $b64Fragment,
- [switch] $createFile = $false
+ [switch] $createFile = $false,
+ [switch] $emptyFile = $false
)
-
+
$op = @{{
BytesWritten = $null
}}
@@ -8851,9 +8940,6 @@ namespace System.Management.Automation.Internal
try
{{
- # Decode
- $fragment = [System.Convert]::FromBase64String($b64Fragment)
-
$filePathExists = Microsoft.PowerShell.Management\Test-Path -Path $copyToFilePath
if ($createFile -or (! $filePathExists))
@@ -8866,11 +8952,21 @@ namespace System.Management.Automation.Internal
# Create the new file.
$fileInfo = Microsoft.PowerShell.Management\New-Item -Path $copyToFilePath -Type File -Force
+
+ if ($emptyFile)
+ {{
+ # Handle the empty file scenario.
+ $op['BytesWritten'] = 0
+ return $op
+ }}
}}
# Resolve path in case it is a PSDrive
$resolvedPath = Microsoft.PowerShell.Management\Resolve-Path -literal $copyToFilePath
+ # Decode
+ $fragment = [System.Convert]::FromBase64String($b64Fragment)
+
# Check if drive specifies max size and if max size is exceeded
CheckPSDriveSize $resolvedPath $fragment.Length
@@ -9012,6 +9108,53 @@ namespace System.Management.Automation.Internal
}}
}}
+ # Returns a hashtable with the following member:
+ # IsFileInfo - boolean to keep track of whether the given path is a remote file.
+ # IsDirectoryInfo - boolean to keep track of whether the given path is a remote directory.
+ # ParentIsDirectoryInfo - boolean to keep track of whether the given parent path is a remote directory.
+ #
+ function PSGetRemotePathInfo
+ {{
+ param (
+ [string] $remotePath
+ )
+
+ try
+ {{
+
+ try
+ {{
+ $parentPath = Microsoft.PowerShell.Management\Split-Path $remotePath
+ }}
+ # catch everything and ignore the error.
+ catch {{}}
+
+ $result = @{{
+ IsFileInfo = (Microsoft.PowerShell.Management\Test-Path $remotePath -PathType Leaf)
+ IsDirectoryInfo = (Microsoft.PowerShell.Management\Test-Path $remotePath -PathType Container)
+ }}
+
+ if ($parentPath)
+ {{
+ $result['ParentIsDirectoryInfo'] = (Microsoft.PowerShell.Management\Test-Path $parentPath -PathType Container)
+ }}
+
+ }}
+ catch
+ {{
+ if ($_.Exception.InnerException)
+ {{
+ Microsoft.PowerShell.Utility\Write-Error -Exception $_.Exception.InnerException
+ }}
+ else
+ {{
+ Microsoft.PowerShell.Utility\Write-Error -Exception $_.Exception
+ }}
+ }}
+
+ return $result
+ }}
+
# Returns a hashtable with the following information:
# - IsFileInfotrue bool to keep track if the given destination is a FileInfo type.
function PSRemoteDestinationPathIsFile
@@ -9130,6 +9273,11 @@ namespace System.Management.Automation.Internal
return PSRemoteDestinationPathIsFile @params
}}
+ ""PSGetRemotePathInfo""
+ {{
+ return PSGetRemotePathInfo @params
+ }}
+
""PSCreateDirectoryOnRemoteSession""
{{
return PSCreateDirectoryOnRemoteSession @params
diff --git a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx
index 87aa7189a1..94d9dc9843 100644
--- a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx
+++ b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx
@@ -333,9 +333,6 @@
Remote copy with {0} is not supported.
-
- Destination folder '{0}' does not exist.
-
Failed to create directory '{0}' on remote destination.
diff --git a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx
index 4520901226..c097913b9e 100644
--- a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx
+++ b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx
@@ -935,6 +935,9 @@ Do you want to continue?
{0} may need to restart the WinRM service if a configuration using this name has recently been unregistered, certain system data structures may still be cached. In that case, a restart of WinRM may be required.
All WinRM sessions connected to Windows PowerShell session configurations, such as Microsoft.PowerShell and session configurations that are created with the Register-PSSessionConfiguration cmdlet, are disconnected.
+
+
+ You are running in a remote session and have selected the Force option which means the WinRM service may restart.If the WinRM service restarts then this remote session will be terminated and you will need to create a new session to continue
The job was null when trying to save identifiers. Specify a job to save its identifiers.
diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs
index b04c6ef5e1..4481b26d1a 100644
--- a/src/System.Management.Automation/security/nativeMethods.cs
+++ b/src/System.Management.Automation/security/nativeMethods.cs
@@ -463,7 +463,7 @@ namespace System.Management.Automation.Security
[DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern
- string CryptFindLocalizedName(string pwszCryptName);
+ IntPtr CryptFindLocalizedName(string pwszCryptName);
[DllImport(PinvokeDllNames.CryptAcquireContextDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern
diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs
index bda9917894..1d30f25e7e 100644
--- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs
+++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs
@@ -1408,13 +1408,12 @@ namespace System.Management.Automation
{
defaultMshSnapins = new List()
{
-#if !CORECLR //TODO:CORECLR - The 'Diagnostics' and 'Host' modules are not available on OneCore yet
new DefaultPSSnapInInformation("Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics", null,
"GetEventResources,Description", "GetEventResources,Vendor"),
- new DefaultPSSnapInInformation("Microsoft.PowerShell.CoreConsoleHost", "Microsoft.PowerShell.ConsoleHost", null,
+ new DefaultPSSnapInInformation("Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost", null,
"HostMshSnapInResources,Description","HostMshSnapInResources,Vendor"),
-#endif
+
CoreSnapin,
new DefaultPSSnapInInformation("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility", null,
@@ -1427,7 +1426,7 @@ namespace System.Management.Automation
"SecurityMshSnapInResources,Description","SecurityMshSnapInResources,Vendor")
};
-#if !CORECLR //TODO:CORECLR - The 'Microsoft.WSMan.Management' module will be available on OneCore soon
+#if !LINUX
if (!Utils.IsWinPEHost())
{
defaultMshSnapins.Add(new DefaultPSSnapInInformation("Microsoft.WSMan.Management", "Microsoft.WSMan.Management", null,
diff --git a/src/System.Management.Automation/utils/ExtensionMethods.cs b/src/System.Management.Automation/utils/ExtensionMethods.cs
index 32948d31fa..0e58cc55f4 100644
--- a/src/System.Management.Automation/utils/ExtensionMethods.cs
+++ b/src/System.Management.Automation/utils/ExtensionMethods.cs
@@ -29,8 +29,8 @@ namespace System.Management.Automation
internal static class EnumerableExtensions
{
+ // CORECLR has an implementation of Append built-in.
#if !CORECLR
- // Porting note: .NET Core has this, but full .NET does not
internal static IEnumerable Append(this IEnumerable collection, T element)
{
foreach (T t in collection)
@@ -38,7 +38,6 @@ namespace System.Management.Automation
yield return element;
}
#endif
-
internal static IEnumerable Prepend(this IEnumerable collection, T element)
{
yield return element;
diff --git a/src/System.Management.Automation/utils/PSTelemetryMethods.cs b/src/System.Management.Automation/utils/PSTelemetryMethods.cs
index 3aacd60832..38fd1093b9 100644
--- a/src/System.Management.Automation/utils/PSTelemetryMethods.cs
+++ b/src/System.Management.Automation/utils/PSTelemetryMethods.cs
@@ -189,6 +189,127 @@ namespace Microsoft.PowerShell.Telemetry.Internal
}
}
+ ///
+ /// Report that a new local session (runspace) is created
+ ///
+ internal static void ReportLocalSessionCreated(
+ System.Management.Automation.Runspaces.InitialSessionState iss,
+ System.Management.Automation.Host.TranscriptionData transcriptionData)
+ {
+ bool isConstrained = (iss != null) && (iss.DefaultCommandVisibility != SessionStateEntryVisibility.Public) && (iss.LanguageMode != PSLanguageMode.FullLanguage);
+ bool isTranscripting = (transcriptionData != null) && (transcriptionData.SystemTranscript != null);
+
+ TelemetryWrapper.TraceMessage("PSNewLocalSession", new
+ {
+ Constrained = isConstrained,
+ Transcripting = isTranscripting
+ });
+ }
+
+ enum RemoteSessionType
+ {
+ Unknown,
+ LocalProcess,
+ WinRMRemote,
+ HyperVRemote,
+ ContainerRemote
+ }
+
+ enum RemoteConfigurationType
+ {
+ Unknown,
+ PSDefault,
+ PSWorkflow,
+ ServerManagerWorkflow,
+ Custom
+ }
+
+ ///
+ /// Report that a new remote session (runspace) is created
+ ///
+ internal static void ReportRemoteSessionCreated(
+ System.Management.Automation.Runspaces.RunspaceConnectionInfo connectionInfo)
+ {
+ RemoteSessionType sessionType = RemoteSessionType.Unknown;
+ RemoteConfigurationType configurationType = RemoteConfigurationType.Unknown;
+ if (connectionInfo is System.Management.Automation.Runspaces.NewProcessConnectionInfo)
+ {
+ sessionType = RemoteSessionType.LocalProcess;
+ configurationType = RemoteConfigurationType.PSDefault;
+ }
+ else
+ {
+ System.Management.Automation.Runspaces.WSManConnectionInfo wsManConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.WSManConnectionInfo;
+ if (wsManConnectionInfo != null)
+ {
+ sessionType = RemoteSessionType.WinRMRemote;
+
+ // Parse configuration name from ShellUri:
+ // ShellUri = 'http://schemas.microsoft.com/powershell/Microsoft.PowerShell'
+ // ConfigName = 'Microsoft.PowerShell'
+ string configurationName = wsManConnectionInfo.ShellUri;
+ if (!string.IsNullOrEmpty(configurationName))
+ {
+ int index = configurationName.LastIndexOf('/');
+ if (index > -1)
+ {
+ configurationName = configurationName.Substring(index + 1);
+ }
+ }
+ configurationType = GetConfigurationTypefromName(configurationName);
+ }
+ else
+ {
+ System.Management.Automation.Runspaces.VMConnectionInfo vmConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.VMConnectionInfo;
+ if (vmConnectionInfo != null)
+ {
+ sessionType = RemoteSessionType.HyperVRemote;
+ configurationType = GetConfigurationTypefromName(vmConnectionInfo.ConfigurationName);
+ }
+ else
+ {
+ System.Management.Automation.Runspaces.ContainerConnectionInfo containerConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.ContainerConnectionInfo;
+ if (containerConnectionInfo != null)
+ {
+ sessionType = RemoteSessionType.ContainerRemote;
+ configurationType = GetConfigurationTypefromName(
+ (containerConnectionInfo.ContainerProc != null) ? containerConnectionInfo.ContainerProc.ConfigurationName : string.Empty);
+ }
+ }
+ }
+ }
+
+ TelemetryWrapper.TraceMessage("PSNewRemoteSession", new
+ {
+ Type = sessionType,
+ Configuration = configurationType
+ });
+ }
+
+ private static RemoteConfigurationType GetConfigurationTypefromName(string name)
+ {
+ string configName = (name != null) ? name.Trim() : string.Empty;
+
+ if (string.IsNullOrEmpty(configName) ||
+ configName.Equals("microsoft.powershell", StringComparison.OrdinalIgnoreCase) ||
+ configName.Equals("microsoft.powershell32", StringComparison.OrdinalIgnoreCase))
+ {
+ return RemoteConfigurationType.PSDefault;
+ }
+ else if (configName.Equals("microsoft.powershell.workflow", StringComparison.OrdinalIgnoreCase))
+ {
+ return RemoteConfigurationType.PSWorkflow;
+ }
+ else if (configName.Equals("microsoft.windows.servermanagerworkflows", StringComparison.OrdinalIgnoreCase))
+ {
+ return RemoteConfigurationType.ServerManagerWorkflow;
+ }
+ else
+ {
+ return RemoteConfigurationType.Custom;
+ }
+ }
+
enum ScriptFileType
{
None = 0,
diff --git a/src/powershell-native/nativemsh/pwrshcommon/pwrshcommon.cpp b/src/powershell-native/nativemsh/pwrshcommon/pwrshcommon.cpp
index e8b519cf3b..b5215d15d8 100644
--- a/src/powershell-native/nativemsh/pwrshcommon/pwrshcommon.cpp
+++ b/src/powershell-native/nativemsh/pwrshcommon/pwrshcommon.cpp
@@ -676,9 +676,10 @@ namespace NativeMsh
L"Microsoft.Win32.Registry",
L"mscorlib",
L"System.AppContext",
+ L"System.Buffers",
L"System.Collections.Concurrent",
- L"System.Collections.Immutable",
L"System.Collections",
+ L"System.Collections.Immutable",
L"System.Collections.NonGeneric",
L"System.Collections.Specialized",
L"System.ComponentModel.Annotations",
@@ -690,7 +691,6 @@ namespace NativeMsh
L"System.Console",
L"System.Core",
L"System.Data.Common",
- L"System.Data.SqlClient",
L"System.Diagnostics.Contracts",
L"System.Diagnostics.Debug",
L"System.Diagnostics.DiagnosticSource",
@@ -701,6 +701,7 @@ namespace NativeMsh
L"System.Diagnostics.Tools",
L"System.Diagnostics.TraceSource",
L"System.Diagnostics.Tracing",
+ L"System",
L"System.Dynamic.Runtime",
L"System.Globalization.Calendars",
L"System.Globalization",
@@ -714,34 +715,30 @@ namespace NativeMsh
L"System.IO.FileSystem.Primitives",
L"System.IO.FileSystem.Watcher",
L"System.IO.MemoryMappedFiles",
+ L"System.IO.Packaging",
L"System.IO.Pipes",
L"System.IO.UnmanagedMemoryStream",
L"System.Linq",
L"System.Linq.Expressions",
L"System.Linq.Parallel",
L"System.Linq.Queryable",
- L"System",
+ L"System.Net",
L"System.Net.Http",
L"System.Net.Http.WinHttpHandler",
- L"System.Net",
L"System.Net.NameResolution",
L"System.Net.NetworkInformation",
+ L"System.Net.Ping",
L"System.Net.Primitives",
L"System.Net.Requests",
L"System.Net.Security",
L"System.Net.Sockets",
- L"System.Net.Utilities",
L"System.Net.WebHeaderCollection",
L"System.Net.WebSockets.Client",
L"System.Net.WebSockets",
L"System.Numerics",
L"System.Numerics.Vectors",
L"System.ObjectModel",
- L"System.Private.CompilerServices.ICastable",
- L"System.Private.CoreLib.InteropServices",
L"System.Private.DataContractSerialization",
- L"System.Private.Interop",
- L"System.Private.Networking",
L"System.Private.ServiceModel",
L"System.Private.Uri",
L"System.Reflection.DispatchProxy",
@@ -760,11 +757,12 @@ namespace NativeMsh
L"System.Runtime.Extensions",
L"System.Runtime.Handles",
L"System.Runtime.InteropServices",
+ L"System.Runtime.InteropServices.PInvoke",
L"System.Runtime.InteropServices.RuntimeInformation",
L"System.Runtime.Loader",
L"System.Runtime.Numerics",
- L"System.Runtime.Serialization.Json",
L"System.Runtime.Serialization",
+ L"System.Runtime.Serialization.Json",
L"System.Runtime.Serialization.Primitives",
L"System.Runtime.Serialization.Xml",
L"System.Security.AccessControl",
@@ -772,45 +770,39 @@ namespace NativeMsh
L"System.Security.Cryptography.Algorithms",
L"System.Security.Cryptography.Cng",
L"System.Security.Cryptography.Csp",
- L"System.Security.Cryptography.DeriveBytes",
L"System.Security.Cryptography.Encoding",
- L"System.Security.Cryptography.Encryption.Aes",
- L"System.Security.Cryptography.Encryption",
- L"System.Security.Cryptography.Hashing.Algorithms",
- L"System.Security.Cryptography.Hashing",
L"System.Security.Cryptography.OpenSsl",
L"System.Security.Cryptography.Primitives",
- L"System.Security.Cryptography.RandomNumberGenerator",
- L"System.Security.Cryptography.RSA",
L"System.Security.Cryptography.X509Certificates",
L"System.Security.Principal",
L"System.Security.Principal.Windows",
L"System.Security.SecureString",
+ L"System.ServiceModel",
L"System.ServiceModel.Duplex",
L"System.ServiceModel.Http",
- L"System.ServiceModel",
L"System.ServiceModel.NetTcp",
L"System.ServiceModel.Primitives",
L"System.ServiceModel.Security",
L"System.ServiceModel.Web",
L"System.ServiceProcess.ServiceController",
L"System.Text.Encoding.CodePages",
- L"System.Text.Encoding.Extensions",
L"System.Text.Encoding",
- L"System.Text.Encoding.Web",
+ L"System.Text.Encoding.Extensions",
+ L"System.Text.Encodings.Web",
L"System.Text.RegularExpressions",
L"System.Threading.AccessControl",
L"System.Threading",
L"System.Threading.Overlapped",
L"System.Threading.Tasks.Dataflow",
L"System.Threading.Tasks",
+ L"System.Threading.Tasks.Extensions",
L"System.Threading.Tasks.Parallel",
L"System.Threading.Thread",
L"System.Threading.ThreadPool",
L"System.Threading.Timer",
L"System.Windows",
- L"System.Xml.Linq",
L"System.Xml",
+ L"System.Xml.Linq",
L"System.Xml.ReaderWriter",
L"System.Xml.Serialization",
L"System.Xml.XDocument",
diff --git a/src/powershell/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/powershell/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1
index 8183aa29c1..e30c63d02e 100644
--- a/src/powershell/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1
+++ b/src/powershell/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1
@@ -11,7 +11,7 @@ CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide",
"Get-EventSubscriber", "Unregister-Event", "New-Event", "Add-Member", "Add-Type", "Compare-Object",
"ConvertFrom-StringData", "Export-Csv", "Import-Csv", "ConvertTo-Csv", "ConvertFrom-Csv", "Export-Alias",
"Invoke-Expression", "Get-Alias", "Get-Culture", "Get-Date", "Get-Host", "Get-Member", "Get-Random",
- "Get-UICulture", "Get-FileHash", "Get-Unique", "Import-Alias", "Import-LocalizedData",
+ "Get-UICulture", "Get-Unique", "Import-Alias", "Import-LocalizedData",
"Select-String", "Measure-Object", "New-Alias", "New-TimeSpan", "Read-Host", "Set-Alias", "Set-Date",
"Start-Sleep", "Tee-Object", "Measure-Command", "Update-TypeData", "Update-FormatData",
"Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object",
@@ -20,8 +20,10 @@ CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide",
"Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint",
"Get-PSBreakpoint", "Remove-PSBreakpoint", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack",
"Unblock-File", "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug",
- "Get-RunspaceDebug", "Wait-Debugger", "Convert-String", "New-TemporaryFile", "New-Guid", "Format-Hex",
- "Import-PowerShellDataFile", "ConvertFrom-SddlString"
+ "Get-RunspaceDebug", "Wait-Debugger"
+FunctionsToExport= "Get-FileHash", "New-TemporaryFile", "New-Guid", "Format-Hex", "Import-PowerShellDataFile",
+ "ConvertFrom-SddlString"
+AliasesToExport= "fhx"
NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1"
HelpInfoURI = 'http://go.microsoft.com/fwlink/?linkid=390787'
}