1

The script I'm using is as follows:

# Enter the file path for your csv here
# note: there needs to be a header named "userEmail" in the first row
$csvArray = Import-Csv "file\path\here" -Filter "file.csv"

# Fill out with necessary information, send to all emails in the csv
foreach ($item in $csvArray) {
    $outlook = new-object -comobject outlook.application
    $template = Get-ChildItem("C:\Users\Name\AppData\Roaming\Microsoft\Templates") -Filter "myTemplate.oft"
    $email = $outlook.CreateItemFromTemplate($template)
    $email.To = $item.userEmail
    $email.send()
}

The error I am getting is:

Exception calling "CreateItemFromTemplate" with "1" argument(s): "We can't open 'myTemplate.oft'. It's possible the file is already open, or you don't have permission to open it. To check your permissions, right-click the file folder, then click Properties."

  • the file is not open anywhere else
  • I've opened and closed Outlook multiple times
  • I've also opened Outlook in safe mode and get the same error
  • I have permissions for these templates
  • I removed myself and added myself to the permissions just to double check that it wasn't stuck somewhere there.

when I first wrote the script it worked a couple times during testing, now I always get this error.

There is also nothing special about the template, it's just a normal email.

I'm also a beginner in powershell, so it's possible I'm just doing something wrong.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
schnondle
  • 121
  • 14
  • 1
    The problem is that _Windows PowerShell_ sometimes stringifies `Get-ChildItem` output objects by file _name_ only rather than by _full path_, _depending on how `Get-ChildItem` was invoked_; the problem has been fixed in _PowerShell (Core) v6.1+_. The workaround is to use `.FullName` to ensure use of the full path or, if the objects are to be passed to other file-processing cmdlets, to pass them _via the pipeline_. See the linked duplicate for details. – mklement0 Oct 31 '22 at 22:39
  • 1
    Also: `Get-ChildItem("C:\Users\Name\AppData\Roaming\Microsoft\Templates") ...` should be `Get-ChildItem "C:\Users\Name\AppData\Roaming\Microsoft\Templates" ...`: PowerShell functions, cmdlets, scripts, and external programs must be invoked _like shell commands_ - `foo arg1 arg2` - _not_ like C# methods - `foo('arg1', 'arg2')`. If you use `,` to separate arguments, you'll construct an _array_ that a command sees as a _single argument_. See [this answer](https://stackoverflow.com/a/65208621/45375) for more information. – mklement0 Oct 31 '22 at 22:41
  • Note: I'm assuming two things: (a) You're using _Windows PowerShell_. (b) The error message you're seeing is of a general nature and tries to cover less obvious cases, but also applies to the simple error of the specified template file path _not existing_. – mklement0 Oct 31 '22 at 22:54

0 Answers0