2015-04-21 60 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

相關問題