26

I'm using PowerShell 2.0 (necessary because of SP2010) On Windows Server 2008 R2. I need to retrieve credentials for a process from the Windows Credential Manager. I can't seem to make it work.

I was given this piece of code:

[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
(new-object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % { $_.RetrievePassword(); $_ }

both lines of code throw errors

Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime : Unable to find type [Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]: make sure that the assembly containing this type is loaded.

and

(new-object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % {$_.RetrievePassword(); $_ } 

respectively. I've been trying to somehow import the PasswordVault class. So far Google has failed me, I haven't even been able to find out which assembly it resides in. What am I missing?

4

6 回答 6

45

在 powershell5 类型中:

   Install-Module CredentialManager -force

然后

   New-StoredCredential -Target $url -Username $ENV:Username -Pass ....

然后

   Get-StoredCredential -Target .... 

该模块的源代码是https://github.com/davotronic5000/PowerShell_Credential_Manager

于 2016-03-30T11:43:52.327 回答
9

您需要访问 Win32 API 才能与凭据管理器进行交互。

Technet 脚本库中的 CredMan.ps1很好地证明了这一点。

对于更简单的使用模式,例如仅列出主体或添加新凭据,您还可以使用cmdkey内置的 Windows 命令行实用程序进行凭据管理

为了在 PowerShell 中重用存储的凭据,这个人似乎找到了一种方法PSCredential,使用类似于 CredMan.ps1 的技术从凭据存储中的通用凭据句柄构建一个:Get-StoredCredential

于 2015-03-17T15:56:26.210 回答
3

根据文档,Windows Server 2008 R2 不支持 PasswordVault 类。

支持的最低服务器Windows Server 2012

https://msdn.microsoft.com/library/windows/apps/windows.security.credentials.passwordvault.aspx

于 2015-03-17T15:40:57.403 回答
3

如果有人只想要一个代码片段,以便他们可以分发脚本而不必指示最终用户安装模块或包含 DLL 文件,那么这应该可以解决问题。

$code = @"
using System.Text;
using System;
using System.Runtime.InteropServices;

namespace CredManager {
  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  public struct CredentialMem
  {
    public int flags;
    public int type;
    public string targetName;
    public string comment;
    public System.Runtime.InteropServices.ComTypes.FILETIME lastWritten;
    public int credentialBlobSize;
    public IntPtr credentialBlob;
    public int persist;
    public int attributeCount;
    public IntPtr credAttribute;
    public string targetAlias;
    public string userName;
  }

  public class Credential {
    public string target;
    public string username;
    public string password;
    public Credential(string target, string username, string password) {
      this.target = target;
      this.username = username;
      this.password = password;
    }
  }

  public class Util
  {
    [DllImport("advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern bool CredRead(string target, int type, int reservedFlag, out IntPtr credentialPtr);

    public static Credential GetUserCredential(string target)
    {
      CredentialMem credMem;
      IntPtr credPtr;

      if (CredRead(target, 1, 0, out credPtr))
      {
        credMem = Marshal.PtrToStructure<CredentialMem>(credPtr);
        byte[] passwordBytes = new byte[credMem.credentialBlobSize];
        Marshal.Copy(credMem.credentialBlob, passwordBytes, 0, credMem.credentialBlobSize);
        Credential cred = new Credential(credMem.targetName, credMem.userName, Encoding.Unicode.GetString(passwordBytes));
        return cred;
      } else {
        throw new Exception("Failed to retrieve credentials");
      }
    }

    [DllImport("Advapi32.dll", SetLastError = true, EntryPoint = "CredWriteW", CharSet = CharSet.Unicode)]
    private static extern bool CredWrite([In] ref CredentialMem userCredential, [In] int flags);

    public static void SetUserCredential(string target, string userName, string password)
    {
      CredentialMem userCredential = new CredentialMem();

      userCredential.targetName = target;
      userCredential.type = 1;
      userCredential.userName = userName;
      userCredential.attributeCount = 0;
      userCredential.persist = 3;
      byte[] bpassword = Encoding.Unicode.GetBytes(password);
      userCredential.credentialBlobSize = (int)bpassword.Length;
      userCredential.credentialBlob = Marshal.StringToCoTaskMemUni(password);
      if (!CredWrite(ref userCredential, 0))
      {
        throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
      }
    }
  }
}
"@
Add-Type -TypeDefinition $code -Language CSharp
# How to store credentials
[CredManager.Util]::SetUserCredential("Application Name", "Username", "Password")
# How to retrieve credentials
[CredManager.Util]::GetUserCredential("Application Name")
# How to just get the password
[CredManager.Util]::GetUserCredential("Application Name").password

上面的代码在 PowerShell 7 和 PowerShell 5 上进行了测试,但如果您使用后者,您可能需要一个较新版本的 .Net 框架。

编辑:如@alazyworkaholic 所述,在代码片段中添加了缺少的分号

于 2021-06-11T22:25:38.957 回答
3

Microsoft 的SecretManagement 和 SecretStore似乎是官方解决方案。它们于 2021 年 3 月 25 日正式发布。秘密可以是凭证。

Install-Module Microsoft.PowerShell.SecretManagement
Install-Module SecretManagement.JustinGrote.CredMan  # windows credential manager
Register-SecretVault SecretManagement.JustinGrote.CredMan
Set-Secret -Name TestSecret -Secret "TestSecret"
Get-Secret -Name TestSecret -AsPlainText
TestSecret
于 2020-02-18T13:23:31.753 回答
2

我找到了一个非常好的帖子,这段代码将打印所有用户名、资源和密码

[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$vault = New-Object Windows.Security.Credentials.PasswordVault
$vault.RetrieveAll() | % { $_.RetrievePassword();$_ }

归功于Todd 的帖子

于 2020-06-21T05:20:41.500 回答