Generate a CSV File - csv

I am creating a powershell script, and one of the features is multi-user creation from a CSV.
I want it so after the script runs it clears the CSV file, then generates another with the correct headers.
Relevant Code
Script Beginning
[string]$csvpath = "multiusers.csv"
$csv = Import-Csv -Path "multiusers.csv"
Script End
Clear-Content $csvpath
Write-Output "User,First Name,Surname,Job Title,Department,Ticket Number,Managers First Name,Managers Surname" `n`n|FT -AutoSize >>multiusers.csv
In my mind, this should work, however all this does is create one large header.

You are using one long string as one column, seperate it to multiple strings first then Remove the | FT -AutoSize[...] Part, create a custom object row and use Export-CSV
Also, some of your columns contains spaces, you need to add quotes between them
Try this instead:
"" | Select User,"First Name",Surname,"Job Title",Department,"Ticket Number","Managers First Name","Managers Surname" | Export-csv multiusers.csv -NoTypeInformation
Another way using your string with split, like this:
$Columns = "User,First Name,Surname,Job Title,Department,Ticket Number,Managers First Name,Managers Surname" -split ","
"" | Select $Columns | Export-csv c:\multiusers.csv -NoTypeInformation
Or using Out-File if you don't want empty commas line.
$Columns = "User,First Name,Surname,Job Title,Department,Ticket Number,Managers First Name,Managers Surname" -split ","
(($Columns | % {'"{0}"' -f $_} ) -join ',') + "`n`n" | Out-File C:\multiusers.csv

Related

Out-File a csv with specific format/information

I'm having trouble getting my head around how to take the two "properties" of each object within a json and output them into a csv. The two properties are "name" and "jobtitle" and I figure there should be a way to extract them.
$employees= ConvertFrom-Json $json
foreach ($person in $employees.information) {
# $person.name $person.jobtitle
}
No need for a loop, that should be bread-and-butter PowerShell territory. Feed the collection to a pipeline, use Select-Object to pick out the properties you care about, and then feed the pipeline to Export-CSV which handles the CSV header row, putting them on the same line, putting commas between them, quoting, etc.
$employees = ConvertFrom-Json $json
$employees.information | Select-Object name, jobtitle | Export-CSV -Path out.csv -NoTypeInformation
The only weird bit is -NoTypeInformation which stops it from putting PowerShell-specific markers for Integer/String/etc. types in the CSV, things which Excel (for example) won't read.
e.g. three objects with X,Y,Z properties - select just X and Z, and make them a CSV:
PS C:\> $Things = #(
[PSCustomObject]#{X=1; Y=2; Z=3}
,[PSCustomObject]#{X=4; Y=5; Z=6}
,[PSCustomObject]#{X=7; Y=8; Z=9}
)
$Things | Select-Object X,Z | ConvertTo-Csv -NoTypeInformation
"X","Z"
"1","3"
"4","6"
"7","9"

PowerShell: Get 2 strings into a hashtable and out to .csv

PowerShell newbie here,
I need to:
Get text files in recursive local directories that have a common string, students.txt in them.
Get another string, gc.student="name,name" in the resulting file set from #1 and get the name(s).
Put the filename from #1, and just the name,name from #2 (not gc.student="") into a hashtable where the filename is paired with its corresponding name,name.
Output the hashtable to an Excel spreadsheet with 2 columns: File and Name.
I've figured out, having searched and learned here and elsewhere, how to output #1 to the screen, but not how to put it into a hashtable with #2:
$documentsfolder = "C:\records\"
foreach ($file in Get-ChildItem $documentsfolder -recurse | Select String -pattern "students.txt" ) {$file}
I'm thinking to get name in #2 I'll need to use a RegEx since there might only be 1 name sometimes.
And for the output to Excel, this: | Export-Csv -NoType output.csv
Any help moving me on is appreciated.
I think this should get you started. The explanations are in the code comments.
# base directory
$documentsfolder = 'C:\records\'
# get files with names ending with students.txt
$files = Get-ChildItem $documentsfolder -recurse | Where-Object {$_.Name -like "*students.txt"}
# process each of the files
foreach ($file in $files)
{
$fileContents = Get-Content $file
$fileName = $file.Name
#series of matches to clean up different parts of the content
#first find the gc.... pattern
$fileContents = ($fileContents | Select-String -Pattern 'gc.student=".*"').Matches.Value
# then select the string with double quotes
$fileContents = ($fileContents | Select-String '".*"').Matches.Value
# then remove the leading and trailing double quotes
$fileContents = $fileContents -replace '^"','' -replace '"$',''
# drop the objects to the pipeline so that you can pipe it to export-csv
# I am creating custom objects so that your CSV headers will nave nice column names
Write-Output [pscustomobject]#{file=$fileName;name=$fileContents}
} | Export-Csv -NoType output.csv

