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

PowerShell脚本-从外部文件获取帐户信息,powershell,scripting,credentials,windows-server,Powershell,Scripting,Credentials,Windows Server,我目前有一个脚本成功地使用此方法远程连接到服务器,并使用Invoke命令运行某些任务: $c = Get-Credential $computername = "server.fqdn" $session = New-PSSession -ComputerName $computername -Authentication CredSSP -Credential $c 执行此操作时,系统会提示我输入要运行的帐户的用户名和密码。我进入它,它就工作了 我希望能够做到的是,在脚本执行时,不

我目前有一个脚本成功地使用此方法远程连接到服务器,并使用Invoke命令运行某些任务:

$c = Get-Credential 
$computername = "server.fqdn"
    $session = New-PSSession -ComputerName $computername -Authentication CredSSP -Credential $c
执行此操作时,系统会提示我输入要运行的帐户的用户名和密码。我进入它,它就工作了

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

还有一个似乎和我想做的非常接近。使用文本文件并转换securestring。我不太明白如何使用新的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

我的密码在文本文件中。就像密码123一样。在我尝试使用文本文件之前,密码一直有效。

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

$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

多亏了你,我走得更远了。当我使用新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$ComputerName-Authentication CredSSP-Credential$credNew PSSession:[server.fqdn]连接到远程服务器服务器失败。fqdn出现以下错误消息:参数不正确。有关更多信息,请参阅关于远程故障排除帮助主题。第1行:1个字符:12$session=新建PSSession-ComputerName$ComputerName-Authentication CredSSP-Cr…~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~CategoryInfo:OpenError:(System.Manageme.…RemoteRunspace:RemoteRunspace)[New PSSession],PSRemotin GTTransportException+FullyQualifiedErrorId:87,PSSessionOpenFailed`您创建密码文件的方式出错,请查看并测试我的代码。