MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4#pragma warning disable 1634, 16915#pragma warning disable 565066 7namespace System.Management.Automation8{9 /// <summary>10 /// Defines the attribute used to designate a cmdlet parameter as one that11 /// should accept credentials.12 /// </summary>13 [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]14 public sealed class CredentialAttribute : ArgumentTransformationAttribute15 {16 /// <summary>17 /// Transforms the input data to an PSCredential.18 /// </summary>19 /// <param name="engineIntrinsics">20 /// The engine APIs for the context under which the transformation is being21 /// made.22 /// </param>23 /// <param name="inputData">24 /// If Null, the transformation prompts for both Username and Password25 /// If a string, the transformation uses the input for a username, and prompts26 /// for a Password27 /// If already an PSCredential, the transform does nothing.28 /// </param>29 /// <returns>An PSCredential object representing the inputData.</returns>30 public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)31 {32 PSCredential cred = null;33 string userName = null;34 bool shouldPrompt = false;35 36 if ((engineIntrinsics == null) ||37 (engineIntrinsics.Host == null) ||38 (engineIntrinsics.Host.UI == null))39 {40 throw PSTraceSource.NewArgumentNullException(nameof(engineIntrinsics));41 }42 43 if (inputData == null)44 {45 shouldPrompt = true;46 }47 else48 {49 // Try to coerce the input as an PSCredential50 cred = LanguagePrimitives.FromObjectAs<PSCredential>(inputData);51 52 // Try to coerce the username from the string53 if (cred == null)54 {55 shouldPrompt = true;56 userName = LanguagePrimitives.FromObjectAs<string>(inputData);57 58 // If we couldn't get the username (as a string,)59 // throw an exception60 if (userName == null)61 {62 throw new PSArgumentException("userName");63 }64 }65 }66 67 if (shouldPrompt)68 {69 string caption = null;70 string prompt = null;71 72 caption = CredentialAttributeStrings.CredentialAttribute_Prompt_Caption;73 74 prompt = CredentialAttributeStrings.CredentialAttribute_Prompt;75 76 cred = engineIntrinsics.Host.UI.PromptForCredential(77 caption,78 prompt,79 userName,80 string.Empty);81 }82 83 return cred;84 }85 86 /// <summary/>87 public override bool TransformNullOptionalParameters { get { return false; } }88 }89}90 91#pragma warning restore 5650692 