使用不同的用户凭据通过Powershell连接到TFS

时间:2017-04-11 13:27:49

标签: powershell tfs

我编写了一个Powershell脚本,它连接到我们的TFS服务器,创建工作区,下载最新的源代码并执行每晚构建和发布。

我遇到的问题是它始终与我自己的凭据相关联,而且从我读过的内容来看,这是因为我以我的身份登录到了计算机。我已经创建了一个新的域用户帐户,并且我们已在TFS中授予此管理员权限,但是我无法让脚本使用这些凭据。

这里是脚本的一部分,它处理当前的初始连接和工作区创建:

$subfolder = [System.Guid]::NewGuid().ToString()
$tfsServer = "http://tfsserver:8080/tfs/xyz"

$tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServer)
$tfsVersionCtrlType = [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]
$tfsVersionCtrl = $tfsCollection.GetService([type] $tfsVersionCtrlType)
$tfsWorkspace = $tfsVersionCtrl.CreateWorkspace($subfolder, $tfsVersionCtrl.AuthenticatedUser)

为了完整起见,请参阅" Get"逻辑:

$tfsWorkspace.Map($serverLocation, $localLocation)
$recursion = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
$versionSpec = [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest

$itemSpec = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec($serverLocation, $recursion)
$fileRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest($itemSpec, $versionSpec)
$getStatus = $tfsWorkspace.Get($fileRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite)

通过Powershell使用TFS时遇到的主要问题是微软不断改变他们的实现,在某些情况下非常彻底,而我们留下的是在互联网上乱七八糟的代码帖子和文档碎片(包括SO),这些引用旧的插件和其他现在过时的引用,它们会引导你走上无数错误的路径。

无论如何,所以我尝试创建Windows凭据,PSCredentials等等(似乎没有被任何东西接受),提供IC严格的旧方法是现在已经过时了,我真的不知道该往哪里转。

基本上,我只想创建一个工作区,检查项目,更新文件并重新检入它们 - 所有这些都是我们新的" tfsService"用户帐号。请帮忙......

更新 基于@Nick的答案,我需要进行以下更改。请注意使用[System.Uri]这对我来说是必需的(不确定这是我的设置的怪癖,因为其他人似乎并不需要这样)。另外,我需要将TfsTeamProjectCollection所有的构造函数调用放在一行上,因为按照尼克的例子将它拆分为不同的行,对我来说也不适用。

$cred = New-Object System.Net.NetworkCredential("username", "password", "domain")
$tfsCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection([System.Uri]$tfsServer, $cred)
#$tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServer)

$tfsVersionCtrlType = [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]
$tfsVersionCtrl = $tfsCollection.GetService([type] $tfsVersionCtrlType)
$tfsWorkspace = $tfsVersionCtrl.CreateWorkspace($subfolder, $tfsVersionCtrl.AuthenticatedUser)

1 个答案:

答案 0 :(得分:1)

我无法有效地测试这一点,但对于这个问题,这似乎是SO的常见答案。

$cred = New-Object NetworkCredential("myuser", "myPassword", "mydomain")
$tfsCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection
(
     $tfsServer,
     $cred
)