Putting CSV Data as is into a New CSV - csv

I have a CSV file with two columns; Identitiy, and User. the User column contains UserPrincipalNames, and the Identity column contains a name. What I'm trying to do is to take the Userprincipalnames and get the Displayname from them, which I am able to do.
What I can't figure out it how to get each rows Identity (which is already in the csv I imported) to be displayed alongside the newly found Displayname. I'm not using the Identity column to get anything, I just want to display the values again.
The code I'm using is this:
$accounts = ipcsv 'D:\code-folder\small-results.csv'
$accounts | % {
$Identity = $_.Identity
$User = $_.User
Get-MsolUser -UserPrincipalName $User | select Displayname
}
This gets the displayname, but nothing more. I tried placing the $Identity variable in the select, but that didn't work. I feel like there must be a simple solution to this.
For example,a row in the CSV file would look like this
But I want the output to look like this, but the output I'm getting leaves out the Identity, and I don't know how to have it added.

You can make a custom column with Select-Object (select):
$accounts = ipcsv 'D:\code-folder\small-results.csv'
$accounts | % {
$Identity = $_.Identity
$User = $_.User
Get-MsolUser -UserPrincipalName $User | select #{n='Identity';e={$Identity}},Displayname
}

I would create a new PSCustomObjectfor each row and pipe the result to Export-Csv:
$accounts = ipcsv 'D:\code-folder\small-results.csv'
$accounts | % {
[PSCustomObject] #{
Identity = $_.Identity
User = Get-MsolUser -UserPrincipalName $_.User | select Displayname
}
} | Export-Csv -Path 'D:\code-folder\small-results.csv' -NoTypeInformation

Related

Powershell - set Json to variable

So I'm making a MySQL query, and one of the columns is a chunk of json that I want to set a particular subset of info to a variable. Wondering if I can condense my code a little. Right now my code is:
$data = Query -Query "select * from TABLE where fqdn = 'testhost.mycompany.com'"
$json = $data.request | ConvertFrom-Json
$WhatIreallyWant = $json.build_request
Can I condense the last two lines? build_request is part of the request json.
You could use a pipeline like this
$WhatIWant = $data.request | ConvertFrom-Json | Select-Object -ExpandProperty build_request
or like suggested by TessellatingHeckler in the comments
$WhatIWant = ($data.request | ConvertFrom-Json).build_request

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
...

adding data or modifying data in powershell

I have a CSV file with users and dates in it.
I want to run a powershell script that will modify or add to that list.
I have the modify part down, but I can't get the script right to add a line.
Here is what I have.
The file is users.csv with the following data:
Username Date
Johnson 3/10/16
Smith 12/31/15
Brown 3/9/16
When the script runs, I want to check the username. if there is a match, update the date. if there isn't a match add a new line.
Here is my code:
Get time parts
$date=Get-Date -format d
Get username
$user=$env:username
import data and modify
($CSV= import-csv c:\users.csv -delimiter ',') | foreach {
if ($_.username -match $user) {
$_.date=$date
}
}
output
Export-csv c:\users.csv -notypeinformation -force
This will change the date for a user and export the file just fine.
I can't get the code write to read all the usernames and if there isn't a match to add a line at the end with a username and date.
I'm fairly new to powershell.
Thanks for your help
Charles
try this:
$date = Get-Date -format d
$user = $env:username
$csv = ipcsv c:\users.csv
$csv | % {if ($_.username -match $user) {$_.date = $date}}
if ($user -notin $csv.username) {$csv += [pscustomobject]#{Username = $user; Date = $date}}
$csv

Import only select data from json to powershell

I want to Import selected data from Json url and so I can convert it to XML.
I am using following code to import.
(Invoke-RestMethod -URI "http://www.broadbandmap.gov/broadbandmap/broadband/dec2013/wireline?latitude=29.488412&longitude=-98.550208&format=json").Results.wirelineServices.providerName | Select-Object | Format-Table –AutoSize
so I am using .Results.wirelineServices.providerName to pull selected columns from one branch/table.
how can I pull data from .Results.broadbandSource.stateFips also at same time?
Thanks bunch.
Json code screenshot.
follow up question
I think that you should separate out your steps a bit:
$r = Invoke-RestMethod -URI "http://www.broadbandmap.gov/broadbandmap/broadband/dec2013/wireline?latitude=29.488412&longitude=-98.550208&format=json"
$providers = $r.Results.wirelineServices.providerName
$stateFips = $r.Results.broadbandSource.stateFips
Note that in your example, your call to Select-Object is redundant (you're not selecting anything, so it's not changing the input object).
Also, a very important point about Format-Table (and any Format- cmdlet) is that those are for display only so they should always be the last thing you do, if in fact they're needed at all.
The code I've given gives you the information in objects, which you can then work with, filter or, display as needed. I'm not sure how you wanted to use/display it, but since there are multiple providers and only one stateFips value, I might assume that you would apply the Fips value to each provider. Here's an example of that which uses the $stateFips variable we created:
$r.Results.wirelineServices | Select-Object providerName,#{Name='stateFips' ; Expression={ $stateFips }}
And here's an example that uses only the original result $r:
$r.Results.wirelineServices | Select-Object providerName,#{Name='stateFips' ; Expression={ $r.Results.broadbandSource.stateFips }}
The Select-Object computed column syntax
Note that the second column definition looks a bit wonky. It's actually a hashtable that allows you to specify the name of the column, and an expression (a complete code block) whose return value will be the value of the column. It could be spread over multiple lines like this:
$r.Results.wirelineServices | Select-Object providerName,#{
Name = 'stateFips'
Expression = {
$r.Results.broadbandSource.stateFips
}
}
Or you could even create the hashtable as a variable first:
$computed = #{
Name = 'stateFips'
Expression = {
$r.Results.broadbandSource.stateFips
}
}
$r.Results.wirelineServices | Select-Object providerName,$computed
XML?
#Stephen Connolly's answer reminded me that you wanted to make XML out of this. Let's take the above code and assign it to a variable:
$computed = #{
Name = 'stateFips'
Expression = {
$r.Results.broadbandSource.stateFips
}
}
$data = $r.Results.wirelineServices | Select-Object providerName,$computed
Because $data is still an object and wasn't sent through a Format- command, we can still use it!
$xml = $data | ConvertTo-Xml -NoTypeInformation
As his comment also suggested though, we don't know how you wanted the resultant XML to be formatted.
So here's another approach:
Forget the JSON
$r = Invoke-RestMethod -URI "http://www.broadbandmap.gov/broadbandmap/broadband/dec2013/wireline?latitude=29.488412&longitude=-98.550208&format=xml"
Now $r contains XML already. You can filter it out and modify it using XPATH. I won't get into that at the moment unless you think that way would work better for you.
Hope this helps, let me know if I've misunderstood what you're trying to do here.
If you want a composite object try something like
$results = (Invoke-RestMethod -URI "http://www.broadbandmap.gov/broadbandmap/broadband/dec2013/wireline?latitude=29.488412&longitude=-98.550208&format=json")
$obj = $results.Results.wirelineServices
$obj | add-member -type noteproperty -Name StateFips -Value $($results.Results.broadbandSource.stateFips) -PassThru
$obj | convertto-xml -as string

