May 26 2023 02:30 AM
can anyone help me review my Powershell script? thanks
# Import the Microsoft Graph module
Import-Module Microsoft.Graph
# Output a message indicating that the module was successfully imported
Write-Output "Successfully imported Microsoft Graph"
# Connect to Microsoft Graph using the Get-MgUserMailFolder command
Connect-MgGraph -Scopes ((Find-MgGraphCommand -command Get-Mgusermailfolder).name)
# Check if there is only one user logged in
if ((Get-MgUser).count -eq 1) {
# If there is only one user, store their UserPrincipalName in the $userEmail variable
$userEmail = (Get-MgUser).UserPrincipalName
# Output a message indicating which user is logged in
Write-Output "Logged in as $userEmail"
} else {
# If there are multiple users logged in, create a list of their UserPrincipalNames
$userList = (Get-MgUser).UserPrincipalName | Foreach-Object {
@{ ++$num = $_ }
}
# Output a message asking the user to select an email address
Write-Output "Please select an email address."
# Output the list of email addresses
Write-Output $userList
try {
# Prompt the user to select an email address
[int] $selected = Read-Host
# Retrieve the selected email address from the list
$userEmail = ((Get-MgUser).UserPrincipalName)[$selected -1]
# Output a message indicating which user is logged in
Write-Output "Logged in as $userEmail"
}
catch {
# If an error occurs, output an error message
throw "Not a valid input!"
}
}
# Retrieve the ID of the inbox folder for the logged in user
$inboxId = (Get-MgUserMailFolder -u $userEmail).SyncRoot | Where-Object DisplayName -eq Inbox |ForEach-Object Id
# Output the inbox ID
Write-Output "inbox ID is : $inboxId"
# Iterate through all messages for the logged in user
(Get-MgUserMessage -u $userEmail -all)| ForEach-Object {
# Check if the message is not in the inbox folder
if ($_.ParentFolderId -ne $inboxId ) {
# If the message is not in the inbox folder, skip it
return
}
# If the message is in the inbox folder, delete it using the Remove-MgUserMessage cmdlet
Remove-MgUserMessage -UserId $userEmail -MessageId $_.Id
# Output a message indicating that the message was deleted
Write-Output "Deleted $($_.Subject)"
}
# Disconnect from Microsoft Graph
Disconnect-MgGraph