Copy output powershell TFS data into an excel sheet - powershell

I am querying TFS with TFPT.exe and powershell as shown below:
$TFSSERVER = "http://tfsserveraddress"
Function Get-WorkItem {
$query = "SELECT [System.Id], [System.Title], [System.State], [Completed Work] FROM WorkItems " +
"WHERE [System.AssignedTo] = 'xyz ' " +
"AND [System.State] <> 'Closed' " +
"AND [System.State] <> 'Resolved' " +
"ORDER BY [System.Id]"
tfpt query /collection:$TFSSERVER /wiql:$query /include:data >work.xls }
In the above code I am able to view the data as expected but I am trying to create and copy the data into an excel sheet which is not happening.
Can anyone please help me how to copy the output data into an excel sheet or in xml format.Pleas ehelp
Thank you.

Not having access to TFS server, I'm assuming that tfpt query command produces a table of data, which PowerShell converts to a PSObject.
This should produce a valid CSV file, which can be opened in Excel:
$data = tfpt query /collection:$TFSSERVER /wiql:$query /include:data
Export-Csv -Path "c:\temp\file.csv" -InputObject $data -NoTypeInformation
Note: You need PowerShell v.3 to run Export-Csv.

Related

Powershell: How to pick 1 result of many from Invoke-Sqlcmd Select statement

