PowerShell Script Balloon tip does not show $variable output - powershell

I have a script that is related to exchange online PowerShell. This script moves mail item from deleted mailbox to a new mailbox and once completed shows the balloon tip with the status. The Balloon tip script has a $variable which does not show the right output.
Script is as below:-
$User = "Admin#domain.com"
$mypass = cat "C:\pass.txt" | convertTo-securestring -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("$User", $mypass)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $mycreds -Authentication Basic -AllowRedirection
Import-PSSession $Session
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
$DeletedUser = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Deleted Mailbox Email Address", "Deleted Mailbox")
$UserMailbox = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Destination Mailbox Email Address", "Destination Mailbox")
$DeletedGUID = Get-Mailbox -SoftDeletedMailbox $DeletedUser | fw guid
$DestinationGUID = Get-Mailbox $UserMailbox | fw guid
New-MailboxRestoreRequest -SourceMailbox $DeletedGUID -TargetMailbox $DestinationGUID -AllowLegacyDNMismatch
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Status = Get-MailboxRestoreRequest | Get-MailboxRestoreRequestStatistics | FW StatusDetail
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = (join-path ([environment]::GetFolderPath('MyDocuments')) "EXO.ico")
$objNotifyIcon.BalloonTipIcon = "Error"
$objNotifyIcon.BalloonTipText = "Mail Item move has $Status"
$objNotifyIcon.BalloonTipTitle = "Operation $Status"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(50000)
The Balloon tip cannot parse the variable. Can anyone help?
Thanks in Advance!

Related

Powershell "ExternalEmailAddress can not convert the system.collection.arraylist

My Goal:
To create in bulk Mail Contact using Powershell.
My program asks me to input manually the ExternalEmailAddres.
When I do so, the program works.
I can not do that because of the big number of Mail contact to create.
I just do not know see where my error is.
Anyone can help? Please.
My code:
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xxx.yyy.com/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session -DisableNameChecking
Import-Module ActiveDirectory
$User = Import-CSV C:\CREATE-MAIL-CONTACT.csv
$Params = #{
Name = $user.Name
ExternalEmailAddress = $User.PrimarySmtpAddress
OrganizationalUnit = "OU=Mail Contacts,DC=xxx,DC=com"
}
New-MailContact #Params
My CSV:
------
Displayname Name PrimarySmtpAddress
John Smith John Smith john.smith#abc.com
What your code is missing is to iterate over each row of your CSV, one way to do that is with ForEach-Object:
Import-CSV C:\CREATE-MAIL-CONTACT.csv | ForEach-Object {
try {
$Params = #{
Name = $_.Name
ExternalEmailAddress = $_.PrimarySmtpAddress
OrganizationalUnit = "OU=Mail Contacts,DC=xxx,DC=com"
}
New-MailContact #Params
}
catch {
# error handling here
Write-Warning $_.Exception.Message
}
}

Powershell: Using specific credentials to execute a command

Dears,
In my Powershell script, I would like to use a specific credential on a remote computer. This login exists on the remote computer and is local.
Hence, my code looks like this:
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$Vault = New-Object Windows.Security.Credentials.PasswordVault
$RESOURCE = "Resource"
$USERNAME = "MyLogin"
try {
$credentials = $Vault.Retrieve($RESOURCE,$USERNAME)
$pwd = $credentials.Password | ConvertTo-SecureString -Key (1..16)
}
catch {
$pwd = Read-Host "please enter your password:" -AsSecureString
$Encrypted = ConvertFrom-SecureString -SecureString $pwd -Key (1..16)
$credentials = new-object -Type Windows.Security.Credentials.PasswordCredential -ArgumentList $RESOURCE,"REMOTE_COMPUTER\"+$USERNAME,$Encrypted
$Vault.Add($credentials)
}
$cred = New-Object System.Management.Automation.PsCredential($USERNAME,$pwd)
$ComputerMemory = Get-WmiObject -ComputerName "REMOTE_COMPUTER" -Class win32_operatingsystem -ErrorAction Stop -Credential $cred
$Memory = ([math]::round(((($ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory)*100)/ $ComputerMemory.TotalVisibleMemorySize), 2))
echo $Memory
Problem of course is when executing GetWmiObject, I got an Access denied error...
Is there something wrong with this code?
Thanks in advance for your feedback,
Kind regards,

Connect-MsolService - providing credentials without exposing password in script

