Powershell export to csv excel

В PowerShell для экспорта массивов данных в CSV файлы можно использовать командлет Export-CSV. В этой статье мы покажем, как экспортировать данные в CSV файл и добавить в него дополнительные строки.

CSV формат представляет собой текстовый файл для хранения табличных данных, в котором значения разделены специальным символом-разделителем. Командлет Export-CSV преобразует полученный объект PowerShell в список строк с разделителями и сохраняет эти строки в указанный файл.

Следующая команда экспортирует список служб Windows в CSV файл:

Get-Service |select-object Name,DisplayName,Status | Export-CSV "C:PSservices.CSV" -NoTypeInformation -Encoding UTF8

Откройте полученный CSV файл с помощью любого текстового редактора. Как вы видите, в первой строке указаны названия столбцов (атрибуты объекта PowerShell, в нашем примере вы выбрали определенные поля с помощью select-object), и далее построчно идут данные, разделенные запятыми.

выгрузка данных в CSV файл с помощью PowerShell

По-умолчанию в качестве разделителя (делиметера) в CSV используется запятая. Вы можете задать другой разделитель (точку с запятой, двоеточие и т.д.) с помощью параметра –Delimiter.

Например, укажем что в качестве разделителя нужно использовать точку с запятой:

Get-Service | Export-CSV "C:PSservices.CSV" -NoTypeInformation -Encoding UTF8 -Delimiter ";"

Вы можете использовать разделитель в зависимости от региональных настроек Windows. Для этого используется параметр -UseCulture.

Get-Process | Export-Csv "c:psprocess.csv" -UseCulture

Вы можете также получить разделитель по-умолчанию из региональных настроек Windows:

(Get-Culture).TextInfo.ListSeparator

По умолчанию командлет Export-CSV создает новый CSV файл (если файл уже существует, он перезаписывается/заменяется новым). Если вы хотите добавить новые строки в уже существующий CSV файл, нужно использовать параметр -Append.

Например, вы хотите по расписанию запускать PowerShell скрипт, который проверяет свободное место на диске и добавляет текущее значение в CSV файл:

$cur_time=get-date -Format u
$freedisksize=Get-CimInstance -Class Win32_LogicalDisk |Where-Object {$_.DeviceID -eq "C:"} |select DeviceID,FreeSpace

Теперь нужно добавить дату в таблицу (объект) в качестве одного из полей:

$freedisksize| add-member -membertype NoteProperty -name Date -value  $cur_time

Экспорт объекта PowerShell в CSV файл:

$freedisksize| Export-Csv -Path C:psfreespace.csv -Delimiter ";" -NoTypeInformation -Append

export-csv дописать данные в файл с помощью append

Также вы можете использовать следующие дополнительные параметры Export-CSV:

  • -Encoding – позволяет указать кодировку CSV файла (по умолчанию используется utf8NOBOM). В большинстве случае я указываю тут UTF8;
  • -Force – перезапишет доступный на чтение файл;
  • -NoClobber – не перезаписывать файл, если он существует;
  • -Header – добавить заголовок в CSV файл (если он отсутствует);
  • -IncludeTypeInformation/-NoTypeInformation –добавить/не добавлять в заголовок файла строку #TYPE с информацией о типе объекта (например,
    #TYPE System.Diagnostics.Process
    или
    #TYPE System.Service.ServiceController
    ). Начиная с PowerShell 6 информация TYPE в заголовке не выводится по-умолчанию;
  • UseQuotes (появился в версии PowerShell Core 7.x) – нужно ли заключать значения в кавычки или нет (AsNeeded/ Always (default)/Never)

В дальнейшем вы можете обрабатывать полученный CSV файл в Excel или других программах.

Командлет Export-CSV часто используется для построения различных табличных выгрузок и отчетов. Ниже несколько примеров полезных отчетов для системного администратора, которые можно сформировать с помощью Export-CSV:

  • Сформировать список компьютеров в AD c помощью Get-ADComputer
  • Получить информацию о пользователях через Get-ADUser
  • Найти неактивных пользователей/компьютеры в домене
  • Выгрузить информацию о входах пользователей в Azure
  • Экспортировать историю (логи) RDP подключений
  • Создать отчет со статусом активации Windows на компьютерах в домене.

