2016-09-15 66 views
0

我有一種困境。Powershell和作爲其他用戶運行計劃任務

我想在Windows中設置一個作爲另一個用戶(有權訪問但沒有登錄權限的服務帳戶)運行PowerShell腳本的計劃任務。問題是我們的安全團隊告訴我們不要在密碼中編碼(顯然是很好的建議),但是SQL的連接字符串似乎需要用純文本。我得到解決此通過創建一個密碼文件:

$credential = Get-Credential 
$credential.Password | ConvertFrom-SecureString | Set-Content e:\temp\password.txt 

然後在腳本轉換回爲純文本(一個連接字符串中使用)

$password = cat E:\temp\password.txt | ConvertTo-SecureString 
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) 
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) 

$connectionString = "Data Source=<mydatabase>;Initial Catalog='<mytable>';User ID=tng ;Password=$Unsecurepassword;" 

的障礙雖然是當我創建密碼文件並以我自己的方式運行腳本時,它運行良好,但我似乎無法將其作爲計劃任務運行。在過去的經驗中,我已經看到密碼文件可能需要由運行計劃任務的服務帳戶創建的位置,但沒有本地登錄權限,我不知道如何創建此密碼文件。有什麼想法嗎?

我試過this technet article但它似乎仍然需要本地登錄從另一個帳戶。

+0

嗯,我想我可能有一些[李NK](http://www.adminarsenal.com/admin-arsenal-blog/secure-password-with-powershell-encrypting-credentials-part-2/) – jdolluc

回答

0

找到了答案 - 我需要一鍵添加到安全字符串:

在創建文件 - 添加在$鍵:

[byte[]] $key = (1..16) 
$credential = Get-Credential 
$credential.Password | ConvertFrom-SecureString -key $key | Set-Content e:\temp\password.txt 

然後在閱讀它的時候回:

$passwordfile = "E:\temp\password.txt" 
[byte[]] $key = (1..16) 
$securePassword = Get-Content $passwordfile | ConvertTo-SecureString -Key $key 
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securepassword) 
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) 

答發現由於this link

相關問題