Category Archives: Microsoft
Importing and Exporting CSV and XML Files in PowerShell
The Import-Csv cmdlet reads a CSV file and outputs a list of custom PowerShell objects, one for each row of the input data. PowerShell uses the first row of the CSV file as the objects’ properties, and the subsequent lines of the file are the output objects. For example, if you run the command.
Import-Csv Sample.csv
Import-Csv Sample.csv -Header DisplayName,EmailAddress
Import-Csv Sample.csv -Delimiter "`t"
Import-Csv Sample.csv | Sort-Object DisplayName | Select-Object Mail
Import-Csv Sample.Csv | ForEach-Object { '"{0}" <{1}>' -f $_.DisplayName,$_.Mail }
Exporting CSV FilesSometimes you need to create a CSV file from PowerShell output objects. To do so, you pipe PowerShell’s output to the Export-Csv cmdlet and specify a filename. PowerShell will then write the output objects to a CSV file. It really is that simple, with one minor caveat. By default, Export-Csv writes a line starting with the string #TYPE as the first line of the CSV file. Export-Csv’s -NoTypeInformation parameter omits this extra line of output, so I usually include this parameter.For example, suppose you want to create a copy of Sample.csv sorted by the DisplayName property. All you need to do is import the file, pipe its contents to the Sort-Object cmdlet, then export the contents to a new CSV file:
Import-Csv Sample.csv | Sort-Object DisplayName | Export-Csv Sample-Sorted.csv -NoTypeInformation
Get-ChildItem | Sort-Object Length | Select-Object FullName,LastWriteTime,Length | Export-Csv Data.csv -NoTypeInformation
This command creates a CSV file containing the files in the current directory, sorted by file size. Note that this command uses the Select-Object cmdlet to select each file’s full filename, last write time, and file size (length), so these three properties will be the columns in the CSV file.
Search string in log file with powershell
Search string use “or”
cat test.txt | where-object {$_.contains(“CREATE”)-or$_.contains(“date”)}
Search string use “and”
cat test.txt | where-object {$_.contains(“CREATE”)-and$_.contains(“date”)}
Search string and export to a test file
cat test.txt | where-object {$_.contains(“CREATE”)-or$_.contains(“date”)} | out-file test2.txt
Export to a CSV file
Get-Process | Export-Csv c:\scripts\test.csv
How Tomorrow’s Technologies Will Shape Your World
Idea Man: A Memoir by the Cofounder of Microsoft
Idea Man Part One: Roots
Idea Man Part Two: Lakeside to Boston
Idea Man Part Three: Albuquerque to Seattle
Idea Man Part Four: Journey to Space
Idea Man Part Five: Music
Idea Man Part Six: Mapping the Brain
Idea Man Part Seven: Giving Back
Idea Man Part Eight: Trail Blazers
Idea Man Part Nine: Seahawks
Idea Man Part Ten: Adventures