Для загрузки (импорта) данных из CSV файла в PowerShell используется командлет Import-CSV.

Automate Excel with PowerShell without having Excel installedДанный материал является переводом оригинальной статьи «ATA Learning : Adam Bertram : PowerShell and Excel: Seize the Power!».

Microsoft Excel — один из тех вездесущих инструментов, от которых большинство из нас не может уйти, даже если хочет. Многие ИТ-специалисты используют Excel, как небольшую базу данных, в которой хранятся тонны данных в различных процедурах автоматизации. Каков наилучший сценарий автоматизации и Excel? Это, например, PowerShell!

Работу с таблицами Excel непросто автоматизировать. В отличие от менее функционального (и более простого) аналога файла CSV, книги Excel — это не просто текстовые файлы. Для работы со сложными книгами Excel потребует от PowerShell манипуляции с Component Object Model (COM), для чего раньше нужно было установить Excel. Однако, на самом деле, это вовсе не обязательно. Например, проницательный участник сообщества PowerShell, Doug Finke, создал модуль PowerShell, названный ImportExcel. Модуль устраняет сложность работы с Excel и позволяет легко работать с книгами Excel через PowerShell сценарии!

В этой статье рассмотрим пример того, что можно сделать в PowerShell и Excel с помощью модуля ImportExcel, а также рассмотрим несколько популярных вариантов использования.

Предварительные требования

При запуске модуля ImportExcel в системе Windows отдельные зависимости не требуются. Однако, если вы работаете с MacOS, вам необходимо установить пакет mono-libgdiplus, используя команду вида:

brew install mono-libgdiplus

Примечание: Все примеры в этой статье будут построены с использованием macOS, но все они должны работать и на других платформах. При использовании macOS, не забудьте перезапустить сеанс PowerShell, прежде чем продолжить.

Установка модуля ImportExcel

Начните с загрузки и установки модуля через PowerShell Gallery, запустив:

Install-Module ImportExcel -Scope CurrentUser

Через несколько секунд все будет в порядке.

Использование PowerShell для экспорта в рабочий лист Excel

Возможно, вы знакомы со стандартными командлетами PowerShell Export-Csv и Import-Csv. Эти командлеты позволяют читать и экспортировать объекты PowerShell в файлы CSV. К сожалению, в PowerShell нет таких же встроенных командлетов для Excel. Но, используя модуль ImportExcel, вы можете создать такой функционал!

Один из наиболее частых запросов системного администратора — это экспорт объектов PowerShell в рабочий лист Excel. С помощью командлета Export-Excel из модуля ImportExcel, вы можете легко сделать это. Командлет Export-Excel принимает любой объект точно так же, как делает Export-Csv. Этому командлету можно передать любой объект.

Например, возможно, вам нужно найти какие-то процессы, запущенные на вашем локальном компьютере, и поместить их в книгу Excel.

Чтобы найти процессы, запущенные в системе с помощью PowerShell, используйте командлет Get-Process, который возвращает каждый запущенный процесс и различную информацию о каждом процессе. Чтобы экспортировать эту информацию в Excel, используйте командлет Export-Excel, указывающий путь к создаваемой книге Excel. Вы можете увидеть пример команды и снимок экрана сгенерированного файла Excel ниже.

Get-Process | Export-Excel -Path './processes.xlsx

PowerShell command Export-Excel

Поздравляем! Вы экспортировали всю информацию точно так же, как Export-Csv, но, в отличие от Export-Csv, мы можем сделать эти данные намного интереснее. Убедитесь, что имя рабочего листа называется «Proccesses», данные находятся в таблице, а размер строк устанавливается автоматически.

Добавим к командлету параметр -AutoSize для автоматического изменения размера всех строк, -TableName, чтобы указать имя таблицы, которая будет включать все данные, и имя параметра -WorksheetName для процессов, и сможем увидеть на снимке экрана ниже, что в итоге получится.

Get-Process | Export-Excel -Path './processes.xlsx' -AutoSize -TableName 'Processes' -WorksheetName 'Proccesses'

