I have a script that extracts data from an XML file and put this into an CSV file with 2 columns.
The file looks like this:
Name, Count
1,34
3,55
15,66
103,99
etc.
So far so good...
My problem is that the program that reads the CSV-file always expect 3 digits in the column "Name".
So the CSV-file need to look like this:
Name, Count
001,34
003,55
015,66
103,99
etc.
How can I do this formatting using "Export-CSV"?
Please help I'm stuck here..
There are several ways to apply the changes to the csv file.
Read/Import to a variable, change name, Export-Csv variable
$Csv = Import-Csv .\Sample.csv
$Csv | ForEach-Object{ $_.Name = $_.Name.PadLeft(3,'0') }
$Csv | Export-Csv .\NewSample.csv -NoTypeInformation
Do the same on the fly with a calculated property reusing the same header/property name.
Import-Csv .\Sample.csv |
Select-Object #{n='Name';e={$_.Name.PadLeft(3,'0')}},Count|
Export-Csv .\NewSample2.csv -NoTypeInformation
Use the -f ( format ) operator with variable
i.e.
[int] $int = 25;
"{0:D3}" -f $int
Here 3 is a number of digits and Output will be :
025
Related
I have two files. One is called allper.csv
institutiongroup,studentid,iscomplete
institutionId=22343,123,FALSE
institutionId=22343,456,FALSE
institutionId=22343,789,FALSE
The other one is called actswithpersons.csv
abc,123;456
def,456
ghi,123
jkl,123;456
Note: The actswithpersons.csv does not have headers - they are going to be added in later via an excel power query so don't want them in there now. The actswithpersons csv columns are delimited with commas - there are only two columns, and the second one contains multiple personids - again Excel will deal with this later.
I want to remove all rows from allper.csv where the personid doesn't appear in actswithpersons.csv, and export them to another csv. So in the desired outcome, allper.csv would look like this
institutiongroup,studentid,iscomplete
institutionId=22343,123,FALSE
institutionId=22343,456,FALSE
and the export.csv would look like this
institutiongroup,studentid,iscomplete
institutionId=22343,789,FALSE
I've got as far as the below, which will put into the shell whether the personid is found in the actswithpersons.csv file.
$donestuff = (Get-Content .\ActsWithpersons.csv | ConvertFrom-Csv); $ids=(Import-Csv .\allper.csv);foreach($id in $ids.personid) {echo $id;if($donestuff -like "*$id*" )
{
echo 'Contains String'
}
else
{
echo 'Does not contain String'
}}
However, I'm not sure how to go the last step, and export & remove the unwanted rows from allper.csv
I've tried (among many things)
$donestuff = (Get-Content .\ActsWithpersons.csv | ConvertFrom-Csv);
Import-Csv .\allper.csv |
Where-Object {$donestuff -notlike $_.personid} |
Export-Csv -Path export.csv -NoTypeInformation
This took a really long time and left me with an empty csv. So, if you can give any guidance, please help.
Since your actswithpersons.csv doesn't have headers, in order for you to import as csv, you can specify the -Header parameter in either Import-Csv or ConvertFrom-Csv; with the former cmdlet being the better solution.
With that said, you can use any header name for those 2 columns then filter by the given column name (ID in this case) after your import of allper.csv using Where-Object:
$awp = (Import-Csv -Path '.\actswithpersons.csv' -Header 'blah','ID').ID.Split(';')
Import-Csv -Path '.\allper.csv' | Where-Object -Property 'Studentid' -notin $awp
This should give you:
institutiongroup studentid iscomplete
---------------- --------- ----------
institutionId=22343 789 FALSE
If you're looking to do it with Get-Content you can split by the delimiters of , and ;. This should give you just a single row of values which you can then compare the entirety of variable ($awp) using the same filter as above which will give you the same results:
$awp = (Get-Content -Path '.\actswithpersons.csv') -split ",|;"
Import-Csv -Path '.\allper.csv' | Where-Object -Property 'Studentid' -notin $awp
I have a CSV File and in Column 1 are words.
I want to modify the words, for example I want to add the String "cat" at the end and write it down in Column 2.
I've posted a Question days ago where #Theo archived this:
$CSV = Import-CSV -Path 'C:\path.csv' -Header Column1
$newCsv = foreach ($row in $CSV) {
# output an Object that gets collected in variable $newCsv
# Select-Object * takes everything already in $row,
# #{Name = 'Column2'; Expression = {$row.Column1 + 'cat'}} adds the extra column to it.
$row | Select-Object *, #{Name = 'Column2'; Expression = {$row.Column1 + '-cat'}}
}
# output on screen:
$newCsv
# output to new CSV file
$newCsv | Export-Csv -Path 'C:\path.csv' -NoTypeInformation
Output (on screen):
Column1 Column2
------- -------
Wild Wildcat
Copy Copycat
Hell Hellcat
Tom Tomcat
Snow Snowcat
As far as good, now I want to create and write down a Password in Column 3.
So I would create a variable with a randomized Password with some of the many PS generators already posted online.
And I also would like to declare Column1 and Column2 as a variable because I need those 3 Column entries further down the road to create a .txt File that include those.
Just if you curious why the hell do I create a .txt File AND a CSV:
Column1 is basicly a Systemname, Column2 Username and Column3 a Password.
I document access data in the CSV and create a Script in the .txt, so I can create the User in the Exchange by Script (for about 1000+ Systems).
I appreciate any hint!
I need to take a number such as:
59.234 and make it 00:59.234
and
1:01.555 01:01.555
I need to perform this on a column in a csv file.
If your input csv file looks anything like this:
"Something","Time","MoreStuff"
"whatever","59.234","whereever"
"etcetera","1:01.555","and so forth"
you can use below code to format the time values as you need them:
$csv = Import-Csv -Path 'D:\Test\thefile.csv'
$csv | ForEach-Object {
# get the field to format. in this demo it is $_.Time
$whole, $fraction = ($_.Time -replace '[:,]').PadLeft(8, '0') -split '\.'
# overwrite the field with the formatted time string
$_.Time = '{0}:{1}.{2}' -f $whole.Substring(0,2), $whole.Substring(2,2), $fraction.PadRight(3, '0')
}
# output on screen
$csv
# write to new file
$csv | Export-Csv -Path 'D:\Test\theNewfile.csv' -NoTypeInformation
Output on screen:
Something Time MoreStuff
--------- ---- ---------
whatever 00:59.234 whereever
etcetera 01:01.555 and so forth
This might not be graceful but it might work depending on how the format looks like if you have a smaller or larger number. Eg. 1:59.234 or just 23.
$CSV | select-object #{ Name = "MyTimeSpan"; Expression = { [System.TimeSpan]::Parse(("00:00:" + $_.ColumnName).Substring(("00:00:" + $_.ColumnName).Length - 12,12)) }}
I have a CSV file with 2 columns, latitude & longitude. I am trying to merge the 2 columns into 1, separated by a comma (no spaces).
Input CSV file, first 5 rows
latitude longitude
35.1868 -106.6652
42.3688 -83.4799
40.3926 -79.9052
40.5124 -88.9883
38.5352 -90.0006
My goal is to take this CSV and create a new one with a single column with both values separated by a comma (no spaces in-between) using PowerShell. See the desired output below...
location
35.1868,-106.6652
42.3688,-83.4799
40.3926,-79.9052
40.5124,-88.9883
38.5352,-90.0006
Any help will be greatly appreciated!
The IMO easiest way is a Select-Object with a calculated property
Import-Csv .\input.csv |
Select-Object #{Name='Location';Expression={$_.latitude,$_.longitude -join ','}} |
Export-Csv .\output.csv -NoTypeInformation
> Get-Content .\output.csv
"Location"
"35.1868,-106.6652"
"42.3688,-83.4799"
"40.3926,-79.9052"
"40.5124,-88.9883"
"38.5352,-90.0006"
Edit
In case there are other columns which should not be affected by the merge,
see this modified Select-Object
Select-Object *,#{N='Location';E={$_.latitude,$_.longitude -join ','}} -Exclude latitude,longitude|
But the new column will then be the last one.
the 1st ten lines are just a way to embed sample data in a script without needing to write it to a file & then read it back in. [grin]
use Import-CSV to get the real data into the script.
# fake reading in a CSV file
# in real life, use Import-CSV
$InStuff = #'
latitude, longitude
35.1868, -106.6652
42.3688, -83.4799
40.3926, -79.9052
40.5124, -88.9883
38.5352, -90.0006
'# | ConvertFrom-Csv
$LocationList = foreach ($IS_Item in $InStuff)
{
[PSCustomObject]#{
Location = #($IS_Item.Latitude, $IS_Item.Longitude) -join ','
}
}
# on screen
$LocationList
# CSV file
$LocationList |
Export-Csv -LiteralPath "$env:TEMP\JohnnyCarino_LocationList.csv" -NoTypeInformation
screen output ...
Location
--------
35.1868,-106.6652
42.3688,-83.4799
40.3926,-79.9052
40.5124,-88.9883
38.5352,-90.0006
CSV file content ...
"Location"
"35.1868,-106.6652"
"42.3688,-83.4799"
"40.3926,-79.9052"
"40.5124,-88.9883"
"38.5352,-90.0006"
I have a CSV file with about 10 columns separated with a ; (semicolon). I would like to add another column which generates a hashkey for the first columns value.
Is there a possibility in Powershell to do this? Also are there short haskeys (up to 10 to 15 chars)?
Example:
Old:
10000;value2;value3....
New:
HashkeyOf10000;1000;value2;value3...
You can use a calculated property for adding a column to a CSV:
$csv = 'C:\path\to\your.csv'
(Import-Csv $csv -Delimiter ';') |
select -Property #{n='Hashkey';e={Calc-Hash $_.A}},* |
Export-Csv $csv -Delimiter ';' -NoType
Replace Calc-Hash with the actual name of your hash function and A with the actual name of the first column of your CSV.
The parentheses around Import-Csv are required to ensure that reading the file is completed before writing the output starts.