【问题标题】:PSCredential ErrorPSCredential 错误
【发布时间】:2017-03-06 22:53:07
【问题描述】:

我使用内联脚本创建了一个PSCredential,并且能够访问该凭据,直到创建凭据的 PowerShell 会话打开。当我关闭并重新打开 PowerShell 以再次运行脚本时,我无法访问 $TFSAdminCred

$UserID = "xyz"
$PswdFile = "\\Server1\TFSencrypt$\Pswd.txt"
$KeyFile = "\\Server1\TFSencrypt$\AES.txt"

$Key = New-Object byte[] 16
[System.Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | Out-File $KeyFile
$Key = Get-Content $KeyFile

$Pswd = "password" | ConvertTo-SecureString -AsPlainText -Force |
        ConvertFrom-SecureString -Key $Key | Out-File $PswdFile

$TFSAdminCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserId, (Get-Content $PswdFile | ConvertTo-SecureString -Key $Key)

【问题讨论】:

  • 变量不会在 powershell 重启后持续存在
  • 任何存储它们以供重复使用的建议将不胜感激。

标签: powershell credentials


【解决方案1】:

要保留变量以供重复使用,您可以将它们导出到磁盘并在 Powershell 启动时导入,或者您可以使用 powershell 配置文件为您执行此操作。

导出变量做

$var | export-clixml 'path'

导入

$var = import-clixml 'path'

要使用配置文件导入,只需将导入添加到您的 powershell 配置文件中,要访问您的配置文件,请在 PS 提示符下执行 notepad $profile

【讨论】:

  • 按照建议,我尝试在最后添加内联脚本 $TFSAdminCred = Export-Clixml -Path "\\server\sharedpath\cred.txt" 以及当我想使用它时
  • 按照建议,我尝试在末尾添加内联脚本 $TFSAdminCred = Export-Clixml -Path "\\server\sharedpath\cred.txt" 并且当我想用它来停止网站,运行这个 $TFSAdminCred = Import-Clixml -Path "\\server\sharedpath\cred.txt" Invoke-Command -computername xyz.com -credential $TFSadminCred -scriptblock {import-module webadministration; stop-website -name "Websitename"} 手动工作!但是当我试图自动化它时,会抛出错误“密钥在指定状态下无效。”我错过了什么吗?
  • 刚刚意识到我错过了通知您,我正在尝试在远程服务器上导入这些凭据,并且通过此链接 stackoverflow.com/questions/40029235/… 它明确指出它不能在远程服务器上使用。这帮助我明白了 XML 序列化不是解决方案。此后,我仍在寻找一种从我的构建机器上在远程服务器上运行自动化脚本的方法。也感谢您在这方面为我提供的帮助。
猜你喜欢
  • 1970-01-01
  • 2019-10-25
  • 2021-11-09
  • 2012-04-12
  • 1970-01-01
  • 2018-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多