2017-04-05 103 views
1

嗨自动化使用PowerShell服务的创建作为一个更大的脚本的一部分时,我所遇到的绊脚石与任务的凭证侧:添加凭据PowerShell来服务

运行:

New-Service -Credential $dmhostcred -BinaryPathName "C:\$AppInstance\Data.Service.exe" -DisplayName "DataService $AppInstance Host Service" -StartupType Automatic -Description "Data $AppInstance Host_Service" -Name "Data Service $AppInstance Host Service" 

不会工作。它将创建服务,但不会将密码添加到服务的凭证字段中。使用Get-Credential命令将脚本中的变量存储在变量中。

很明显,我不希望密码存储为一个字符串/以原始形式在脚本中。

要解决这个问题,我发现了另一个方法为实现这一点,它的工作,但涉及很多旁敲侧击的:

$serviceName = "Data $AppInstance Host" 
     $hostdescription = "Data Host" 
     $exePath = "C:\Path to App Folder\Service.exe" 
     $userName = "$host" 
     $securePassword = convertto-securestring -String "$password" -AsPlainText -Force 
     $credentialsObject = new-object -typename System.Management.Automation.PSCredential -argumentlist $userName, $securePassword 
     New-Service -BinaryPathName $exePath -Name $serviceName -Description $hostdescription -Credential $credentialsObject -DisplayName $serviceName -StartupType Automatic 

这并不工作,但创建多个服务时,这是一场噩梦,我必须将密码存储为另一个变量中的字符串,我希望您能够欣赏 - 我试图减少不得不重复输入相同的详细信息,这些解决方案都不适用于设置服务帐户自动化的时尚。

任何有关如何以更直接的方式实现这一目标的帮助将不胜感激。

感谢, 罗伊

回答

0
$user = "myUser" 
$server = "myServer" 
$file = ".\password.txt" 

# Store password in a file at the beginning of your script 
Read-Host "Enter Password for $user on $server" -AsSecureString | ConvertFrom-SecureString | Out-File $file 


# Retrieve password later on, whenever you need it 
$credential = New-Object -TypeName System.Management.Automation.PSCredential($user, (Get-Content $file | ConvertTo-SecureString)) 
+0

感谢您的回复。代码的最后一行与我通过$ credential = get-credential输入用户名和密码有什么区别? – Royston

+0

您可以将加密的密码保存在一个文件中,并避免在该文件存在的情况下重新输入密码。只是一点点方便。 –

+0

这非常好,尽管我想要在这里实现的是用new-service cmdlet运行脚本,并从$ credential = get-credential变量中导入(服务帐户)凭证在整个脚本中,因此只能进入一次)。你能否想到如果没有我张贴的令人费解的第二种方法来做到这一点? – Royston

0

目前还不清楚我是什么的问题。为了防止重复使用密码,我建议可以多次使用pscredential变量。如果您不想重复使用凭据而只使用密码,那么.Password属性可以重新用作securestring对象。 get-credentials不验证凭据,因此您可以使用虚拟用户名一次性使用它来请求某人输入安全信息。由于这有点脏,那么如果你需要用户输入密码,那么你需要从主机读取,然后将其转换为安全的密码类型。

我希望这是你正在寻找的。

+0

嗨,代码的第一行不工作,因为新服务不接受或从凭证变量输入凭据(这是从$ cred =获取凭证输入的用户名和密码。所以,新的服务不工作的这是我的问题,重申。 – Royston

+0

如果没有执行,请注意,Windows服务需要'computername \ username'模式作为用户名才能工作。不确定New-'Service'对于传入的'pscredential'参数有什么作用。 –

0
New-Service -Credential $dmhostcred -BinaryPathName "C:\$AppInstance\Data.Service.exe" -DisplayName "DataService $AppInstance Host Service" -StartupType Automatic -Description "Data $AppInstance Host_Service" -Name "Data Service $AppInstance Host Service" 

由于某种原因,现在这种方式现在可以工作,一旦我将代码嵌入到函数中。

谢谢