2015-04-21 88 views
1

我目前有成功使用此方法来远程连接到服务器,并使用Invoke-Command运行脚本的一些任务:PowerShell脚本 - 获取从外部文件帐户信息

$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

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

$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 
+0

感谢你,我得到了更远一点。当我使用New-PSSession时,我仍然遇到一个错误。你能看到我出错的地方吗? '$ username =“domain \ username” $ passcontent = Get-Content“c:\ scripts \ password.txt” $ password = ConvertTo-SecureString -String $ passcontent -AsPlainText -Force $ cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ username,$ password $ computername =“server.fqdn” $ session = New-PSSession -ComputerName $计算机名 - 认证CredSSP -Credential $ cred' – spex5

+0

New-PSSession:[server。 fqdn]连接到远程服务器server.fqdn失败,出现以下错误消息: :参数不正确。有关详细信息,请参阅about_Remote_Troubleshooting帮助 主题。 在线:1 char:12 $ session = New-PSSession -C计算机名称$计算机名称-Authentication CredSSP -Cr ... ~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~ + CategoryInfo:OpenError:(System.Manageme .... RemoteRunspace:RemoteRunspace)新的PSSession],PSRemotin gTransportException + FullyQualifiedErrorId:87,PSSessionOpenFailed' – spex5

+0

你去错了的方式你创建你的密码文件,看看并测试我的代码。 – JPBlanc

相关问题