TFS online 2017 upload files via powershell - tfs

I have a trial 2017 online TFS and i am trying to find a way to upload files with powershell commands. I have tried installing some relevant modules with wrapped api commands, but none of them has anything similar.
Any suggestions?here are actually the two commands i am trying to execute through ps

Why you have to do this? The actions via web portal are more convenient and friendly.
Whatever you can have a try with the REST API.
Create a folder: (Create folder test0232 under $/0522TFVCScrum/ in below example)
Param(
[string]$vsoAccount = "YourInstance",
[string]$keepForever = "true",
[string]$user = "test#hotmail.com",
[string]$token = "PAT or Password here"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
function CreateJsonBody
{
$value = #"
{"changes":[{"changeType":1,"item":{"path":"$/0522TFVCScrum/test0232","isFolder":true}}],"comment":"Added folder test0232"}
"#
return $value
}
$json = CreateJsonBody
$uri = "https://$($vsoAccount).visualstudio.com/_apis/tfvc/changesets?api-version=4.1-preview.3"
$result = Invoke-RestMethod -Uri $uri -Method Post -Body $json -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Write-host $result
Create a file with below body: (Just replace the Jsonbody in above script, 0229test.ps1 created in this sample)
{"changes":[{"changeType":1,"item":{"path":"$/0522TFVCScrum/0229test.ps1","contentMetadata":{"encoding":65001}},"newContent":{"content":"test0229","contentType":0}}],"comment":"Added file 0229test.ps1"}
Upload file:
Cannot find a way to upload files directly with the REST API, however you can try to copy files to workspace first, then add the files in source control with Add command, then check in the files with Checkin command.
Downlaod as Zip:
You can track the API with tools, then you can get the URL something like this:
https://{your account}.visualstudio.com/b3cbc52a-22f6-4de9-ae78-b2b305365ff8/_api/_versioncontrol/itemContentZipped?repositoryId=&path=%24%2F0522TFVCScrum%2Ftest0228&version=T&__v=5
Then you can try downlaod with that url in your script.

Related

Bulk Export file paths from sharepoint

I am adding 200+ hyperlinks to an excel file for easier access to sharepoint folders. Rather than manually pulling each one I am trying to bulk export the file paths from a sharepoint folder. Any ideas on how to do this?
We can use PnP PowerShell to achieve it.
#Config Variables
$SiteURL = "https://tenant.sharepoint.com/sites/lz"
$ListName = "DL0906"
$FolderRelativeURL= "/sites/lz/DL0910/Test"
$ExportFile="C:\temp\FileUrls.csv"
#Get Credentials to connect
$Cred = Get-Credential
Try {
#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials $Cred
#Get All Items from the Folder
$CAMLQuery = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FileDirRef'/><Value Type='Text'>$FolderRelativeURL</Value></Eq></Where></Query></View>"
$FolderItems = Get-PnPListItem -List $ListName -Query $CAMLQuery
$FileCollection = #()
ForEach($Item in $FolderItems)
{
$ExportFileUrl = New-Object PSObject
$ExportFileUrl | Add-Member -MemberType NoteProperty -name "File URL" -value $Item["FileRef"]
$FileCollection += $ExportFileUrl
}
$FileCollection | Export-CSV $ExportFile -NoTypeInformation
}
catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
Refer to: SharePoint Online: Get All Files from a Folder using PowerShell

PowerShell Webrequest POST for PowerShell 2.0

How can I modify this snippet code for PowerShell version 2.0 on Windows 7?
$path = "myfolder/file.txt"
$body = "file=$(Get-Content $path | Out-String)"
Invoke-WebRequest -Uri "http//mywebsite" -Method POST -Body $body`
I tried this but cannot run on PowerShell version 2.0.
Any suggestions?
Invoke-webRequest is present in PowerShell v3.0 [ref - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-6]
There are two solution to solve the problem, one you can update the powershell version to 3 or above ,
else use following cmdlet to perform WebRequest.
$WebRequest = [System.Net.WebRequest]::Create("http://url")
$WebRequest.Method = "GET"
$WebRequest.ContentType = "application/json"
$Response = $WebRequest.GetResponse()
$ResponseStream = $Response.GetResponseStream()
$ReadStream = New-Object System.IO.StreamReader $ResponseStream
$Data=$ReadStream.ReadToEnd()

I have existing team project ( TFS 2018 )I want to know which process template have been used

I have existing team project ( TFS 2018 )I want to know which process template have been used.
List the projects via REST API and get the {projectId} for
a specific project:
GET http://SERVER:8080/tfs/DefaultCollection/_apis/projects
Retrieve the Process template information from project
properties by calling REST API:
GET http://SERVER:8080/tfs/DefaultCollection/_apis/projects/{projectId}/properties
Please see Projects - Get Project Properties for details.
Well, you can simply use below Powershell script to get which process template have been used for a specific team project:
Param(
[string]$collectionurl = "http://server:8080/tfs/DefaultCollection",
[string]$projectname = "GXJGitTest",
[string]$user = "domain\user",
[string]$token = "password/PAT"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
#Get project ID
$ProjectsUrl = "$collectionurl/_apis/projects"
$ProjectsResponse = Invoke-RestMethod -Uri $ProjectsUrl -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$projectid = ($ProjectsResponse.value | where {$_.name -eq $projectname}).id
#Get system.template
$PTurl = "$collectionurl/_apis/projects/$projectid/properties"
$response = Invoke-RestMethod -Uri $PTurl -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$ProcressTemplate = ($response.value | where {$_.name -eq 'System.Process Template'}).value
Clear-host
Write-Host "The project $projectname is using the $ProcressTemplate Process Template."
If you use 1 from 3 built-in templates (Agile, Scrum, CMMI) you can check which work item type you have:
Agile - User story
Scrum - Product Backlog Item
CMMI - Requirement
If you use a custom template you can check the process template with rest API:
Get http://yourServer:8080/tfs/DefaultCollection/_apis/projects/TestTemplate?includeCapabilities=true&api-version=1.0
You could get the result about the template like the following:
"capabilities": {
"processTemplate": {
"templateName": "Test"
},

Create jenkins JLNP slave programmatically

I am able to create a new node via the Jenkins web GUI and then have the node running in a container connect back to the Jenkins master via the name and -secret value
ex.
docker run jenkinsci/jnlp-slave -url http://jenkins-server:port <secret> <slave name>
Is there a way to programmatically create a Jenkins node and get the secret and slave name so I don't have to do it via the GUI?
Creating an agent programmatically
You can use the create-node CLI command to create new agents with a given configuration.
For example, given this minimal JNLP agent configuration in a file config.xml:
<slave>
<remoteFS>/opt/jenkins</remoteFS>
<numExecutors>2</numExecutors>
<launcher class="hudson.slaves.JNLPLauncher" />
</slave>
you can run the create-node command via the CLI client, or the SSH interface:
cat config.xml | java -jar jenkins-cli.jar -s https://jenkins/ create-node my-agent
Viewing agent configuration
To see what the XML configuration looks like for an existing agent, you can append config.xml to an agent URL, e.g. https://jenkins/computer/some-agent-name/config.xml, or you can use the get-node CLI command.
Fetching the per-agent secret programmatically
To fetch the secret hex value without using the Jenkins web UI, you can run a script via the groovy CLI command:
echo 'println jenkins.model.Jenkins.instance.nodesObject.getNode("my-agent")?.computer?.jnlpMac' \
| java -jar ~/Downloads/jenkins-cli.jar -s https://jenkins/ groovy =
This will return the secret value directly. Note that in order to use the groovy command via the SSH interface, you need Jenkins 2.46 or newer. In earlier versions, it only works via the CLI client.
You can also create an agent using the REST API. This is especially useful when having an apache proxy in front (see issue JENKINS47279) and no direct access to the jenkins otherwise (e.g. in a corporate network) where CLI will not work.
I recommend to create an API token for this purpose. Then you can do something like this
Linux (Bash)
export JENKINS_URL=https://jenkins.intra
export JENKINS_USER=papanito
export JENKINS_API_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxx
export NODE_NAME=testnode
export JSON_OBJECT="{ 'name':+'${NODE_NAME}',+'nodeDescription':+'Linux+slave',+'numExecutors':+'5',+'remoteFS':+'/home/jenkins/agent',+'labelString':+'SLAVE-DOCKER+linux',+'mode':+'EXCLUSIVE',+'':+['hudson.slaves.JNLPLauncher',+'hudson.slaves.RetentionStrategy\$Always'],+'launcher':+{'stapler-class':+'hudson.slaves.JNLPLauncher',+'\$class':+'hudson.slaves.JNLPLauncher',+'workDirSettings':+{'disabled':+true,+'workDirPath':+'',+'internalDir':+'remoting',+'failIfWorkDirIsMissing':+false},+'tunnel':+'',+'vmargs':+'-Xmx1024m'},+'retentionStrategy':+{'stapler-class':+'hudson.slaves.RetentionStrategy\$Always',+'\$class':+'hudson.slaves.RetentionStrategy\$Always'},+'nodeProperties':+{'stapler-class-bag':+'true',+'hudson-slaves-EnvironmentVariablesNodeProperty':+{'env':+[{'key':+'JAVA_HOME',+'value':+'/docker-java-home'},+{'key':+'JENKINS_HOME',+'value':+'/home/jenkins'}]},+'hudson-tools-ToolLocationNodeProperty':+{'locations':+[{'key':+'hudson.plugins.git.GitTool\$DescriptorImpl#Default',+'home':+'/usr/bin/git'},+{'key':+'hudson.model.JDK\$DescriptorImpl#JAVA-8',+'home':+'/usr/bin/java'},+{'key':+'hudson.tasks.Maven\$MavenInstallation\$DescriptorImpl#MAVEN-3.5.2',+'home':+'/usr/bin/mvn'}]}}}"
curl -L -s -o /dev/null -v -k -w "%{http_code}" -u "${JENKINS_USER}:${JENKINS_API_TOKEN}" -H "Content-Type:application/x-www-form-urlencoded" -X POST -d "json=${JSON_OBJECT}" "${JENKINS_URL}/computer/doCreateItem?name=${NODE_NAME}&type=hudson.slaves.DumbSlave"
In order to get the agent secret via REST API checkout this, which would look something like this:
curl -L -s -u ${JENKINS_USER}:${JENKINS_API_TOKEN} -X GET ${JENKINS_URL}/computer/${NODE_NAME}/slave-agent.jnlp | sed "s/.*<application-desc main-class=\"hudson.remoting.jnlp.Main\"><argument>\([a-z0-9]*\).*/\1/"
Windows (PS)
And here my solution for Windows using Powershell:
$JENKINS_URL="https://jenkins.intra"
$JENKINS_USER="papanito"
$JENKINS_API_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxx"
$NODE_NAME="testnode-ps"
# https://stackoverflow.com/questions/27951561/use-invoke-webrequest-with-a-username-and-password-for-basic-authentication-on-t
$bytes = [System.Text.Encoding]::ASCII.GetBytes("${JENKINS_USER}:${JENKINS_API_TOKEN}")
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = #{ Authorization = $basicAuthValue; }
$hash=#{
name="${NODE_NAME}";
nodeDescription="Linux slave";
numExecutors="5";
remoteFS="/home/jenkins/agent";
labelString="SLAVE-DOCKER linux";
mode="EXCLUSIVE";
""=#(
"hudson.slaves.JNLPLauncher";
'hudson.slaves.RetentionStrategy$Always'
);
launcher=#{
"stapler-class"="hudson.slaves.JNLPLauncher";
"\$class"="hudson.slaves.JNLPLauncher";
"workDirSettings"=#{
"disabled"="true";
"workDirPath"="";
"internalDir"="remoting";
"failIfWorkDirIsMissing"="false"
};
"tunnel"="";
"vmargs"="-Xmx1024m"
};
"retentionStrategy"=#{
"stapler-class"= 'hudson.slaves.RetentionStrategy$Always';
'$class'= 'hudson.slaves.RetentionStrategy$Always'
};
"nodeProperties"=#{
"stapler-class-bag"= "true";
"hudson-slaves-EnvironmentVariablesNodeProperty"=#{
"env"=#(
#{
"key"="JAVA_HOME";
"value"="/docker-java-home"
};
#{
"key"="JENKINS_HOME";
"value"="/home/jenkins"
}
)
};
"hudson-tools-ToolLocationNodeProperty"=#{
"locations"=#(
#{
"key"= 'hudson.plugins.git.GitTool$DescriptorImpl#Default';
"home"= "/usr/bin/git"
};
#{
"key"= 'hudson.model.JDK\$DescriptorImpl#JAVA-8';
"home"= "/usr/bin/java"
};
#{
"key"= 'hudson.tasks.Maven$MavenInstallation$DescriptorImpl#MAVEN-3.5.2';
"home"= "/usr/bin/mvn"
}
)
}
}
}
#https://stackoverflow.com/questions/17929494/powershell-convertto-json-with-embedded-hashtable
$JSON_OBJECT = $hash | convertto-json -Depth 5
$JSON_OBJECT
Invoke-WebRequest -Headers $headers -ContentType "application/x-www-form-urlencoded" -Method POST -Body "json=${JSON_OBJECT}" -Uri "${JENKINS_URL}/computer/doCreateItem?name=${NODE_NAME}&type=hudson.slaves.DumbSlave"
Just chiming in a bit late to the party here, but I would highly recommend looking at the Jenkins Client plugin instead. Once the plugin is installed, you need only to start the client JAR from the build node and give it the IP address of the master.
As far as the master goes, you don't need to bother configuring anything. Nodes that register with the master are available automatically to start executing jobs. This is much easier than any of the slave.jar-based approaches.

Invoke-wmimethod win32_process

Background: I am creating a script to send out a message to everyone in my Domain. I was able to complete this using Invoke-WMImethod and MSG.exe. However, my supervisor wants a more customizable message to be sent. Like changing Color, font size, font style...etc. Which i have created using PowerShell.
Script:
Invoke-WmiMethod -ComputerName $Computer -Class Win32_Process -Name Create -ArgumentList {"C:\x\x\x\Powershell.exe -File `"\\Server\Share\Folder\Script.ps1`""}
When i run this script against my Computer it works perfectly. However, when i attempt to run it on a remote computer it fails.
I don't understand why.
It's the same exact script that i used with MSG.exe, which worked, but it still doesn't work with a powershell script.
I attempted to copy the script to the remote computers 'C:\' and run it from that file path but it still didn't work.
I've verified the file path to Powershell.exe is the same as the script and that the remote workstation can access the .PS1 Script.
However, the script does run and says it is successful with a Return Value of 0. Example:
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ProcessId : 8748
ReturnValue : 0
My Suggestion would be to check for the versions on both the machines. The CmdLet you using may not be working on the previous version.
I again have a suggestion to make, you can use the below command to get your work done, if you have powershell Version 3 or above.
$Outputreport = "Test message to send data using port 443"
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
$wc = new-object System.Net.WebClient
Invoke-RestMethod -Method Post https://hostnamedotcom/cgi-bin/dir-path/$hostname-filename -Body $Outputreport

Resources