Ejemplo n.º 1
0
        /// <summary>
        /// Use when the user needs to decide on possible options
        /// It invokes <see cref="OnQuestion"/> where the implementer can either block uppm with user query or use the default value.
        /// </summary>
        /// <typeparam name="T">Must be an enum</typeparam>
        /// <param name="question">Question to be asked from user</param>
        /// <param name="note">Displayed on top of the prompt</param>
        /// <param name="possibilities">If null any input will be accepted. Otherwise input is compared to these possible entries.</param>
        /// <param name="defaultValue">This value is used when user submits an empty input or in a potential unattended mode.</param>
        /// <returns>User answer or default</returns>
        public static T PromptForEnum <T>(
            this PSCmdlet cmdlet,
            string question,
            string note = "",
            IEnumerable <T> possibilities = null,
            T defaultValue = default(T)) where T : struct
        {
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException($"{typeof(T)} type is not enum.");
            }
            var poss = possibilities == null?Enum.GetNames(typeof(T)) : possibilities.Select(p => p.ToString());

            var resstr = cmdlet.PromptForChoice(question, note, poss, defaultValue.ToString());

            return(Enum.TryParse <T>(resstr, true, out var res) ? res : defaultValue);
        }