Windows上的PowerShell:“;此平台不支持Windows数据保护API(DPAPI)。”;

Windows上的PowerShell:“;此平台不支持Windows数据保护API(DPAPI)。”;,powershell,Powershell,我需要在Windows上使用数据保护API,但PowerShell似乎无法。运行此脚本时: $scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser $ciphertext = [System.Text.Encoding]::UTF8.GetBytes("hallo welt") $protected = [System.Security.Cryptography.ProtectedData]::Protec

我需要在Windows上使用数据保护API,但PowerShell似乎无法。运行此脚本时:

$scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
$ciphertext = [System.Text.Encoding]::UTF8.GetBytes("hallo welt")
$protected = [System.Security.Cryptography.ProtectedData]::Protect($ciphertext, $null, $scope)
$unprotected = [System.Security.Cryptography.ProtectedData]::Unprotect($protected, $null, $scope)
$text = [System.Text.Encoding]::UTF8.GetString($unprotected)
Write-Output $text
我得到这个输出:

Exception calling "Protect" with "3" argument(s): "Windows Data Protection API (DPAPI) is not supported on this platform."
At line:3 char:1
+ $protected = [System.Security.Cryptography.ProtectedData]::Protect($c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : PlatformNotSupportedException
当我创建一个控制台应用程序并在C#中执行相同的操作时,它工作得非常好。为什么它在PowerShell中不起作用

编辑:
这在PowerShell核心上确实有效。为什么不在经典的PowerShell上呢?

我想出来了。这在PowerShell中不起作用,但在PowerShell核心中起作用的原因是,我实际上在PowerShell中加载了错误的程序集

当我为.NET4.6.1加载正确的程序集时,它就工作了

Add-Type -Path "D:\_packages\System.Security.Cryptography.ProtectedData.4.6.0\lib\net461\System.Security.Cryptography.ProtectedData.dll"
$scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
$ciphertext = [System.Text.Encoding]::UTF8.GetBytes("hallo welt")
$protected = [System.Security.Cryptography.ProtectedData]::Protect($ciphertext, $null, $scope)
$unprotected = [System.Security.Cryptography.ProtectedData]::Unprotect($protected, $null, $scope)
$text = [System.Text.Encoding]::UTF8.GetString($unprotected)
Write-Output $text

您正在使用PowerShell Core吗?这在Windows 10上的PowerShell 5.1(64位和32位版本)以及ISE中都适用。事实上,很难想象这怎么会失败,因为它会调用非托管代码。
[System.Reflection.Assembly]:LoadWithPartialName(“System.Security”)
是否生成了正确的程序集?对我来说也很好。经典PowerShell 5.1什么Windows版本?我的平台和我的Windows版本绝对受支持,因为如果我在.net core或.net framework控制台应用程序中使用DPAPI,这将非常有效。我想它可能是装配错误了。