2013-04-11 179 views
0

我正在嘗試將遠程服務器身份驗證添加到PS1批處理文件腳本中。PowerShell v1腳本提示輸入密碼

所以我可以這樣做:

Copy-Item $src $destination -Credential $Creds 

我創建了一個密碼文件,對於現在在同一目錄中的腳本。它只是包含密碼字符串。

引起提示行:

Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File password.txt 

當我去掉Read-host命令,迅速消失和腳本按預期執行。

問題 什麼是做遠程服務器驗證的正確方法?

下面是在腳本的背景下,新代碼:

[...] 

    if(-not(Test-Path $destination)){mkdir $destination | out-null} 

    Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File password.txt 
    $PW = Get-Content password.txt | ConvertTo-Securestring 
    $Creds = New-Object -Typename System.Management.Automation.PSCredential -Argumentlist "SERVER02\Administrator",$PW 

ForEach ($sourcefile In $(Get-ChildItem $source | Where-Object { $_.Name -match "Daily_Reviews\[\d{1,12}-\d{1,12}\].journal" })) 
{ 

     [...] 

     Copy-Item $src $destination -Credential $Creds 

     [...] 

} 
+0

您是否試圖在沒有提示的情況下讀取密碼?或者您使用的身份驗證不起作用? – 2013-04-11 17:05:50

回答

1

如果您不擔心機器之間的密碼文件的便攜性,你可以使用這個相當安全的方法:

# Capture once and store to file - DON'T PUT THIS PART IN YOUR SCRIPT 
$passwd = Read-Host "Enter password" -AsSecureString 
$encpwd = ConvertFrom-SecureString $passwd 
$encpwd 
$encpwd > $path\password.bin 

# Later pull this in and restore to a secure string 
$encpwd = Get-Content $path\password.bin 
$passwd = ConvertTo-SecureString $encpwd 

$cred = new-object System.Management.Automation.PSCredential 'john',$passwd 
$cred 

# NOTE: The "secret" required to rehyrdate correctly is stored in DPAPI - consequence: 
#  You can only rehydrate on the same machine that did the ConvertFrom-SecureString 

如果您需要調試這個,看看是否$ passwd是正確的,你可以執行此同時調試:

$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwd) 
$str = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) 
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) 
$str