botmtl
8/29/2016 - 12:37 AM

DeviceCmdletBase.CS

using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using DeviceManagementLib;
using DeviceManagementLib.Win32;

namespace DeviceManagementModule
{
    public class DeviceCmdletBase : PSCmdlet
    {
        protected DeviceClass? @class;
        protected IEnumerable<Device> devices = null;
        protected string instanceId;
        protected string name;

        protected IEnumerable<Device> GetDevice()
        {
            IEnumerable<Device> source = null;
            if (!string.IsNullOrEmpty(instanceId) && @class.HasValue)
                source = DeviceManagementLib.DeviceManagementLib.GetDevices(instanceId, @class);
            else if (!string.IsNullOrEmpty(instanceId) && !@class.HasValue)
                source = DeviceManagementLib.DeviceManagementLib.GetDevices(instanceId, new DeviceClass?());
            else if (string.IsNullOrEmpty(instanceId) && @class.HasValue)
                source = DeviceManagementLib.DeviceManagementLib.GetDevices("", @class);
            else if (string.IsNullOrEmpty(instanceId) && !@class.HasValue)
                source = DeviceManagementLib.DeviceManagementLib.GetDevices("", new DeviceClass?());

            if (!string.IsNullOrEmpty(name))
                source = source.Where(d =>
                {
                    if (!string.IsNullOrEmpty(d.Name))
                        return d.Name.ToLower() == name.ToLower();
                    return false;
                });

            if ((!string.IsNullOrEmpty(name) | !string.IsNullOrEmpty(instanceId)) && (source.Count() == 0))
                throw new DeviceNotFoundException();
            return source;
        }
    }
}