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