Hi all I got the below script to download a file from TFS, using powershell script, but I need to download entire solution how can I achieve that
cls
$tfsCollectionUrl = New-Object System.URI("http://localhost:8080/tfs/defaultcollection");
[Microsoft.TeamFoundation.Client.TfsTeamProjectCollection] $tfsCollection = Get-TfsServer $tfsCollectionUrl
$VersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$DestinationFile = [IO.Path]::GetTempFileName()
$VersionControl.DownloadFileByUrl('$/MyFirstProject/WebApplication1/WebApplication1/WebForm1.aspx.cs', $DestinationFile)
Invoke-Item $DestinationFile
Also this is not checking whether he is having permission to download , I would like to prompt for username and password instead of downloading directly. Can I achieve the same for bitbucket too if so how can I
The same code converted to powershell
connect to tfs and download the files present in it VS2010
For credential use the above logic
Write-Host "Enter source location "
$sourceLocation = Read-Host
$tfsCollectionUrl = New-Object System.URI($sourceLocation);
Write-Host "Enter server path "
$serverPath = Read-Host
Write-Host "Enter local path to download"
$localPath = Read-Host
[Microsoft.TeamFoundation.Client.TfsTeamProjectCollection] $tfsCollection = Get-TfsServer $tfsCollectionUrl
$VersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$latest = [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest
$recursionType = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
try
{
foreach ($item in $VersionControl.GetItems($serverPath, $latest,$recursionType).Items)
{
$target = [io.path]::Combine($localPath,$item.ServerItem.Substring(2))
$exists=[System.IO.Directory]::Exists($target)
if($item.ItemType -eq "Folder" -and !$exists)
{
New-Item $target -Type Directory
}
if($item.ItemType -eq "File")
{
$item.DownloadFile($target)
}
}
Write-Host "`n Successfully downloaded all the files to the target folder: " $localPath -ForegroundColor Green
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Break
}
An easy way is to have a workspace mapping multiple projects and run the tf get command from Powershell.
You can also manage workspace with tf workspace command line.
The simple way is that:
Create a workspace
Map a workspace
Get all files.
Sample code:
$tfsCollectionUrl = New-Object System.URI("[team project collection url");
$username="[user name]"
$password="[password]"
$domain="[domain]"
$cret = new-object System.Net.NetworkCredential($username, $password, $domain)
$teamProjectCollection=new-object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsCollectionUrl,$cret)
$teamProjectCollection.EnsureAuthenticated()
$VersionControl = $teamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$workspace = $VersionControl.CreateWorkspace("BasicSccExamplePS", $VersionControl.AuthorizedUser);
$workspace.Map("[file or folder server path, for example:$/TestTeam/FolderA]", "[local path]")
$workspace.Get()
You can find that it lets you to provide the credential, so you could let user to provide username, password, then connect to TFS with that account.
Regards
Related
I am using the following slightly modified script (from https://winscp.net/eng/docs/script_local_move_after_successful_upload) to upload files to an SFTP site on AWS...and in a PRD env I will have to have this run through approx 0.5M small files...
param (
$localPath = "C:\FTP\*.DAT",
$remotePath = "/",
$backupPath = "C:\FTP\Complete\"
)
try
{
# Load WinSCP .NET assembly
#Add-Type -Path "WinSCPnet.dll"
$ScriptPath = $(Split-Path -Parent $MyInvocation.MyCommand.Definition)
[Reflection.Assembly]::UnsafeLoadFrom( $(Join-Path $ScriptPath "WinSCPnet.dll") ) | Out-Null
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "somewhere.com"
UserName = "user"
SshHostKeyFingerprint = "ssh-rsa 2048 XXXXXXXI"
SshPrivateKeyPath = "C:\blahblah.ppk"
}
$session = New-Object WinSCP.Session
$transferOptions = New-Object WinSCP.TransferOptions
# Look to ignore any file property change errors
$transferOptions.FilePermissions = $Null # This is default
$transferOptions.PreserveTimestamp = $False
try
{
# Connect
$session.Open($sessionOptions)
# Upload files, collect results
$transferResult = $session.PutFiles($localPath, $remotePath)
# Iterate over every transfer
foreach ($transfer in $transferResult.Transfers)
{
# Success or error?
if ($Null -eq $transfer.Error)
{
Write-Host "Upload of $($transfer.FileName) succeeded, moving to backup"
# Upload succeeded, move source file to backup
Move-Item $transfer.FileName $backupPath
}
else
{
Write-Host "Upload of $($transfer.FileName) failed: $($transfer.Error.Message)"
}
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch
{
Write-Host "Error: $($_.Exception.Message)"
exit 1
}
The scripts works great, but unfortunately only loads one file before disconnecting. The script fails if there is an error loading any of the files, so it is working as expected.
But the error I am getting, is
"Upload of file 'somefile.DAT' was successful, but error occurred while setting the permissions and/or timestamp.
If the problem persists, turn off setting permissions or preserving timestamp. Alternatively you can turn on 'Ignore permission errors' option.
The server does not support the operation.
Error code: 8
Error message from server (US-ASCII): SETSTAT unsupported"
I think I have the following settings possibly configured incorrectly, but I'm not sure what I am doing wrong here....thoughts?
$transferOptions.FilePermissions = $Null # This is default
$transferOptions.PreserveTimestamp = $False
I've actually managed to get this to work by modifying the session and transfer options..
$session.Open($sessionOptions)
$transferOptions = New-Object WinSCP.TransferOptions
# Look to ignore any file property change errors
$transferOptions.PreserveTimeStamp = $false
$transferOptions.FilePermissions = $Null
$transferOptions.AddRawSettings("IgnorePermErrors", "1")
# Upload files, collect results
$transferResult = $session.PutFiles($localPath, $remotePath, $False, $transferOptions)
I have this simple script that is working and I'm able to download a csv file From my SharePoint site but I'm just wondering how can I modify it so that I can download another file that is located in another path and save it in the same local folder as soon as the first one is complete downloading?.
Basically this is what I'm trying to do
Download this first
$SourceFile="/sites/msteams/ReportsFull/OneDrive.csv"
Download this second, save in the same folder with the first one
$SourceFile="/sites/msteams/Shared%20Documents/OneDriveInventory/ActiveLitHoldWithOneDrive.csv"
\#Set parameter values
$SiteURL="https://companyName.sharepoint.com"
$SourceFile="/sites/msteams/ReportsFull/OneDrive.csv"
$TargetFile="C:\\Users\\AS\\Downloads\\New folder\\LegalDoc.docx"
Function Download-FileFromLibrary()
{
param
(
\[Parameter(Mandatory=$true)\] \[string\] $SiteURL,
\[Parameter(Mandatory=$true)\] \[string\] $SourceFile,
\[Parameter(Mandatory=$true)\] \[string\] $TargetFile
)
Try {
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Global:adminUPN, $Global:adminPwd)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
#sharepoint online powershell download file from library
$FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx,$SourceFile)
$WriteStream = [System.IO.File]::Open($TargetFile,[System.IO.FileMode]::Create)
$FileInfo.Stream.CopyTo($WriteStream)
$WriteStream.Close()
Write-host -f Green "File '$SourceFile' Downloaded to '$TargetFile' Successfully!" $_.Exception.Message
}
Catch {
write-host -f Red "Error Downloading File!" $\_.Exception.Message
}
}
\#Call the function to download file
Download-FileFromLibrary -SiteURL $SiteURL -SourceFile $SourceFile -TargetFile $TargetFile
You've got the right code, just need to call the function twice
$sourceFile1 = '/sites/msteams/ReportsFull/OneDrive.csv'
$targetFile1 = 'C:\\Users\\AS\\Downloads\\New folder\\LegalDoc.docx'
Download-FileFromLibrary -SiteURL $SiteURL -SourceFile $SourceFile1 -TargetFile $TargetFile1
$sourceFile2 = '/sites/msteams/Shared%20Documents/OneDriveInventory/ActiveLitHoldWithOneDrive.csv'
$targetFile2 = 'C:\\Users\\AS\\Downloads\\New Folder\\NewFile2.docx'
Download-FileFromLibrary -SiteURL $siteUrl -SourceFile $sourceFile2 -TargetFile $targetFile2```
I'm trying to connect to SharePoint Online but I'm getting this error and not 100% sure why so I would be really appreciated if I can get any help or suggestion why it might be.
I believe it might have to do with my tenant using MFA so just wondering how can I connect/login using MFA?.
#Variables
$SiteURL = "https://companyName-my.sharepoint.com/personal/yzqpsn_nam_corp_m_com"
$ServerRelativeUrl= "documents/Testing"
Try {
#Get Credentials to connect
$Cred= Get-Credential
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get the web from URL
$Web = $Ctx.web
$Ctx.Load($Web)
$Ctx.executeQuery()
#Get the Folder object by Server Relative URL
$Folder = $Web.GetFolderByServerRelativeUrl($ServerRelativeUrl)
$Ctx.Load($Folder)
$Ctx.ExecuteQuery()
#Call the function to empty Folder
Empty-SPOFolder $Folder
#Delete the given Folder itself
Write-host -f Green "Deleting Folder:"$Folder.ServerRelativeUrl
$Folder.Recycle() | Out-Null
$Ctx.ExecuteQuery()
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}
I have a PS script which downloads the latest code from TFS on my local machine but I want it to download a specific labelled code instead of latest.
Below is the script which downloads the latest code present in TFS,
$sourceLocation = "http://vwmaztfsapp:8080/tfs/MatchCollection"
$tfsCollectionUrl = New-Object System.URI($sourceLocation);
$serverPath = "$/Match Web/Installscript Projects/Utility Scripts"
#It gets copied at local path with the above folder sequence
$localPath = "C:\"
$visualStudiopath = 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer'
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.VersionControl.Client.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.Common.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.WorkItemTracking.Client.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.Client.dll"
Add-type -path "$visualStudiopath\Microsoft.TeamFoundation.ProjectManagement.dll"
Add-Type -Path "$visualStudiopath\Microsoft.TeamFoundation.Build.Common.dll"
$tfsCollection = New-Object -TypeName Microsoft.TeamFoundation.Client.TfsTeamProjectCollection -ArgumentList $tfsCollectionUrl
$VersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$latest = [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest
$recursionType = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
try
{
foreach ($item in $VersionControl.GetItems($serverPath, $latest,$recursionType).Items)
{
$target = [io.path]::Combine($localPath,$item.ServerItem.Substring(2))
$exists=[System.IO.Directory]::Exists($target)
if($item.ItemType -eq "Folder" -and !$exists)
{
New-Item $target -Type Directory
}
if($item.ItemType -eq "File")
{
$item.DownloadFile($target)
}
}
Write-Host "`n Successfully downloaded all the files to the target folder: " $localPath -ForegroundColor Green
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Break
}
I tried using the Microsoft.TeamFoundation.VersionControl.Client.LabelVersionSpec but was not successful.
Can anyone please guide me to the correct link or script by which I can download the "$/Match Web" code using the label which I had applied on it. This is the label which I had applied on "$/Match Web" branch for e.g. - "PreBuildLabel-MatchEnterpriseBuild1"
#Assael Azran, getting below result in $vs
Try this (works for me):
$vs = New-Object Microsoft.TeamFoundation.VersionControl.Client.LabelVersionSpec($label, $scope);
foreach ($item in $VersionControl.GetItems($serverPath, $vs,$recursionType).Items)
{
.....
}
$label - name of your label
$scope - The scope (project) of the label. To verify that through VisualStudio, navigate to File-> Source control-> Find-> Find Label.
In the "Find Label" form find your label and open it, then you will see the project name (the one under the collection), you can use it as the scope.
LabelVersionSpec Constructor
UPDATE
Upon request of #SRP, this is how you should create a branch from a TFS label:
$vcs = $server.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]);
$changesetId = $vcs.CreateBranch($sourceBranch, $destBranch,$vs)
VersionControlServer.CreateBranch
I've used the following sites to help me get this far and to troubleshoot.
Download file from SharePoint
How to download newest file from SharePoint using PowerShell
Mike Smith's Tech Training Notes SharePoint, PowerShell and .Net!
Upload file to a SharePoint doc library via PowerShell
Download latest file from SharePoint Document Library
How to iterate each folders in each of the SharePoint websites using PowerShell
PowerShell's Get-ChildItem on SharePoint Library
I am trying to download random files from SharePoint folder, and I have it working for when I actually know the file name and extension.
Working code with name and extension:
$SharePoint = "https://Share.MyCompany.com/MyCustomer/WorkLoad.docx"
$Path = "$ScriptPath\$($CustomerName)_WorkLoad.docx"
#Get User Information
$user = Read-Host "Enter your username"
$username = "$user#MyCompany"
$password = Read-Host "Enter your password" -AsSecureString
#Download Files
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($UserName, $Password)
$WebClient.DownloadFile($SharePoint, $Path)
However, I don't seem to be able to figure out how to do it with multiple files of unknown names or extensions.
I have tried mapping a drive, only to end up with "drive mapping failed" & "The network path was not found." errors:
$SharePoint = Read-Host 'Enter the full path to Delivery Site'
$LocalDrive = 'P:'
$Credentials = Get-Credential
if (!(Test-Path $LocalDrive -PathType Container)) {
$retrycount = 0; $completed = $false
while (-not $completed) {
Try {
if (!(Test-Path $LocalDrive -PathType Container)) {
(New-Object -ComObject WScript.Network).MapNetworkDrive($LocalDrive,$SharePoint,$false,$($Credentials.username),$($Credentials.GetNetworkCredential().password))
}
$Completed = $true
}
Catch {
if ($retrycount -ge '5') {
Write-Verbose "Mapping SharePoint drive failed the maximum number of times"
throw "SharePoint drive mapping failed for '$($SharePoint)': $($Global:Error[0].Exception.Message)"
} else {
Write-Verbose "Mapping SharePoint drive failed, retrying in 5 seconds."
Start-Sleep '5'
$retrycount++
}
}
}
}
I've also used the following code with similar results or no results at all.
#Get User Information
$user = Read-Host "Enter your username"
$username = "$user#MyCompany"
$password = Read-Host "Enter your password" -AsSecureString
#Gathering the location of the Card Formats and Destination folder
$Customer = "$SharePoint\MyCustomer"
$Products = "$Path\$($CustomerName)\Products\"
#Get Documents from SharePoint
$credential = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-PSDrive -Credential $credential -Name "A" -PSProvider "FileSystem" -Root "$SharePoint"
net use $spPath #$password /USER:$user#corporate
#Get PMDeliverables file objects recursively
Get-ChildItem -Path "$Customer" | Where-Object { $_.name -like 'MS*' } | Copy-Item -Destination $Products -Force -Verbose
Without defined "input parameters", it's not exactly clear the full solution you need so I'll provide a few snippets of PowerShell that should be of use based on what you've described.
I'll spare you the basics of the various OOTB functions (i.e. Get-SPWeb, etc) though can provide those details as well if needed. I've also been overly explicit in the scripting, though know some of these lines could be chained, piped, etc to be made shorter & more efficient.
This example will iterate over the contents of a SharePoint Library and download them to your local machine:
$Destination = "C:\YourDestinationFolder\ForFilesFromSP"
$Web = Get-SPWeb "https://YourServerRoot/sites/YourSiteCollection/YourSPWebURL"
$DocLib = $Web.Lists["Your Doc Library Name"]
$DocLibItems = $DocLib.Items
foreach ($DocLibItem in $DocLibItems) {
if($DocLibItem.Url -Like "*.docx") {
$File = $Web.GetFile($DocLibItem.Url)
$Binary = $File.OpenBinary()
$Stream = New-Object System.IO.FileStream($Destination + "\" + $File.Name), Create
$Writer = New-Object System.IO.BinaryWriter($Stream)
$Writer.write($Binary)
$Writer.Close()
}
}
This is pretty basic; the variables up top are where on your local machine you wish to store the download files ($Destination), the URL of your SharePoint Site/Web ($Web) and the name of the Document Library (Your Doc Library Name).
The script then iterates through the items in the Library (foreach ($DocLibItem in $DocLibItems) {}), optionally filters for say items with a .docx file extension and downloads each to your local machine.
You could customize this further by targeting a specific sub-folder within the Doc Library, filter by metadata or properties of the Docs or even iterate over multiple Sites, Webs and/or Libraries in one script, optionally filtering those based on similar properties.