我正在尝试通过Powershell连接到网络共享。网络共享位于不同的域上,因此我需要提供凭据。由于 New-PSDrive 不支持凭据,因此我打算使用 net use ,但是我担心将用户名/密码以明文形式存储在脚本中。我强制 ConvertTo-SecureString 从密码中创建一个安全字符串,然后使用 ConvertFrom-SecureString 并将结果存储在文件中。然后,我将其从文件中拉出,并尝试 net use :
$password = Get-Content <locationOfStoredPasswordFile> | ConvertTo-SecureString
net use q: "\\server\share" $password /user:domain\username
但是净使用无法识别安全字符串。
任何人都对如何存储凭据有任何想法,以便 net use 可以使用它们?谢谢!
最佳答案
这是我用于加密/解密字符串的两个函数。它们是从powershell.com帖子改编而成的,但是我没有可用的链接。这个想法是,您的密码文件将存储Protect-String的输出,然后转换回常规字符串,读入文件并调用UnProtect-String,从UnProtect字符串返回的值将是您的$ password变量。
#######################
function Protect-String
{
param([string]$InputString)
$secure = ConvertTo-SecureString $InputString -asPlainText -force
$export = $secure | ConvertFrom-SecureString
write-output $export
} #Protect-String
#######################
function UnProtect-String
{
param([string]$InputString)
$secure = ConvertTo-SecureString $InputString
$helper = New-Object system.Management.Automation.PSCredential("SQLPSX", $secure)
$plain = $helper.GetNetworkCredential().Password
write-output $plain
} #UnProtect-String
关于networking - Powershell:如何使用存储的非纯文本用户名/密码连接到不同域上的网络文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661503/