PowerShell command Export-Excel as Table

Командлет Export-Excel имеет множество параметров, которые можно использовать для создания книг Excel всех видов. Для получения полной информации о возможностях Export-Excel, запустите:

Get-Help Export-Excel
Использование PowerShell для импорта в Excel

Итак, ранее вы экспортировали некоторую информацию в файл с именем process.xlsx. Возможно, теперь вам нужно переместить этот файл на другой компьютер и импортировать / прочитать эту информацию. Командлет Import-Excel к вашим услугам.

При простейшем использовании вам нужно только указать путь к документу / книге Excel с помощью параметра -Path, как показано ниже. Вы увидите, что он читает первый рабочий лист, в данном случае рабочий лист «Processes», и возвращает объекты PowerShell.

Import-Excel -Path './processes.xlsx'

PowerShell command Import-Excel

Может быть, у вас есть несколько листов в книге Excel? Вы можете прочитать конкретный рабочий лист с помощью параметра -WorkSheetname.

Import-Excel -Path './processes.xlsx' -WorkSheetname 'SecondWorksheet'

Вам нужно читать только определенные столбцы из рабочего листа Excel? Используйте параметр -HeaderName, чтобы указать только те параметры, которые вы хотите прочитать.

Import-Excel -Path './processes.xlsx' –WorkSheetname 'Processes' -HeaderName 'CPU','Handle'

Командлет Import-Excel имеет другие параметры, которые можно использовать для чтения книг Excel всех типов. Чтобы получить полное изложение всего, что может делать Import-Excel, запустите:

Get-Help Import-Excel
Использование PowerShell для получения (и установки) значений ячеек Excel

Теперь вы знаете, как читать весь лист Excel с помощью PowerShell. Но что, если вам нужно только одно значение ячейки? Технически вы можете использовать Import-Excel и отфильтровать нужное значение с помощью Where-Object, но это будет не слишком эффективно.

Вместо этого, используя командлет Open-ExcelPackage, вы можете «преобразовать» книгу Excel в объект PowerShell, который затем можно будет читать и изменять. Этот командлет аналогичен использованию New-Object -ComObject ‘Excel.Application’, если работать напрямую с COM-объектами.

Чтобы найти значение ячейки, сначала откройте книгу Excel, чтобы занести его в память. Затем выберите лист внутри книги.

$excel = Open-ExcelPackage -Path './processes.xlsx'
$worksheet = $excel.Workbook.Worksheets['Processes']

Этот процесс похож на способ открытия книг с помощью COM-объекта ‘Excel.Workbooks.Open’.

После того, как рабочий лист назначен переменной, вы можете перейти к отдельным строкам, столбцам и ячейкам. Возможно, вам нужно найти все значения ячеек в строке A1. Вам просто нужно сослаться на свойство ‘Cells’, указав индекс A1, как показано ниже.

$worksheet.Cells['A1'].Value

Вы также можете изменить значение ячеек на листе, присвоив другое значение, например:

$worksheet.Cells['A1'] = 'differentvalue'

Будучи хранимым в оперативной памяти, важно высвобождать пакет Excel с помощью командлета Close-ExcelPackage.

Close-ExcelPackage $excel
Конверсия Excel в файлы CSV с помощью PowerShell

Если у вас есть содержимое листа Excel, представленное с помощью объектов PowerShell, преобразование листов Excel в CSV просто требует отправки этих объектов в командлет Export-Csv.

Используя созданную ранее книгу processes.xlsx, прочтите первый рабочий лист, который получает все данные в объекты PowerShell, а затем экспортируйте эти объекты в CSV с помощью приведенной ниже команды.

Import-Excel './processes.xlsx' | Export-Csv -Path './processes.csv' -NoTypeInformation
Конверсия множества рабочих листов

Если у вас есть книга Excel с несколькими листами, вы также можете создать файл CSV для каждого листа. Для этого вы можете найти все листы в книге с помощью командлета Get-ExcelSheetInfo. Когда у вас есть имена рабочих листов, вы можете передать их в параметр -WorksheetName, а также использовать имя листа в качестве имени файла CSV.

