PowerShell脚本 - 从外部文件获取帐户信息

时间:2015-04-21 18:51:38

标签: powershell scripting credentials windows-server

我目前有一个成功使用此方法远程连接服务器并使用Invoke-Command运行某些任务的脚本:

$c = Get-Credential 
$computername = "server.fqdn"
    $session = New-PSSession -ComputerName $computername -Authentication CredSSP -Credential $c

执行此操作时,系统会提示我输入要运行的帐户的用户名和密码。我输入它就可以了。

我希望能够做的不是在脚本执行时提示输入凭据,而是希望自动使用我存储在某个文本文件中的凭据(或者至少以这种方式使用密码)。这是因为我需要安排脚本从服务器外部运行。

还有另一个thread似乎与我试图做的非常接近。使用文本文件和convert-securestring。我不太明白如何使用New-PSSession来使用此方法。也许还有另一种方式。

到目前为止,我有以下代码。

  $username = "domain\username"
    $password  = cat C:\scripts\password.txt | convertto-securestring
    $c = new-object -typename System.Management.Automation.PSCredential `
             -argumentlist $username, $password 
    $computername = "server.fqdn"
    $session = New-PSSession -ComputerName $computername -Authentication CredSSP -Credential $c 

我仍然被提示输入用户名和密码并收到错误:

convertto-securestring : Input string was not in a correct format

我的密码在文本文件中。它就像password123。密码有效,直到我尝试使用文本文件。

1 个答案:

答案 0 :(得分:1)

我不打算更正您的代码,但这是我用来在我的某些服务器上存储密码的方式。第一次运行代码时,它会要求输入密码,然后将其加密存储在文件中,下次从文件中读取密码。 小心密码可以从文件内容中找到,它对我们来说不可读,但可能是安全问题。

$passwordFile = "C:\scripts\password.txt"
$username = "domain\username"

# First time create password file
if (! (Test-Path $passwordFile))
{
  Read-Host -AsSecureString | convertfrom-securestring | out-file $passwordFile
}

$password = Get-Content $passwordFile | convertto-securestring
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password