Powershell: Create CSV entries - powershell

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!

Related

Updating Active directory DN in csv records with Powershell

I'm completely stuck on how to update multiple rows in a CSV file with new values.. the issue is as follows, I import an active directory csv export file into my powershell which has roughly 500 users, like so:
$Users = Import-CSV "C:\Users\administrator\userExport.csv"
I then need to update the DN column so that they have the new active directory structure on the new domain
Current structure:
DN:
-----------------
CN=John Smith,OU=Users,DC=XTR,DC=ORG
Required new domain structure
DN:
-----------------
CN=John Smith,OU=Users,OU=Administration,DC=RTS,DC=LIVE,DC=LOCAL
The trouble is I have no idea how I can sequentially go through the entries in this CSV files to update only the necessary elements of the entry via powershell, any help with this would be much appreciated.
Sample line from csv file:
DN objectClass instanceType
-- ------------ ------------
CN=John Smith,OU=Users,DC=XTR,DC=ORG user 4
Apologies, I know how vague the request is but I'm sure there must be an elegant way of doing this but my powershell knowledge is extremely limited.
Thanks for your time.
Import-Csv will convert each row in the CSV to an object with properties corresponding to the column headers and the column value of the current row. This makes them easy to manipulate:
$Users = Import-CSV "C:\Users\administrator\userExport.csv"
$Users |ForEach-Object {
# Update DN column value
$_.DN = $_.DN -replace ',DC=XTR,DC=ORG$', ',OU=Administration,DC=RTS,DC=LIVE,DC=LOCAL'
# Output modified object
$_
} |Export-Csv C:\Users\administrator\userExportModified.csv -NoTypeInformation
You should put your CSV sample "as is", and not trying to format it. How can we know if the CSV is well-formed ?
I am trying to answer anyway, based on a well-formed CSV, with default delimiter (comma) :
Import-CSV "C:\Users\administrator\sourceUsers.csv" | ForEach {
$_.DN = $_.DN -replace "OU=Users,DC=XTR,DC=ORG","OU=Users,OU=Administration,DC=RTS,DC=LIVE,DC=LOCAL"
# ^
# Are you sure it is actually 'OU' here and not 'CN'
$_
} | Export-Csv "C:\Users\administrator\destinationUsers.csv" -NoTypeInformation -Enconding UTF8
If there is another delimiter, eg semi colon :
Import-CSV "C:\Users\administrator\sourceUsers.csv" -Delimiter ';' | ForEach {
$_.DN = $_.DN -replace "OU=Users,DC=XTR,DC=ORG","OU=Users,OU=Administration,DC=RTS,DC=LIVE,DC=LOCAL"
# ^
# Are you sure it is actually 'OU' here and not 'CN'
$_
} | Export-Csv "C:\Users\administrator\destinationUsers.csv" -NoTypeInformation -Enconding UTF8
Edit :
Mathias answered during I was typing my own one :), I keep it only because of my remarks about CSV and the 'OU=Users...'

Need 3 digits in column in a CSV-file

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

How to clean up some data in a csv file using Powershell scripting and save the result as a new csv file?

I have a csv (employees.csv) file of 3 columns contain 'n' number of employee details and in my first column i have employeeid in a format 11_22$(contain integers and non integer values-string) and here I want to remove all special characters and i want to keep only 1122(only integers).
In my second column I have their website address and is of format www.website.com and here i want to replace www by http that is i need http.website.com. In my third column i have their dob in format YYYY:MM:DD and i want to change it to DD:MM:YYYY format .
Finally i want to save/export the result to a new csv file. How can i achieve all these using PowerShell scripting?
Although i have no idea why you would want websites to become something like 'http.website.com' instead of 'http://website.com', you can do that using the code below.
########################################################################
# your input file 'employees.csv" looks like this
########################################################################
"employeeid","website","dob"
"11_22$","www.website.com","2000:04:12"
"22_33$","www.stackoverflow.com","1990:04:12"
"33_44$","www.somothersite.org","1970:04:12"
########################################################################
# after running the code the new file 'newemployees.csv' looks like this
########################################################################
"employeeid","website","dob"
"1122","http.website.com","12:04:2000"
"2233","http.stackoverflow.com","12:04:1990"
"3344","http.somothersite.org","12:04:1970"
$newcsv = #()
Import-Csv -Path $PSScriptRoot\employees.csv | ForEach-Object {
$newcsv += New-Object -TypeName PSObject -Property ([ordered]#{
employeeid = $_.employeeid -replace '\D+', ''
website = $_.website -replace 'www', 'http'
dob = ([datetime]::ParseExact($_.dob, 'yyyy:MM:dd', [System.Globalization.CultureInfo]::InvariantCulture)).toString('dd:MM:yyyy')
})
}
$newcsv | Export-Csv -Path $PSScriptRoot\newemployees.csv -Force -NoTypeInformation

Manipulate CSV files with Powershell (generate column for hashkey)

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.

Find and replace inside one csv column with powershell

I have a large CSV file that looks like this named student.export.text
Student Number,Last Name,Middle Name,First Name,Schoolid,Grade Level,Dob
I'm trying to build an automated task that will run nightly so that another piece of software can understand the CSV correctly.
Here is my code, but I'm missing something that is causing an error. I am new to Powershell and I am hoping for some advice.
Any help will be greatly appreciated!
$Replacements = #{
"5" = "AE";
"7" = "ER";
"10" = "FM";
"12" = "HC";
"14" = "JH";
"18" = "LE";
#...]
}
Import-Csv .\student.export.text | ForEach-Object {
$_.Schoolid = $Replacements[$_.Schoolid]
$_
} | Export-Csv -NoTypeInformation .\new.csv
Here's one approach that can work.
# declare hash table with School ID to School Name mapping
$schoolIdsToNames = #{
"3" = "SchoolA";
"4" = "SchoolB"
}
# import the CSV file
$csv = Import-Csv "C:\input.csv";
# for each row, replace the School ID field with the School Name
foreach($row in $csv)
{
$row.Schoolid = $schoolIdsToNames[$row.Schoolid];
}
# export the modified CSV
$csv | Export-Csv "C:\replaced.csv" -NoTypeInformation;
In the first step, we set up a PowerShell hashtable (a sort of key-value pair list), then import the CSV file using Import-Csv and store it in the $csv variable. This cmdlet will create an object from every row of the CSV that we can manipulate easily. For each row, we simply replace the Schoolid field with the value assigned to the ID key in the $schoolIdsToNames hashtable. Finally, we export the CSV to another file.
Another, more PowerShell-ly approach would be something like this:
Import-Csv "C:\test\school.csv" | Select-Object *, #{ Name = "SchoolName"; Expression = { $schoolIdsToNames[$_.Schoolid] } } | Export-Csv "C:\test\replaced2.csv" -NoTypeInformation
This one-liner imports the CSV and sends it down the pipeline. For each row, we select all properties of the row using Select-Object and add a new property called SchoolName, setting its value using the same hash table-based technique as above. Finally, we export the object list to CSV.