Powershell 如何从函数返回SecureString对象

Powershell 如何从函数返回SecureString对象,powershell,Powershell,如何将SecureString对象从函数返回到变量 function ReadSecuredFile { [SecureString] $SecuredString; $SecuredString = ConvertTo-SecureString 'Testing123' -asplaintext -force; return $SecuredString; } $a = ReadSecuredFile; $a未在语句return$SecuredString中获取$Se

如何将SecureString对象从函数返回到变量

function ReadSecuredFile
{
   [SecureString] $SecuredString;

   $SecuredString = ConvertTo-SecureString 'Testing123' -asplaintext -force;

   return $SecuredString;
}

$a = ReadSecuredFile;
$a未在语句return$SecuredString中获取$SecuredString。它在VS中作为System.Object返回,在PowerGUI中作为System.Array返回

# Encrypt.
[SecureString] $Local:objPassword = Read-Host -Prompt 'Enter Password' -AsSecureString;

# Decrypt.
$strPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto( [Runtime.InteropServices.Marshal]::SecureStringToBSTR( $objPassword ) );
Write-Host -Object ( 'Decrypted password is "{0}"...' -f $strPassword );

表达式
[SecureString]$SecuredString
导致在
SecureString
对象之前返回
$null
。删除该声明

function ReadSecuredFile
{
   $SecuredString = ConvertTo-SecureString 'Testing123' -asplaintext -force;

   return $SecuredString;
}
或更简单:

function ReadSecuredFile
{
    return ConvertTo-SecureString Testing123 -AsPlainText -Force
}

发布一个简短的示例函数,该函数只包含重现问题所需的最少代码量。OK@Bill_Stewart我创建了一个bear bones示例函数。如果您能够提供帮助,那将非常好。函数中的第一行代码是多余的,实际上返回了一个空对象。感谢您的回答@Simon Catlin,但希望将[SecureString]对象从函数返回到[SecureString]对象变量。没问题。:-)
return
语句是不需要的,尽管它出现在那里并没有什么坏处。@mathias-r-jessen。非常感谢你。效果很好。我仍然不明白为什么它返回null而不是您声明的类型和您设置的最后一个值?在更大的函数中,我用一个变量返回它,因为有时我不关心值,只返回true或false。@CostaZachariou这是一个强制转换,不是一个声明-powershell没有像C#for这样的变量声明概念example@mathias-r-jessen OK现在说得通了。谢谢。:-)