0

I tried the following code but it pastes some garbage text while copying data from excel to outlook. Using powershell. Code used:

$body=""
get-content "C:\Users\smi00019\Desktop\AO\Book1.xlsx" | foreach{$body+="$_`n"}

Excel data:

Name    Place   Animal
ABC     Mumbai  Dog
XYZ     Pune    Cat

I am trying to copy above data range A1:c3

3
  • Possible duplicate of Read Excel data with Powershell and write to a variable Commented Mar 21, 2018 at 15:15
  • 1
    you are not reading "garbage data", you are trying to get what's in the file, which is more than simply the values in the cells. Commented Mar 21, 2018 at 15:16
  • You need the link Pac0 posted or save the file as csv rather than xlsx and use Import-Csv to bring the data into Powershell. Commented Mar 21, 2018 at 15:37

1 Answer 1

2

Get-Content is for use with text-based files. Excel files are not text based and contain other elements (formatting, formulas, macros, graphs etc)

I would recommend using the PSExcel Module as it contains the Import-XLSX function which makes working with Excel files very easy.

Import-XLSX works like Import-CSV, and generates an 'array' object from the file.

Excel:

enter image description here

$Imported = Import-XLSX -Path C:\Temp\Demo.xlsx -Header samaccountname, EID, Date

PS Object:

enter image description here


You can then use Select-Object to get the Property (column names) you want and that you only the First two entries (rows).

$Imported | Select-Object -Property Column1,Column1,Column1 -First 2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.