delete the last column from a csv file in powershell

I am new to powershell. Currently we are in need of a poweshell script to compare two large (100000 rows and n columns (n > 300, also column headers are Dates corresponding to each wednesday). The value of n keeps on incrementing each week in the file. We need to compare the files (current week and last week), and need to make sure that the only difference between the two files is the last column.
I have gone through some Forums and Blogs and I could do only Little due to my ignorance.
If there is a way to drop the last column from a csv file in powershell, we may be able to make use of the below script below to compare the previous week's file and the current week's file after droping the last column from current week's file.
It would be really helpful if someone can help me here with your hard earned knowledge
[System.Collections.ArrayList]$file1Array = Get-Content "C:\Risk Management\ref_previous.csv"|Sort-Object
[System.Collections.ArrayList]$file2Array = Get-Content "C:\Risk Management\ref_current.csv"|Sort-Object
$matchingEntries = #()
foreach ($entry in $file1Array) {
if ($file2Array.Contains($entry)) {
$matchingEntries += $entry
}
}
foreach ($entry in $matchingEntries){
$file1Array.Remove($entry)
$file2Array.Remove($entry)
}
Cheers,
Anil
Assuming that the column name you want to exclude is LastCol (adjust to your actual column name):
$previous = Import-csv "C:\Risk Management\ref_previous.csv" | Select-Object -Property * -ExcludeProperty LastCol | Sort-Object;
$current = Import-csv "C:\Risk Management\ref_current.csv" | Sort-Object;
Compare-Object $previous $current;
This will drop the last column from each of the input files and indicate whether the remaining content differs.
Based on the answer that alroc gave, you should be able to get the last column name using a split operation on the first line of the CSV file, and then using that on the -ExcludeProperty parameter.
However, the Compare-Object command on this doesn't work for me, but it does pull back the right data into each variable.
$CurrentFile = "C:\Temp\Current.csv"
$PreviousFile = "C:\Temp\Previous.csv"
$CurrentHeaders = gc $CurrentFile | Select -First 1
$CurrentHeadersSplit = $CurrentHeaders.Split(",")
$LastColumn = $CurrentHeadersSplit[-1] -Replace '"'
$Current = Import-Csv $CurrentFile | Select -Property * -ExcludeProperty $LastColumn | Sort-Object
$Previous = Import-Csv $PreviousFile | Sort-Object
Compare-Object $Current $Previous
The import-csv and export-csv both give the opportunity to exclude columns.
The import-csv has the -header option and you simply name the incoming headers and exclude the last columns header. If there are 10 columns, only name 9. The last column will be excluded.
For export-csv, select the columns you'd like to write out ( |select col1,col2,col3|export-csv... ) and don't select the column you're trying to exclude.