Ниже вы можете найти необходимый пример кода.

$sheets = (Get-ExcelSheetInfo -Path './processes.xlsx').Name
foreach ($sheet in $sheets) {
 Import-Excel -WorksheetName $sheet -Path './processes.xlsx' | Export-Csv "./$sheet.csv" -NoTypeInformation
 }
Заключение

Используя модуль ImportExcel из библиотеки модулей PowerShell, вы можете импортировать, экспортировать и управлять данными в книгах Excel точно так же, как и в CSV, без установки Excel!

This article will discuss converting Excel Files (XLSX) to CSV using Windows PowerShell. We will see how to convert a single XLSX file, an Excel file with multiple worksheets, and, lastly, work through an example that shows how to convert all XLSX files into a folder to CSV.

The commands we will use in this post can be executed directly from PowerShell or inside a PowerShell script (a file with the extension .ps1). We will, however, be going with the second option in this article.

Converting a Single XLSX File into CSV

To demonstrate concepts in this Section, we will use the XLSX file saved as SalaryData2.xlsx with two sheets: Incomes and PersonalDetails.

Figure 1: A snapshot of the SalaryData2.xlsx file will be used in the examples. The file has two worksheets: Incomes and PersonalDetails.

The XLSX file can be converted into CSV in PowerShell by following these steps:

Step 0: Create a PowerShell Script to execute to perform the conversion

Save the following contents into a PowerShell script called xlsx_to_csv.ps1 (you can give it any other name).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

Function ConvertExcelToCsv () {

    <#

    Pass the parameters to the function.

     SourcePath the input (A full path to XLSX file),

     DestPath the outfile (A full path to the output CSV file)

    The two parameters must be given. Mandatory = $true

    #>

    Param

      (

[Parameter(Mandatory = $true)] [string] $SourcePath,

[Parameter(Mandatory = $true)] [string] $DestPath

      )

  <# Start Excel Application that we will use to open and convert XLSX to CSV #>

  $Excel = NewObject ComObject Excel.Application

  # Open the XLSX file

  $workbook = $Excel.Workbooks.Open($SourcePath)

  # @ In the following line, convert PowerShell Object to Array

  # the line outputs an Array with all the worksheets in the Excel file

  $sheets = @($workbook.Worksheets)

  # Getting the first sheet in the list of all sheets at index 0

  $sheet = $sheets[0]

  # Save the content on DestPath — a CSV file

  # Option 6 allows text formatting of the output.

  $sheet.SaveAs($DestPath, 6)

  $Excel.Quit()

}

# Full path to the XLSX file – input file

$FilePath = «PathtoXLSX_file»

# Full path to the CSV file – the output file

$DestPath = «PathtoCSV_file»

# Calling ConvertExcellToCsv function with the two paths as parameters.

ConvertExcelToCsv $FilePath $DestPath

Examples of FilePath and DestPath:

  • FilePathC:UserskipronoDesktopSalaryData2.xlsx
  • DestPathC:UserskipronoDesktopSalaryData2.csv

The ConvertExcelToCsv function takes two parameters: FilePath and DestPath. FilePath is the full path to the XLSX file, and DestPath is the path where the resulting CSV file is saved. The two parameters must be given.

Step 1: Execute the PowerShell Script

To execute the script created in step 0, run the following command on the PowerShell:

cd <path_to_directory_containing_the_script> ; .xlsx_to_csv2.ps1

For example: cd C:Users<username>Desktop ; .xlsx_to_csv2.ps1

The line above executes two commands separated by a semi-colon (;). The first part changes the working directory to the script folder, and the second part executes the actual script.

Alternatively, if you have PowerShell 2.0, use PowerShell.exe’s -File parameter to invoke a script from another environment, like Command Prompt (cmd.exe). For example, you can run something like this on CMD.

Powershell.exe File path_to_the_script

Example: Powershell.exe -File cd C:UserskipronoDesktopxlsx_to_csv.ps1

Step 2: Looking at the output

Once you have executed the script, you should be able to find the CSV file in the location defined by the DestPath parameter. In my case, the output file, SalaryData2.csv, has the following truncated content (opened on notepad editor)