Issue while saving collection into csv using powershell

I have below powershell code using which am saving results into csv file but I couldnt save them in csv file.
[Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$SSASServerName = "SSAS_ServerName"
$SSASDB = "TESTDB"
$SSASServer = New-Object Microsoft.AnalysisServices.Server
$SSASServer.Connect($SSASServerName)
$SSASDatabase = $SSASServer.Databases.Item($SSASDB)
$SSASDatabase.Roles | Select-Object Name, Members | Export-Csv C:\dev\psout\test.Csv
pause
This script extracts name of the role and members associated to that role. one role can have multiple members.
I tried above script, it exports role but in Members field, I see string "Microsoft.AnalysisServices.RoleMemberCollection" for all the roles.
If I do not export to csv, I can view the members in either ps window or text file.
what am i missing?
You can only export values that can be represented as a string to a csv-file. Members is a collection-object that may include multiple RoleMember-objects, so you need use a calculated property to access the Name-property inside each RoleMember. How to approach this depends on the desired output.
You can join the objects Name-property to a single string
$SSASDatabase.Roles |
Select-Object Name, #{n="Members";e={ ($_.Members | % { $_.Name }) -join '; '}} |
Export-Csv C:\dev\psout\test.Csv -NoTypeInformation
Role1,"User1; User2"
Role2,"User3; User4"
Or you could make one row in the csv-file "per row per member" which I usually prefer since it's easier to filter in Excel.
$SSASDatabase.Roles | ForEach-Object {
#Store role-reference so we can access it later inside the member-foreach
$r = $_
$r.Members | ForEach-Object {
#Store member-reference so it's available inside Selec-Object
$m = $_
$r | Select-Object Name, #{n="Member";e={ $m.Name }}
}
} | Export-Csv C:\dev\psout\test.Csv -NoTypeInformation
Role1,User1
Role1,User2
Role2,User3
...

Find and Replace many Items with Powershell from Data within a CSV, XLS or two txt documents

So I recently have found the need to do a find and replace of mutliple items within a XML document. Currently I have found the code below which will allow me to do multiple find and replaces but these are hard coded within the powershell.
(get-content c:\temp\report2.xml) | foreach-object {$_ -replace "192.168.1.1", "Server1"} | foreach-object {$_ -replace "192.168.1.20", "RandomServername"} | set-content c:\temp\report3.xml
Ideally instead of hard coding the value I would like to find and replace from a list, ideally in a CSV or and XLSX. Maybe two txt file would be easier.
If it was from a CSV it could grab the value to find from A1 and the value to replace it with from B1 and keep looping down until the values are empty.
I understand I would have to use the get-content and the for each command I was just wondering if this was possible and how to go about it/ if anybody could help me.
Thanks in advance.
SG
#next line is to clear output file
$null > c:\temp\report3.xml
$replacers = Import-Csv c:\temp\replaceSource.csv
gc c:\temp\aip.xml | ForEach-Object {
$output = $_
foreach ($r in $replacers) {
$output = $output -replace $r.ReplaceWhat, $r.ReplaceTo
}
#the output has to be appended, not to rewrite everything
return $output | Out-File c:\temp\report3.xml -Append
}
Content of replaceSource.csv looks like:
ReplaceWhat,ReplaceTo
192.168.1.1,server1
192.168.1.20,SERVER2
Note the headers

Export Matches array object to CSV in Powershell

I have a powershell script to find particular instances and then export them to CSV. Here's an example of the way the code works
$items = "Hello Tim", "Hola Bob", "Hello Susan"
$filter = $items | Select-String -Pattern "Hello"
$filter | Select-Object Line, Matches | Export-Csv "C:\log.csv"
Invoke-Item "C:\log.csv"
When I run the Select-Object in PS, it's nicely formatted info like this:
However, when I export to CSV, it exports the whole object and writes it as the following string: System.Text.RegularExpressions.Match[]
How can I get it to export just the first match or a listing of all matches into a single field when writing to CSV?
Here is one way using a PSObject:
$items = "Hello Tim", "Hola Bob", "Hello Susan"
$filter = $items | Select-String -Pattern "Hello"
$filter | % {New-Object PSObject -property #{
Line = $_.Line
Matches = $_.Matches.Groups[0].Value}
} | Export-Csv "C:\log.csv" -NoTypeInformation
Quickly note that Matches is an array which may create issues exporting to a csv.
Try joining the array into a string with a chosen delimiter. I used "::" in my example.
$filter | Select Line, #{Expression={$_.Matches -join "::"}; Label="Matches"} | Export-Csv "C:\log.csv"