Reputation: 755
I would like to make an iteration which automatically deletes all contacts from Outlook.
This first row makes the collection:
$olSession = (New-Object -ComObject Outlook.Application).Session
$olSession.Logon('Outlook')
$contactsFolder = 10
$elemek = $olSession.GetDefaultFolder($contactsFolder).Items
I can delete one item, if I know the name:
$deleteone = $elemek | Where-Object {$_.FullName -eq "Your Name"}
$deleteone.Delete()
But I would like to delete all contacts automatically, so I get the number of elements in $elemek
with $elemek.Count
.
I don't know how to get the value of the array "dynamically":
for ($i=0; $i -le $elemek.Count; $i++)
{
# The following line is not working
$elemek.Count[0].Delete()
}
Could you help me to fix the iteration?
Thank you.
Addition:
If i run this:
$elemek | Format-Table FullName,MobileTelephoneNumber,Email1Address
I got this:
FullName MobileTelephoneNumber Email1Address
-------- --------------------- -------------
Morgan Freeman /o=Mydomain/ou=Exchange Administrativ...
Johny English /o=Mydomain/ou=Exchange Administrativ...
So i really need to got FullName from $elemek and use in the script block of the for itaration.
Upvotes: 1
Views: 590
Reputation: 22132
Just use ForEach-Object
, but preread content of $elemek
before deleting:
@($elemek)|ForEach-Object {$_.Delete()}
Upvotes: 1
Reputation: 26170
the exception could be raised if $elemk contains null value, try this : ...
$ErrorActionPreference="stop"
$elemek = $olSession.GetDefaultFolder($contactsFolder).Items
try{
$elemk |%{ if ($_) { $_.delete() } }
}
catch{
"error occured :"
$_
}
Upvotes: 0