ID,income,currency,duration
12182,86519.60854,USD,annually
81213,83085.86498,USD,annually
…
50767,77829.59475,USD,annually

The output shows that SalaryData2.csv is truly CSV – a Comma Separated Values file.

Converting All Excel Files in a Folder into CSV

In this Section, we want to modify the code on the script above to suit the purpose. Let’s save the modified code to xlsx_to_csv3.ps1. Here is the new code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

Function ConvertExcelToCsv () {

    <#

    Pass the parameters to the function.

     SourceFile XLSX file to be converted,

     DestDir CSV files will be written to this directory

     Filename The basename for the XLSX file eg sales in sales.xlsx

    This parameter will be used to name CSV dynamically

    The two parameters must be given. Mandatory = $true

    #>

    Param

      (

[Parameter(Mandatory = $true)] [string] $SourceFile,

[Parameter(Mandatory = $true)] [string] $DestDir,

[Parameter(Mandatory = $true)] [string] $Filename

      )

  <# Start Excel Application that we will use to open and convert XLSX to CSV #>

  $Excel = NewObject ComObject Excel.Application

  # Open the XLSX file

  $workbook = $Excel.Workbooks.Open($SourceFile)

  # @ in the following line, convert PowerShell Object to Array

  # the output of the line is an Array of all sheets in the XLSX file

  $sheets = @($workbook.Worksheets)

  # Getting the first sheet in the list of all sheets.

  $sheet = $sheets[0]

  # DestFile will be concatenation of DestDir, , basename and «.csv»

  $DestFile = $DestDir +«»+ $FileName + «.csv«

  # Save the content on DestFile — a CSV file

  # Option 6 allows text formatting of the output.

  $sheet.SaveAs($DestFile, 6)

  $Excel.Quit()

}

# Get all files with XLSX format in the directory given below

$xlsx_dir = «path_containing_XLSX_files_we_wish_to_convert«

$xlsx_files = Get-ChildItem $xlsx_dir -filter *.xlsx

$DestPath = «path_to_folder_to_hold_CSV_files«

# Loop through each XLSX file found and convert it into csv

foreach($xlsx_path in $xlsx_files)

{

    # sorce_xlsx concatenates the source directory, , and XLSX file name

    $source_xlsx = $xlsx_dir +»«+$xlsx_path

    # Filename picks the basename, e.g., sales_data in sales_data.xlsx

    $filename = $xlsx_path.BaseName

    # Call the function with the three parameters.

     ConvertExcelToCsv $source_xlsx $DestPath $filename

}

Once you have saved the above content into a PowerShell script named xlsx_to_csv3.ps1 (or anything else really), proceed to execute it as follows

cd «path_to_folder_containing_the_script« ; .xlsx_to_csv3.ps1

For example: cd C:UserskipronoDesktop ; .xlsx_to_csv3.ps1

Note: The last two sections discussed converting a single worksheet of an XLSX file into CSV. In the next Section, let’s see how to convert XLSX with multiple sheets.

Converting XLSX with Multiple Worksheets to CSV

The following Section will modify the script contents in the second Section in a new file, xlsx_to_csv2.ps1. Replace the lines between the line $workbook = $Excel.Workbooks.Open($SourceFile) and $Excel.Quit() with the following contents and execute it as we did before.

  # Loop through worksheets on XLSX and save them as csv.

  foreach ($sheet in $workbook.Worksheets) {

     $DestPath = $DestDir +«»+ $FileName + «_» + $sheet.Name + «.csv«

   $sheet.SaveAs($DestPath, 6)

  }

The above content will allow us to loop through all the worksheets in an XLSX file and convert them to CSV. The new CSV file(s) generated will contain the XLSX filename, followed by an underscore (_), then the worksheet name.

For example, consider the SalaryData2.xlsx file introduced at the beginning of the article. It has two worksheets: Incomes and PersonalDetails.

In such a case, the modifications in this Section will result in two CSV files with the following names SalaryData2_Incomes.csv and SalaryData2_ PersonalDetails.csv.

Ezoic