I wish to run the below PowerShell script as a scheduled task to pull provisioning logs from Azure AD. However, I do not wish to embed the password. I appreciate this is not a problem specific to PowerShell or Microsoft Online. What technique can I use to not have the password stored as clear text? Thanks
Script credits go to: Pawel Janowicz
$AzureUsername = 'log.reader#tenant.net'
$Password = "xxxxxx"
$SecureString = ConvertTo-SecureString -AsPlainText $Password -Force
$SecuredCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AzureUsername,$SecureString
$OutputCSV = "$Env:USERPROFILE\desktop\DirSyncProvisioningErrors_$(Get-Date -Format "yyyyMMdd").csv"
###### Connecting ############################################################################################################
Try{
[void] (Connect-MsolService -Credential $SecuredCreds)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $SecuredCreds -Authentication Basic -AllowRedirection
[void] (Import-PSSession $Session -DisableNameChecking)
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
###### Getting errors ########################################################################################################
If(Get-MsolHasObjectsWithDirSyncProvisioningErrors){
Try{
$Errors = Get-MsolDirSyncProvisioningError -All | select DisplayName,ObjectID,ObjectType,ProvisioningErrors
$Results = Foreach ($i in $Errors){
$AllErrors = $i.ProvisioningErrors
$AllErrors | %{
$ErrorItem = $_
Get-AzureADObjectByObjectId -ObjectIds $i.objectid | Foreach{
New-Object PSObject -Property ([ordered]#{
'Displayname' = $i.displayname
'ObjectType' = $i.ObjectType
'Attribute' = $ErrorItem.propertyname
'Conflicting value' = $ErrorItem.propertyvalue
})
}
}
}
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
}
###### Results ###############################################################################################################
If($Results){
$Results | Format-Table -AutoSize
#Exporting CSV
$Results | Export-CSV $OutputCSV -NoTypeInformation -Force
}
Remove-PSSession $Session
Thank You Theo for providing your suggestion as a comment. Making this as answer to help other community member.
I have executed the command and getting a display to enter the password rather than it was manually provided in script itself.
$SecuredCreds = Get-Credential -UserName 'log.reader#tenant.net' -Message "Please enter credentials"
$OutputCSV = "$Env:USERPROFILE\desktop\DirSyncProvisioningErrors_$(Get-Date -Format "yyyyMMdd").csv"
###### Connecting ############################################################################################################
Try{
[void] (Connect-MsolService -Credential $SecuredCreds)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $SecuredCreds -Authentication Basic -AllowRedirection
[void] (Import-PSSession $Session -DisableNameChecking)
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
###### Getting errors ########################################################################################################
If(Get-MsolHasObjectsWithDirSyncProvisioningErrors){
Try{
$Errors = Get-MsolDirSyncProvisioningError -All | select DisplayName,ObjectID,ObjectType,ProvisioningErrors
$Results = Foreach ($i in $Errors){
$AllErrors = $i.ProvisioningErrors
$AllErrors | %{
$ErrorItem = $_
Get-AzureADObjectByObjectId -ObjectIds $i.objectid | Foreach{
New-Object PSObject -Property ([ordered]#{
'Displayname' = $i.displayname
'ObjectType' = $i.ObjectType
'Attribute' = $ErrorItem.propertyname
'Conflicting value' = $ErrorItem.propertyvalue
})
}
}
}
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
}
###### Results ###############################################################################################################
If($Results){
$Results | Format-Table -AutoSize
#Exporting CSV
$Results | Export-CSV $OutputCSV -NoTypeInformation -Force
}
Remove-PSSession $Session

Powershell - Organizer Email Address

I'm trying to retrieve the email address of the Organizer of a meeting in MS Exchange 2010, using Powershell.
(Get-Mailbox -Identity "John Doe").PrimarySmtpAddress
I get the below error
The operation couldn't be performed because object 'John Doe' couldn't be found on 'xxxxxxxxxxxxxx'
These are for meetings that have just been created, so how can the Organizer not exist?
Edit:
Here's the sequence of events:
Fetch list of calendar events from exchange within specific date range
Fetch email address of Organizer for each event <-- this is where I'm stuck
Full script:
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xxxxxxxxxxxxxxx/PowerShell -Authentication kerberos -Credential $credential
Import-PSSession -Session $session -DisableNameChecking
#Date ranges
$exportDate = Get-Date -Format d
$startTime = (Get-Date).AddDays(-1)
$endTime = (Get-Date).AddDays(+1)
$app = New-Object -ComObject Outlook.Application
$ns = $app.GetNamespace('MAPI')
$calFolder = 9
$calItems = $ns.GetDefaultFolder($calFolder).Items
$calItems.Sort("[Start]")
$calItems.IncludeRecurrences = $true
$dateRange = "[Start] >= '{0}' AND [End] <= '{1}'" -f $startTime.ToString("g"), $endTime.ToString("g")
$calExport = $calItems.Restrict($dateRange)
$exportFile = "D:\file.csv"
$calExport | select Subject, StartInStartTimeZone, EndInEndTimeZone, Duration, Organizer, RequiredAttendees, OptionalAttendees, Location | sort StartUTC -Descending | Export-Csv $exportFile
$exportData = Import-Csv $exportFile
foreach ($line in $exportData)
{
$emailAddress = $line.Organizer
$emailAddress = (Get-Mailbox -Identity $line.Organizer).PrimarySmtpAddress
$line | Add-Member -Membertype Noteproperty -Name OrganizerEmail -Value $emailAddress
[array]$csvData += $line
$emailAddress = $null
}
Remove-PSSession $session
Please assist!
Here's what I used to get the Organizers email address
Get-ADUser -Filter {SamAccountName -like "*John Doe*"}

Trouble Trying to Hide Email From Address List Using PowerShell

I am trying to run a simple command to hide an email account from the address list using PowerShell. Here is my code so far.
cls
$EmployeeEmail = "user#example.com"
#Need to hide the Mailbox from address list
$MethodName = "Hide Email Account"
$username = "staff"
$password = "accounts"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Exchmbca1.example.local/PowerShell/ -Authentication Kerberos -Credential $cred
Import-PSSession $Session
Set-Mailbox -Identity $EmployeeEmail -HiddenFromAddressListsEnabled $true
Remove-PSSession $Session
However, when I run this command I receive the following error message:
The operation couldn't be performed because object 'user#example.com' couldn't be found on 'servername.example'.
I have tried changing the value of the -Identity I pass to the Set-Mailbox cmdlet with 'DOMAIN\username' as well and I receive the same error. I know the account exists because I can do a search using Get-ADUser and find the account with the SAMAccountName. Any help would be much appreciated. Thanks!