3 回答
TA贡献1799条经验 获得超6个赞
还有另一种方式,但......
如果你 不想在脚本文件中输入密码,请不要这样做(在脚本中存储密码不是一个好主意,但我们中的一些人只是想知道如何。)
好的,这是警告,这是代码:
$username = "John Doe"$password = "ABCDEF"$secstr = New-Object -TypeName System.Security.SecureString$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$cred
将获得John Doe的凭证,密码为“ABCDEF”。
替代方法是准备好使用密码:
$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force
TA贡献1794条经验 获得超8个赞
关于存储凭证,我使用两个函数(通常在从我的配置文件加载的模块中):
#=====================================================================
# Get-MyCredential
#=====================================================================
function Get-MyCredential
{
param(
$CredPath,
[switch]$Help
)
$HelpText = @"
Get-MyCredential
Usage:
Get-MyCredential -CredPath `$CredPath
If a credential is stored in $CredPath, it will be used.
If no credential is found, Export-Credential will start and offer to
Store a credential at the location specified.
"@
if($Help -or (!($CredPath))){write-host $Helptext; Break}
if (!(Test-Path -Path $CredPath -PathType Leaf)) {
Export-Credential (Get-Credential) $CredPath
}
$cred = Import-Clixml $CredPath
$cred.Password = $cred.Password | ConvertTo-SecureString
$Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
Return $Credential
}
还有这个:
#=====================================================================
# Export-Credential
# Usage: Export-Credential $CredentialObject $FileToSaveTo
#=====================================================================
function Export-Credential($cred, $path) {
$cred = $cred | Select-Object *
$cred.password = $cred.Password | ConvertFrom-SecureString
$cred | Export-Clixml $path
}
你这样使用它:
$Credentials = Get-MyCredential (join-path ($PsScriptRoot) Syncred.xml)
如果凭证文件不存在,则第一次会提示您,此时它会将凭证存储在XML文件中的加密字符串中。第二次运行该行时,xmlfile就会出现并自动打开。
添加回答
举报