Microsoft Excel is one of those ubiquitous tools most of us can’t escape even if we tried. Many IT professionals use Excel as a little database storing tons of data in various automation routines. What’s the best scenario for automation and Excel? PowerShell and Excel!

Excel spreadsheets have always been notoriously hard to script and automate. Unlike its less-featured (and simpler) CSV file counterpart, Excel workbooks aren’t just simple text files. Excel workbooks required PowerShell to manipulate complicated Component Object Model (COM) objects thus you had to have Excel installed. Not anymore.

Thankfully, an astute PowerShell community member, Doug Finke, created a PowerShell module called ImportExcel for us mere mortals. The ImportExcel module abstracts away all of that complexity. It makes it possible to easily manage Excel workbooks and get down to PowerShell scripting!

In this article, let’s explore what you can do with PowerShell and Excel using the ImportExcel module and a few popular use cases.

Prerequisites

When running the ImportExcel module on a Windows system, no separate dependencies are necessary. However, if you’re working on macOS, you will need to install the mono-libgdiplus package using brew install mono-libgdiplus. All examples in this article will be built using macOS but all examples should work cross-platform.

If you’re using macOS, be sure to restart your PowerShell session before continuing.

Installing the ImportExcel Module

Start by downloading and installing the module via the PowerShell Gallery by running Install-Module ImportExcel -Scope CurrentUser. After a few moments, you’ll be good to go.

Using PowerShell and Excel to Export to a Worksheet

You may be familiar with the standard PowerShell cmdlets Export-Csv and Import-Csv. These cmdlets allow you to read and export PowerShell objects to CSV files. Unfortunately, there’s no Export-Excel and Import-Excel cmdlets. But using the ImportExcel module, you can build your own functionality.

One of the most common requests a sysadmin has is exporting PowerShell objects to an Excel worksheet. Using the Export-Excel cmdlet in the ImportExcel module, you can easily make it happen.

For example, perhaps you need to find some processes running on your local computer and get them into an Excel workbook.

The Export-Excel cmdlet accepts any object exactly the way Export-Csv does. You can pipe any kind of object to this cmdlet.

To find processes running on a system with PowerShell, use the Get-Process cmdlet which returns each running process and various information about each process. To export that information to Excel, use the Export-Excel cmdlet providing the file path to the Excel workbook that will be created. You can see an example of the command and screenshot of the Excel file generated below.

Get-Process | Export-Excel -Path './processes.xlsx'
Worksheet created with PowerShell and Excel
Worksheet created with PowerShell and Excel

Congrats! You’ve now exported all the information just like Export-Csv but, unlike Export-Csv, we can make this data a lot fancier. Let’s make sure the worksheet name is called Processes, the data is in a table and rows are auto-sized.

By using the AutoSize switch parameter to autosize all rows, TableName to specify the name of the table that will include all the data and the WorksheetName parameter name of Processes, you can see in the screenshot below what can be built.

Get-Process | Export-Excel -Path './processes.xlsx' -AutoSize -TableName Processes -WorksheetName Proccesses
Autosize Switch Parameter Result
Autosize Switch Parameter Result

The Export-Excel cmdlet has a ton of parameters you can use to create Excel workbooks of all kinds. For a full rundown on everything Export-Excel can do, run Get-Help Export-Excel.

Using PowerShell to Import to Excel

So you’ve exported some information to a file called processes.xlsx in the previous section. Perhaps now you need to move this file to another computer and import/read this information with PowerShell and Excel. No problem. You have Import-Excel at your disposal.

At its most basic usage, you only need to provide the path to the Excel document/workbook using the Path parameter as shown below. You’ll see that it reads the first worksheet, in this case, the Processes worksheet, and returns PowerShell objects.

Import-Excel -Path './processes.xlsx'
Path Parameter
Path Parameter

Maybe you have multiple worksheets in an Excel workbook? You can read a particular worksheet using the WorksheetName parameter.

Import-Excel -Path './processes.xlsx' -WorkSheetname SecondWorksheet

Do you need to only read certain columns from the Excel worksheet? Use the HeaderName parameter to specify only those parameters you’d like to read.

Import-Excel -Path './processes.xlsx' -WorkSheetname Processes -HeaderName 'CPU','Handle'