When I run a SELECT statement using Invoke-Sqlcmd, I'd like to choose 1 out of X results to move forward with a loop. In the example below, I have multiple results for 'Bob' and I'd like to choose the appropriate one to continue working with the query to update his favFood (I know I don't have the code there but just giving an example of what I have so far)
$nameList = $(Write-Host "Enter a list of Names seperated by a comma (ex.`"Bob, Rick, Jordan\`"): " -ForegroundColor Green -NoNewline; Read-Host)
$nameList = $nameList.Split(', ')
ForEach ($element in $nameList)
{
Invoke-Sqlcmd -Server Server01 -database People -Query ` "SELECT firstName, lastName, address, favFood`
FROM People ` WHERE firstName = '$element'" }
Is there a way I can list a first name and have the program ask me which of X results I'd like to update?
I'm honestly a bit stumped on how to choose the specific row/person out of X results to update.
Small side-note/bonus points: When running the program it complains about a "Missing argument in parameter list." as I'm writing down the names even though it will accept and return results as expected (I am separating the names by a space and comma ex. "Bob, Ross, Jay"
In theory you don't need a loop at all, you could use the SQL IN operator and pass all the names of $nameList to your query. Then once you have stored the $result of your query, you can use Out-GridView -PassThru to have a popup DataGridView for you to choose a row, which would be stored in $choice.
Write-Host 'Enter a list of Names seperated by a comma (ex."Bob, Rick, Jordan"): ' -ForegroundColor Green -NoNewline
$nameList = (Read-Host).Split(',').Trim()
# $namelist would become Bob','Rick','Jordan
$nameList = $nameList -join "','"
$result = Invoke-Sqlcmd -Server Server01 -Database People -Query #"
SELECT firstName, lastName, address, favFood
FROM People WHERE firstName IN ('$namelist');
"#
$choice = $result | Out-GridView -PassThru

PowerShell dbatools Invoke-DbaQuery with UNC file

Within PowerShell, I want to run the Invoke-DbaQuery dbatools command and use a UNC path with the -File parameter:
Invoke-DbaQuery -SQLInstance $SQL_host -Database $DatabaseName -File "\\file_svr\scriptdir\userlist.sql"
The command runs without error but doesn't produce any output. Does anyone know if this is possible? If so, what am I missing?
It turns out that the call has been working but the output was not visible. This is because the script has code like this:
DECLARE UserCursor CURSOR FOR
SELECT
'CREATE USER ' + SPACE(1) + QUOTENAME([name]) + ' FOR LOGIN ' + QUOTENAME([name]) + ' WITH DEFAULT_SCHEMA = ' + QUOTENAME([default_schema_name]) + ';'
AS [-- SQL STATEMENTS --]
FROM sys.database_principals AS rm
WHERE [type] IN ('U', 'S', 'G') -- windows users, sql users, windows groups
AND [name] <> 'dbo'
AND [name] <> 'guest'
AND default_schema_name is not null
OPEN UserCursor
FETCH NEXT FROM UserCursor INTO #addUserScript
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT #addUserScript
FETCH NEXT FROM UserCursor INTO #addUserScript
END
CLOSE UserCursor
DEALLOCATE UserCursor;
The solution then was to call the script like this:
Invoke-DbaQuery `
-SQLInstance $HCM_SQL_host `
-Database $Refresh_database `
-Verbose 4>&1 `
-File "\\file-srv0\scriptdir\Userlist.sql" | `
out-string -Width 250 | Out-File -FilePath $Create_Users_File_Fullname
Note the line "-Verbose 4?&1 `" that redirects the verbose output (i.e. the PRINT output) back to the standard output and, ultimately, the file.

Powershell select where not in

I have a Powershell script where I select all the values (they are numeric) from the column of a tab in an Excel sheet. It works but I want to exclude numbers that are returned from a select from an Oracle table. For the moment I just want to get the select "where not in" functioning, I will worry about putting the values I want excluded into an array later.
My Powershell select is below
$Table = "Inventory Parts$"
$qry = "select [Part No] from [{0}]" -f $Table;
$cmd.CommandText = $qry;
$da.SelectCommand = $cmd;
$dt = new-object System.Data.dataTable("$($Table)");
$null = $da.fill($dt);
I select from the tab (Inventory Parts) and assign it to a data table. How do I put in "where not in" to the select? If I could just have an array hardcoded with values and use that as the values for "where not in" it would be start. After that I will instead populate the array from the Oracle table.
Thank you for any replies.
Edit:
I have got as far as populating an array with the values I want in the "where not in" clause (see below).
$queryString = "select PART_NO from INVENTORY_PART_CFV WHERE PART_NO like
'100009%' "
$array = New-Object System.Collections.ArrayList
$command = new-Object
System.Data.OracleClient.OracleCommand($queryString, $connection)
$connection.Open()
$rdr = $command.ExecuteReader();
Foreach($row in $rdr)
{
$array.add( $row.Item("PART_NO") )
}
They go into the array "$array" but I need to append this on to my select statement
"select PART_NO from INVENTORY_PART_CFV WHERE PART_NO NOT IN " + $array
I don't know how to do this though.

PowerShell - count accdb rows for all the files in folder at once

I know I can count how many rows a csv has without opening it by using powershell.
example:
import-csv C:\MyFolde\myfile.csv | Measure-Object
I need to do this for multiple access files (.accdb). This time for every (and all) file/s in a given folder, and then I want to sum the rows up (total sum for all the files in that folder combined). Is there a solution for this?
Thank you
For the benefit of future visitors, here is a PowerShell script that counts all of the rows in the non-system tables of every .accdb file in the specified folder:
$connStrStub = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
$numFiles = 0
$numTables = 0
$totalRows = 0
foreach ($f in Get-ChildItem -Path C:\Users\Public\test\*.accdb)
{
$numFiles++
$conn = New-Object System.Data.OleDb.OleDbConnection ($connStrStub + $f.FullName)
$conn.Open()
$schemaTable = $conn.GetSchema("TABLES")
foreach ($dtRow in $schemaTable)
{
$tblName = $dtRow["TABLE_NAME"]
if (!$tblName.StartsWith("MSys"))
{
$numTables++
$cmd = New-Object System.Data.OleDb.OleDbCommand "SELECT COUNT(*) AS n FROM [$tblName]", $conn
$totalRows += $cmd.ExecuteScalar()
}
}
$conn.Close()
}
write-output "files: $numFiles"
write-output "user_tables: $numTables"
write-output "total_rows: $totalRows"
I gave up trying to use powershell.
However I managed to count all the rows by using SQl Service Integration Services. Used a foreach (to loop through all the files), inside of the loop a task which has a select count from each file and outputs the result into an xls.
Thank you all for your time

Loop through a query in powershell TFS

I am new to TFS and powershell scripting.As a part of my assignment I got a task in which
I have an array with TFS workitem ID's and I need to loop through and
get the details of those id's and display the result.
As a part of it I tried as shown below
$TFSSERVER = "https://server"
$WId = #("1", "2", "3", "4")
$arr = #("")
$i = 0
Function Get-WorkItemData($WId)
{
foreach($Id in $WId)
{
$i++
$query = "SELECT [System.Id]
FROM WorkItemLinks " +
"WHERE [Source].[System.id] = $Id" +
"AND [System.Links.LinkType] = 'Parent'"
if($WId.length -ge $i)
{
$arr+= $query
}
}
$wiData = tfpt query /collection:$TFSSERVER /wiql:$arr
$wiData | out-file "C:\Path"
}
Here is the error i get when i run the script
TFPT.EXE : Expecting end of string. The error is caused by ½SELECT╗.
At line:28 char:22
+ $wiData = tfpt <<<< query /collection:$TFSSERVER /wiql:$b
+ CategoryInfo : NotSpecified: ( Expecting end ...ed by ½SELECT╗.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Can anyone please help me to how to resolve the error and get list of all details. Please help me.
I do not know if this will resolve your error, but you at the very least have syntax issues on the line that starts with $query= as well as the following line. To fix this I would probably go with long single lined string (which in effect is what you are doing as is) or a HereString (if your executable allows for that).
A single lined string would work for you, and while it is long and a bit more troublesome to read it does avoid issues like what you are running into.
$query = "SELECT [System.Id] FROM WorkItemLinks WHERE [Source].[System.id] = $id AND [System.Links.LinkType] = 'Parent'"
A HereString is formatted similarly to what you have above, but may not be compatible with your application. It is formatted where the first line is #" with nothing after it, then however many lines of text that you want, then a line starting with "#. So in your case it would look like:
$query = #"
SELECT [System.Id]
FROM WorkItemLinks
WHERE [Source].[System.id] = $Id
AND [System.Links.LinkType] = 'Parent'
"#
This may not work for your needs, as I don't know if your TFPT.EXE application will accept a multi-line string as input for the query (and have serious doubts about it allowing it).
If you really, really want to continue formatting it like you have you can continue to do so, you just need to fix the first and second lines of that section at the least:
$query = "SELECT [System.Id] " +
"FROM WorkItemLinks " +
"WHERE [Source].[System.id] = $Id " +
"AND [System.Links.LinkType] = 'Parent';"