I am new to Powershell (and coding in general) and am attempting to save outlook attachments that are all in the form of .xlsx from a specific sender. I managed to get a general script written to save attachments from the sender, but I also want to parse the attachment name to save it with a specific title using the parsed group values.
Sample outlook attachment name: Produce Price changes 1-1 for-#70-Butte.xlsx
Here is the general script that works:
#Open outlook and define MAPI environment
$outlook = new-object -com Outlook.Application
$namespace = $outlook.GetNamespace("MAPI")
#Define Inbox as an Object the "1" denotes the second listed account (pricing email account)
$inbox = $outlook.Session.Folders.Item(1).folders.item("Inbox")
$inbox | ft Folderpath
#Define Cody Subfolder as an object
$Cody = $Outlook.Session.Folders.Item(1).Folders.Item("Inbox").folders.item("Cody")
$Cody | ft FolderPath
$Cody.Items | Select-Object Sendername, senderemailaddress -unique
#Define save location
$filepath = "C:Userscody.weiszDesktopProduce"
$Cody.Items | where-object {$_.Sendername -match "Jeff Griffin"} | Foreach {
$_.attachments | Foreach {
Write-Host $_.filename
$name = $_.filename
If($name.contains("xlsx")) {
$_.saveasfile((Join-Path $filepath "$name.xlsx"))}}}
Here are the changes I added to try and parse the attachment name to create a new document title:
$filepath = "C:Userscody.weiszDesktopProduce"
$Cody.Items | where-object {$_.Sendername -match "Jeff Griffin"} | Foreach {
$_.attachments | Foreach {
Write-Host $_.filename
$name = $_.filename | Foreach {
Select-string -Pattern (^(w+sw+sw+s)(d+-d+)(w+-)(Wd+)) |
ForEach-Object {
$Type, $Date, $NA, $Store = $_.Matches[0].Groups[1..4].Value
[PSCustomObject] @{
Type = $Type
Date = $Date
NA = $NA
Store = $Store
If($name.contains("xlsx")) {
$_.saveasfile((Join-Path $filepath "$Type+$Store+$Date.xlsx"))}}}}}}
Any help is greatly appreciated. Thanks
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…