The Import-Excel cmdlet has other parameters you can use to read Excel workbooks of all kinds. For a full rundown on everything Import-Excel can do, run Get-Help Import-Excel.

Using PowerShell to Get (and Set) Excel Cell Values

You now know how to read an entire worksheet with PowerShell and Excel but what if you only need a single cell value? You technically could use Import-Excel and filter out the value you need with Where-Object but that wouldn’t be too efficient.

Instead, using the Open-ExcelPackage cmdlet, you can “convert” an Excel workbook into a PowerShell object which can then be read and manipulated. To find a cell value, first, open up the Excel workbook to bring it into memory.

$excel = Open-ExcelPackage -Path './processes.xlsx'

The Open-ExcelPackage is similar to using New-Object -comobject excel.application if working directly with COM objects.

Next, pick the worksheet inside of the workbook.

$worksheet = $excel.Workbook.Worksheets['Processes']

This process is similar to the COM object way of opening workbooks with excel.workbooks.open.

Once you have the worksheet assigned to a variable, you can now drill down to individual rows, columns, and cells. Perhaps you need to find all cell values in the A1 row. You simply need to reference the Cells property providing an index of A1 as shown below.

$worksheet.Cells['A1'].Value

You can also change the value of cells in a worksheet by assigning a different value eg. $worksheet.Cells['A1'] = 'differentvalue'

Once in memory, it’s important to release the Excel package using the Close-ExcelPackage cmdlet.

Close-ExcelPackage $excel

Converting Worksheets to CSV Files with PowerShell and Excel

Once you have the contents of an Excel worksheet represented via PowerShell objects, “converting” Excel worksheets to CSV simply requires sending those objects to the Export-Csv cmdlet.

Using the processes.xlsx workbook created earlier, read the first worksheet which gets all of the data into PowerShell objects, and then export those objects to CSV using the command below.

Import-Excel './processes.xlsx' | Export-Csv -Path './processes.csv' -NoTypeInformation

If you now open up the resulting CSV file, you’ll see the same data inside of the Processes worksheet (in this example).

Converting Multiple Worksheets

If you have an Excel workbook with multiple worksheets, you can also create a CSV file for each worksheet. To do so, you can find all the sheets in a workbook using the Get-ExcelSheetInfo cmdlet. Once you have the worksheet names, you can then pass those names to the WorksheetName parameter and also use the sheet name as the name of the CSV file.

Below you can the example code needed using PowerShell and Excel.

## find each sheet in the workbook
$sheets = (Get-ExcelSheetInfo -Path './processes.xlsx').Name
## read each sheet and create a CSV file with the same name
foreach ($sheet in $sheets) {
	Import-Excel -WorksheetName $sheet -Path './processes.xlsx' | Export-Csv "./$sheet.csv" -NoTypeInformation
}

Conclusion

Using PowerShell and Excel, you can import, export, and manage data in Excel workbooks exactly like you would CSVs without having to install Excel!

In this article, you learned the basics of reading and writing data in an Excel workbook but this just scratches the surface. Using PowerShell and the ImportExcel module, you can create charts, pivot tables, and leverage other powerful features of Excel!

With PowerShell, you can extract all kinds of information from services like Active Directory or Microsoft 365. But sometimes you need to process this information further in Excel or another system. To do this we can use the Export-CSV function in PowerShell.

The Export-CSV function converts PowerShell objects into a CSV string and saves them into a CSV file. If you only need a CSV string, then you can also use the ConvertTo-CSV function in PowerShell.

In this article, we are going to take a look at how to use the Export-CSV function, how to prevent common mistakes, and what different options there are that you can use.

The Export-CSV cmdlet is pretty straightforward and only has a few properties that are useful:

  • Path – (Required) Location of the CSV file
  • NoTypeInformation – Removes the Type information header from the output. Not needed any more in PowerShell 6
  • Delimiter – Default is comma, but you can change it
  • Append – Append to an existing CSV file
  • Force – Useful in combination with Append
  • NoClobber – Don’t overwrite existing files
  • UseQuotes – (PowerShell 7 only) wrap values in quotes or not

