MSBuild calling Powershell with credentials

2020-05-08 08:36发布

问题:

I'm trying to deploy a windows service using an MSBuild script that runs a Powershell command.

The MSBuild script deploys the files I need and the PowerShell script will uninstall and reinstall the windows service using this command:

Invoke-Command -ComputerName IPAddressHere -FilePath "C:\theScriptFileName.ps1" -credential "TheUserName"

Using an IP address (which I need to because of different domains) I need to use credentials. The problem is that it prompts for a password, which won't work for TeamCity's automation.

I know I can save the credentials into a variable so that the prompt won't show, but I need to get it into a line something like the following that MSBuild can execute:

powershell.exe -NonInteractive -executionpolicy Unrestricted -command "& Invoke-Command -ComputerName IPAddressHere -FilePath 'C:\theScriptFileName.ps1' "

Is there a proper way to do this?

回答1:

Use the code from Lee Holmes' article on exporting credentials:

function Export-Credential($cred, $path) {
  $cred.Password = $cred.Password | ConvertFrom-SecureString
  $cred | Export-Clixml $path
}
function Import-Credential($path) {
  $cred = Import-Clixml $path
  $cred.password = $cred.Password | ConvertTo-SecureString
  New-Object System.Management.Automation.PSCredential($cred.username, $cred.password)
}

Save the credentials first in a regular session with the same user on the same machine that will be running the builds. (Well, on each such machine and user profile.) Then, in the build script, Import-Credential from the same path and pass the new $cred to Invoke-Command.



回答2:

Maybe something like this?

$Creds  =   $host.ui.PromptForCredential("Need credentials", "Please enter username/password with proper rights on objects to manage.`r`n`r`nExample: AD-Domain\username", $env:userdomain + "\" + $env:username, "")
$IPAddressHere = "192.168.0.1"
powershell.exe -NonInteractive -executionpolicy Unrestricted -command "& {Invoke-Command -ComputerName $IPAddressHere -FilePath 'C:\theScriptFileName.ps1' -credentials $creds}"