We are going to start with something simple, exporting our Microsoft 365 users to a CSV file. I am going to use Azure AD throughout the examples here, so if you want to follow along, make sure you connect the Azure AD first.

The Get-AzureADUser cmdlet returns all the users in your Microsoft 365 tenant, as you can see in the screenshot below. What we are going to do is to export this output to a CSV file. To do this we can simply pipe the Export-CSV cmdlet behind it:

Export-CSV PowerShell

Get-AzureADUser | Export-Csv c:tempazureadusers.csv -NoTypeInformation

Sounds easy, right? Well if you open the CSV file you will notice that we got a bit more than we needed and not the nice list that we had seen in PowerShell before.

PowerShell output to csv

So why is this happening? The Export-CSV cmdlet exports all the individual objects from the Get-AzureADUser cmdlet. If we look up a single Azure AD user then you can see all the data that is returned from a single user object:

 Get-AzureADUser -Filter "Displayname eq 'Rudy Mens'" | select *

PowerShell Export CSV

How to Export the correct information with Export-CSV

What we need to do is first select the correct information (properties) that we need before we export the user objects to a CSV file.

Get-AzureADUser | select userprincipalname, displayname, jobtitle, department, city | Export-CSV c:tempazureaduser.csv -NoTypeInformation

This will return the selected fields from each user in a nice CSV file that we can actually use:

powershell output to excel

Appending to CSV file with PowerShell

On some occasions, you may want to append information to a CSV file with PowerShell. Let’s say we want to add the manager of each user to the list. There is a more efficient way to do this, but in this case, we are going to loop through all the users and get the manager from Azure AD.

Tip

Learn more about creating PowerShell Scripts in this complete guide

For this example, we create a custom PowerShell object that will hold the user information and the manager. With the -append switch we can add the user to the CSV file.

$users = Get-AzureADUser

$users | ForEach-Object {
    $Manager = Get-AzureADUserManager -ObjectId $_.ObjectId
    
    $user =[pscustomobject]@{
        'Displayname' = $_.displayname
        'Jobtitle' = $_.jobtitle
        'Department' = $_.Department
        'Manager' = $manager.displayname
    }
    $user | Export-CSV c:tempusermanager.csv -Append -NoTypeInformation -Force
}

I have added the -Force switch as well. This way the CSV file will be created if it doesn’t exist and objects that have mismatched properties can still be written to the CSV file. It will only write the properties that match though, other properties are discarded.

Other useful Export-CSV parameters in PowerShell

There are a couple of other parameters that are useful when you are using the Export-CSV cmdlet in PowerShell.

NoClobber

By default, the Export-CSV cmdlet will overwrite any existing file when used. If you don’t want this then you can add the -NoClobber parameter. This way, if the file already exists, you will get an error, preventing you from overwriting the file.

Delimiter

The values in a Comma Separated Values File (CSV) are by default separated with a comma. Not all applications follow this standard. So when you need to import the data into another application that required a semicolon ( ; ) for example, then you can change the delimiter.

Make sure though that you enclose the new delimiter in quotation marks:

Get-AzureADUser | Select-Object -Property userprincipalname, displayname, jobtitle, department, city | Export-CSV c:tempazureaduser.csv -NoTypeInformation -Delimiter ';'

UseQuotes

When you export objects in PowerShell 5 or 6 then all values are wrapped in quotation marks. On some occasions, you might don’t want that. If you are using PowerShell 7 then you can use the -UseQuotes parameter.

This parameter has a couple of options:

  • AsNeeded
  • Always (default)
  • Never
 Get-Process | export-csv -Path c:tempprocess.csv -UseQuotes AsNeeded

Wrapping Up

The Export-CSV cmdlet is a PowerShell function that I use quite a lot. It’s really useful to pull data out of Microsoft 365 quickly for reports or other tasks. Make sure you select first the correct properties when exporting objects. This is the most commonly made mistake when it comes to exporting PowerShell data to Excel.

If you have any questions, then just drop a comment below.

Понравилась статья? Поделить с друзьями:
  • Power query для excel что это такое
  • Powerpoint data from excel
  • Powershell export excel module
  • Power query для excel описание
  • Powerpoint charts from excel