Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

ActiveSync Report

$
0
0

Hi All,

 

I am using below script to generate activesyn report. I am importing 53K Activesync users which is running from last 4 days. Some have any idea to run this multi thread to get the report faster?

 

if ( (Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue) -eq $null )

{

    Add-PsSnapin Microsoft.Exchange.Management.PowerShell.E2010

}

$ErrorActionPreference = "silentlycontinue"

$EASDevices = “”

$AllEASDevices = @()

 

$EASDevices = “”| select ‘User’,’PrimarySMTPAddress’,’DeviceType’,’DeviceModel’,’DeviceOS’, ‘LastSyncAttemptTime’,’LastSuccessSync’

$EasMailboxes = Import-Csv C:\ActiveSync\batches\ActiveSync_users_Jun.csv | foreach {Get-Mailbox -Identity $_.identity}

#$EasMailboxes

foreach ($EASUser in $EasMailboxes) {

$EASDevices.user = $EASUser.displayname

$EASDevices.PrimarySMTPAddress = $EASUser.PrimarySMTPAddress.tostring()

    foreach ($EASUserDevices in Get-ActiveSyncDevice -Mailbox $EasUser.alias) {

    $EASDeviceStatistics = $EASUserDevices | Get-ActiveSyncDeviceStatistics

    $EASDevices.devicetype = $EASUserDevices.devicetype

    $EASDevices.devicemodel = $EASUserDevices.devicemodel

    $EASDevices.deviceos = $EASUserDevices.deviceos

    $EASDevices.lastsyncattempttime = $EASDeviceStatistics.lastsyncattempttime

    $EASDevices.lastsuccesssync = $EASDeviceStatistics.lastsuccesssync

    $AllEASDevices += $EASDevices | select user,primarysmtpaddress,devicetype,devicemodel,deviceos,lastsyncattempttime,lastsuccesssync

    #$AllEASDevices

    $AllEASDevices | Export-Csv -Path C:\ActiveSync\batches\ActiveSyncReport.csv -NoTypeInformation

    }

    }


Retreiving mailbox move history via Exchange remote session not working as expected

$
0
0

I'm trying to retrieve mailbox move history via a remote session and the results I'm getting are different then what I receive when running the command locally.

The powershell code I'm using is :

$user="<youruser>"

(get-mailbox $user | get-mailboxstatistics -IncludeMoveHistory).movehistory|select CompletionTimestamp,SourceDatabase,TargetDatabase

The code I'm using to set up the remote session is :

$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<yourserver>/powershell

Import-PSSession $session -CommandName Get-MailboxStatistics,Get-Mailbox -AllowClobber

When executed locally I get the expected results.  Executing remotely does not.

Any idea what I am doing wrong? Thanks for all feedback!

Import multiple PST files to archive database

$
0
0

I need to create some script for import pst users archives to EXCHANGE 2010 sp1 database.

Mail archives stored on single file server \\FILE-SERVER\PST\%Username%\

An amount and name of files is different for each of users.

Example:

\\FILE-SERVER\PST\Andy\archive.pst

\\FILE-SERVER\PST\Andy\archive2.pst

\\FILE-SERVER\PST\Andy\Andy-old.pst

 

It's needed to do a script which would execute next actions:

1. Ask for username (input from keyboard or as parameter)

2. Get a list of files for every username in folder \\FILE-SERVER\PST\%Username%\

3. Create a command line (New-MailboxImportRequest-Mailbox%username%-Name"filename" -IsArchive -BaditemLimit 45 -FilePath '\\FILE-SERVER\PST\%Username\filename.pst')

Clean up Distribution group in Exchange 2010

$
0
0

Good Morning 

At my company we currently have a lot of distribution groups actually we have more groups than employees lol 

It seems that after a group stopped being used no one ever decommissioned them. Is it possible to use the powershell built into exchange 2010 to view when was the last time the Distribution group received an email 

So far i have the below but it is not returning results.

 

 

# counts both static and dynamic lists being used

# change the xdays value to however far back you wanna go

# verify how far back your messagetrackinglogs go for accurate results

 

$xdays = 365

$table = @()

$report = @()

$lists = @()

 

$results = Get-TransportServer | get-messagetrackinglog -eventid expand -resultsize unlimited -start (get-date).addDays(-$xdays) | sort timestamp -desc

 

if ($results) 

 {

  $data = $results | group relatedrecipientaddress | sort name

  $lists = get-distributiongroup -resultsize unlimited | select alias,primarysmtpaddress 

  $lists += Get-DynamicDistributionGroup -ResultSize unlimited | select alias,primarysmtpaddress

  $lists = $lists | sort alias

  foreach ($list in $lists)

   {

    $check = $null

    $check = $data | ?{$_.name -like "$($list.primarySMTPaddress.tostring())"}

    if ($check)

     {

      $table += New-Object -TypeName PSObject -Property @{

         MailingList = $list.alias.toLower()

         Hits = $check.count

         LastUsed = ($check | select -expand group | select -first 1).TimeStamp

        }

      }

     else

      {

       $table += New-Object -TypeName PSObject -Property @{

          MailingList = $list.alias.toLower()

          Hits = 0

          LastUsed = $null

         }

       }

     }

  $table | Select-Object MailingList,Hits,LastUsed | Export-Csv -Path ".\MailingListUsage-$(Get-Date -f 'MMddyy').csv" -NoTypeInformation

 }

else

 {"No Results"}

Search a list of mailboxes

$
0
0

I hope this is a simple request.
I don't know how to invoke a list (csv file) to search mailboxes.

For example I can dump a Distribution List members into a csv.
But then i'd like to search those members mailboxes for a specific message.

Search-Mailbox "user 1" -SearchQuery 'Subject:"spam email"' -estimateresultonly

Instead of searching for this one user mailbox, i'd like to use a csv and in that csv are all the DL members.

Problems with using pipes in a For Each command block

$
0
0

I've been given a list of hundreds of email addresses and asked to output the names, office, & department values to a spreadsheet.  I decided to try this using a for each block but for some reason the export-csv isn't working, I end up with an empty csv output file.  Here's what I'm doing:

The input CSV file is just a header of EmailAddress and then 1 or more email addresses on a new line; right now I'm testing with only a single address in the input file, but I've tested with a small list of 2 good addresses and 1 non-existant address which also didn't work.

$addr = Import-CSV C:\dir\list.csv

foreach ($mb in $addr){Get-recipient -resultsize unlimited | where {$_.emailaddresses -like $mb.EmailAddress} | select name, @{Name=’EmailAddresses’;Expression={[string]::join(";", ($_.EmailAddresses))}}, displayname, department, office | Export-CSV -NoTypeInformation Export-List.csv}

Change all AD users assoicated email address for mail enabled users to [alias]@domain.com

$
0
0

What I'm hoping to do is use a powershell script that will take every user in the Active Directory and change their email address to [alias]@domain.com.

 

There isn't a common pattern in this company, and in a recent move to Office 365, the now mail enabled users have the wrong address associated to their account.  They do however still have the correct alias that matches what their email address should be (minus the domain of course on the alias).  I'm hoping I can get help writing a powershell script that will pull the alias and then write that value with @domain.com tacked on into their email address field.

Hyphens Report

$
0
0

I'm trying to write a cmdlets that will shows all the user names with the Hyphen in them in my organization.


Total mail items for a user sorted by year

$
0
0

Hi guys.

 

I'm fairly new to exchange powershell and need some help.

 

We have a journaling mailbox setup in exchange 2007 and this is meant to have been cleared out every month with the existing monthly items archived at the end of the month.

 

This mailbox has grown and is 380 gigs in size. Trying to access this mailbox is causing all sorts of resource issues on the exchange server as there are over 2 million emails in this mailbox.

 

Would someone be able to provide me guidance on the correct command I can use to display the number of mail items per year for this mailbox? So if i could get something like

mailbox@company.com year: 2007 30000 items

 

Failing this, a command to provide the date of the first 100 items in the inbox.

 

Thanks for your help guys.

 

Get-CalendarProcessing - BookInPolicy

$
0
0

Sure it's easy but has defeated me so far!

If I set the BookInPolicy on a Room Mailbox for a couple of email addresses -

Set-CalendarProcessing -Identity "Room9" -BookInPolicy "tom.clark@test.com", "paul.stones@test.com"

What's the most elegant method (using Powershell) to add "pete.smith@test.com" to the two existing addresses?

Set-CalendarProcessing -Identity "Room9" -BookInPolicy "pete.smith@test.com" replaces "tom.clark@test.com", "paul.stones@test.com" with "pete.smith@test.com" rather than appends it to the list (which is what I want)

Thanks in advance

sending emails from within a script

$
0
0

I have this code which works.   

$Outlook=New-Object-ComObjectOutlook.Application
$Mail=$Outlook.CreateItem(0)
$Mail.To="MyEMailAddress@Acme.org"
$Mail.From="ITinsider@Acme.Org"
$Mail.Subject="IT Department: Action Required"
$Mail.Body="Message from IT Department: You have not rebooted for you system for over 1 week. Please reboot your system today. This is required for virus protection. Thank you!"
$Mail.Send()

 

When I run this code the email does show up.  But I get this error at the bottom half of my PowerShell ISE window.

Exception setting "From": "The property 'From' cannot be found on this object. Verify that the property exists and can be set."

If there is no .From method how come it still works?  And if there is no .From method what should I use to make this work and not generate the error I get?  How do I make this email come from someone else?  I need it to come from ITInsider@Acme.org.  

 

editing existing Dynamic Distribution Group or list Exchange Online

$
0
0

We need to edit an existing  Dynamic Distribution Group  in Exchange Online

I need it  to only list User with China  listed for the Country,   and  I am trying to add additional filter  to  filter out Mailboxes with Custom Attribute 1   excludechina   so those mailboxes will not show up in the list recipients.

here is script :

Set-DynamicDistributionGroup -Identity allChinaUsers -RecipientFilter {RecipientType CustomAttribute1 -ne 'excludechina' -and CountryOrRegion -eq "China" -and RecipientType -eq 'UserMailbox'}

 

 

How long does it take for Dynamic Distribution Group to update after filter changes

$
0
0

How long does it take for a Dynamic Distribution group to update and show the changes  after you modify the groups RecipientFilter ,  adding a new CustomAtribute filter

I'm trying to write script that can tell me the last login of all users. Also I'm trying to see what the how much mail space each in my organization is using.

$
0
0

I'm trying to write script that can tell me the last login of all users. Also I'm trying to see what the how much mail space each in my organization is using.  I wrote a script that looks like this.... Get-Mailbox |Get-MailboxStatistics.  The Storage Limit column is empty and I'm going to need information there 

Set all mailboxes to read only

$
0
0
  • I need to set all of my Exchange 2010 sp3 mailboxes to read only. I found an article by Praveen that describes the process, but it appears to be doing so on a per user basis. I'm not familiar enough with powershell to know how to modify the commands to select all mailboxes.

    Can someone please tell me how to set all mailboxes to ready only with powershell?

    Thanks!


Request to review my script

$
0
0
Hello PowerShell gurus,
I am done with creation and addition of variables in a powershell script with does AD creation and Mailbox creation from CSV. 
However, sometimes it creates the mailbox with no error, generally for first AD user in csv, sometimes it does not and rest of the script also ends with no configuration of fields. 
It gives an error "Oops, something went wrong: Cannot find an object with identity:". Can you please review my modified script once and guide me. 
I would be really thankful to you. I thank you for your kind guidance.
P.S.:I am not a master of scripting, so could not find anything more in it. I believe #create mailbox piece has some issue, I have made it bold, can you please check once.
Warm Regards,
Gautam
Script
==========================================================
###########################################################
# AUTHOR  : GAUTAM VERMA 
# DATE    : 23-07-2015 
# EDIT    : 23-07-2015
# COMMENT : This script creates new Active Directory users,
#           including different kind of properties, based
#           on an input_create_ad_users.csv.
# VERSION : 1.3
###########################################################

# CHANGELOG
# Version 1.2: 20-07-2015 - Changed the code for better
# - Added better Error Handling and Reporting.
# - Changed input file with more logical headers.
# - Added functionality for account Enabled,
#   PasswordNeverExpires, ProfilePath, ScriptPath,
#   HomeDirectory and HomeDrive
# - Added the option to move every user to a different OU.
# Version 1.3: 23-07-2015

# ERROR REPORTING ALL
Set-StrictMode -Version latest

#----------------------------------------------------------
# LOAD ASSEMBLIES AND MODULES
#----------------------------------------------------------
Try
{
  	Import-Module ActiveDirectory -ErrorAction Stop
  	Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
}
Catch
{
  Write-Host "[ERROR]`t ActiveDirectory Module couldn't be loaded. Script will stop!"
  Exit 1
}

#----------------------------------------------------------
#STATIC VARIABLES
#----------------------------------------------------------
$path     = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath  = $path + "\import_create_ad_users.csv"
$log      = $path + "\create_ad_users.log"
$date     = Get-Date
$addn     = (Get-ADDomain).DistinguishedName
$dnsroot  = (Get-ADDomain).DNSRoot
$i        = 1

#----------------------------------------------------------
#START FUNCTIONS
#----------------------------------------------------------
Function Start-Commands
{
  Create-Users
}

Function Create-Users
{
  "Processing started (on " + $date + "): " | Out-File $log -append"--------------------------------------------" | Out-File $log -append
  Import-CSV $newpath | ForEach-Object {
    If (($_.Implement.ToLower()) -eq "yes")
    {
      If (($_.GivenName -eq "") -Or ($_.LastName -eq ""))
      {
        Write-Host "[ERROR]`t Please provide valid GivenName, LastName and Initials. Processing skipped for line $($i)`r`n""[ERROR]`t Please provide valid GivenName, LastName and Initials. Processing skipped for line $($i)`r`n" | Out-File $log -append
      }
      Else
      {
        # Set the target OU
        $location = $_.TargetOU + ",$($addn)"

        # Set the Enabled and PasswordNeverExpires properties
        If (($_.Enabled.ToLower()) -eq "true") { $enabled = $True } Else { $enabled = $False }
        If (($_.PasswordNeverExpires.ToLower()) -eq "true") { $expires = $True } Else { $expires = $False }

        # A check for the country, because those were full names and need 
        # to be land codes in order for AD to accept them. I used India
        # as example
        If($_.Country -eq "India")
        {
          $_.Country = "IN"
        }
        Else
        {
          $_.Country = "US"
        }
        # Replace dots / points (.) in names, because AD will error when a 
        # name ends with a dot (and it looks cleaner as well)
        $replace = $_.Lastname.Replace(".","")
        If($replace.length -lt 4)
        {
          $lastname = $replace
        }
        Else
        {
          $lastname = $replace.substring(0,4)
        }
        # Create sAMAccountName according to this 'naming convention':
        # <FirstLetterGivenName><FirstThreeLettersLastName><Last3digitsOfSSN> for example
        # Gverm
        $sam = $_.GivenName.substring(0,1).ToLower() + $lastname.substring(0,3).ToLower() +$_.SSN.substring(0,3).ToLower()
        Try   { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" }
        Catch { }
        If(!$exists)
        {
          # Set all variables according to the table names in the Excel 
          # sheet / import CSV. The names can differ in every project, but 
          # if the names change, make sure to change it below as well.
          $setpass = ConvertTo-SecureString -AsPlainText $_.Password -force

          Try
          {
            Write-Host "[INFO]`t Creating user : $($sam)""[INFO]`t Creating user : $($sam)" | Out-File $log -append
            New-ADUser $sam -GivenName $_.GivenName `
            -Surname $_.LastName -DisplayName ($_.LastName + "," + $_.GivenName) `
            -Office $_.OfficeName -Description $_.Description -EmailAddress $_.Mail `
            -StreetAddress $_.StreetAddress -City $_.City -State $_.State `
            -PostalCode $_.PostalCode -Country $_.Country -UserPrincipalName ($sam + "@" + $dnsroot) `
            -Company $_.Company -Department $_.Department -EmployeeID $_.EmployeeID `
            -Title $_.Title -OfficePhone $_.Phone -AccountPassword $setpass -Manager $_.Manager `
            -profilePath $_.ProfilePath -scriptPath $_.ScriptPath -homeDirectory $_.HomeDirectory `
            -homeDrive $_.homeDrive -Enabled $enabled -PasswordNeverExpires $expires -ChangePasswordAtLogon $True
            Write-Host "[INFO]`t Created new user : $($sam)""[INFO]`t Created new user : $($sam)" | Out-File $log -append
            $dn = (Get-ADUser $sam).DistinguishedName
            # Set an ExtensionAttribute
            If ($_.ExtensionAttribute1 -ne "" -And $_.ExtensionAttribute1 -ne $Null)
            {
              $ext = [ADSI]"LDAP://$dn"
              $ext.Put("extensionAttribute1", $_.ExtensionAttribute1)
              Try   { $ext.SetInfo() }
              Catch { Write-Host "[ERROR]`t Couldn't set the Extension Attribute : $($_.Exception.Message)" }
            }
	    #Create Home Directory

		$HomeDriveLetter=’I:’

		$UserRoot=("\\"+$_.HomeServer+"\e$\Users\")

		$HomeDirectoryPath=$UserRoot+$sam

		New-Item $HomeDirectoryPath -Type directory -force

		SET-ADUSER $sam –HomeDrive $HomeDriveLetter –HomeDirectory $HomeDirectoryPath

		$Acl = Get-ACL $HomeDirectoryPath
		$AccessRule= New-Object System.Security.AccessControl.FileSystemAccessRule("self","FullControl","ContainerInherit,Objectinherit","none","Allow")
		$Acl.AddAccessRule($AccessRule)
		Set-Acl $HomeDirectoryPath $Acl
       	    #Copy items from Share location to Home Drive
		Copy-Item \\covtech1\Software\Applications\HOMEDIR\* $HomeDirectoryPath
	    # Move the user to the OU ($location) you set above. If you don't
            # want to move the user(s) and just create them in the global Users
            # OU, comment the string below
            If ([adsi]::Exists("LDAP://$($location)"))
            {
              Move-ADObject -Identity $dn -TargetPath $location
              Write-Host "[INFO]`t User $sam moved to target OU : $($location)""[INFO]`t User $sam moved to target OU : $($location)" | Out-File $log -append
            }
            Else
            {
              Write-Host "[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!""[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!" | Out-File $log -append
            }
	  #To add user to all the Groups which other user is memberof.It is can be normally used when new user needs to have all the group membership of the existing users
		$Name = $_.mirror
		$groups = (GET-ADUSER –Identity $Name –Properties MemberOf).MemberOf
		foreach ($group in $groups) { 

		Add-ADGroupMember -Identity $group -Members $sam
		}
		$count = $groups.count
		
		# Remote Desktop Services Profile 
		$dn  = (Get-ADUser $sam).DistinguishedName 
		$ext = [ADSI]"LDAP://$dn" 
		$ext.PSBase.invokeSet("TerminalServicesProfilePath","\\PROFILETHIN1\PROFILETHIN1$\$sam.%OSNAME%")
		$ext.SetInfo()#create Mailbox
			Write-Host "`nCreating mailbox for [$sam] on CBT-DB2" -ForegroundColor Cyan
			Start-Sleep -s 10
			$disname = (Get-ADUser $sam).DistinguishedName
			Try {Enable-Mailbox $disname -Database CBT-DB2 -ErrorAction Stop}
			Catch {
			If ($_.Exception.Message -like '*is of type User*') {
			Write-Host `t "[$sam] already has a mailbox, continuing to next step " -ForegroundColor Yellow}
			Else {Write-Host "Proceeding to Next step" -ForegroundColor Green}}

            # Rename the object to a good looking name (otherwise you see
            # the 'ugly' shortened sAMAccountNames as a name in AD. This
            # can't be set right away (as sAMAccountName) due to the 20
            # character restriction
            Write-Host "[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n""[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append
          }
          Catch
          {
            Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
          }
        }
        Else
        {
          Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!`r`n""[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!" | Out-File $log -append
        }
      }
    }
    Else
    {
      Write-Host "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!`r`n""[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!" | Out-File $log -append
    }
    $i++
  }"--------------------------------------------" + "`r`n" | Out-File $log -append
}

Write-Host "STARTED SCRIPT`r`n"
Start-Commands
Write-Host "STOPPED SCRIPT"
==========================================================

Alias change based on Company Attribute

$
0
0

Hi there, I need to edit the Alias details on certain users based on the Company attribute in the Organization Tab.

Can anyone advise if the following would work, I do not have the luxury of a Lab environment and therefore don't really wish to change everyones Alias to Firstname.Lastname.External 

Get-User-Filter {(Company-eq"Custard")}

 Foreach $Details=Get-User$_.Alias;$New=$Details.FirstName+"."+$Details.LastName +"."+"External"; Set-MailContact$_.Alias -Alias$New 

An output of the changes would be awesome too.

Any help is gratefully received.

Graham

Out of Office message export in csv file

$
0
0

Hi,

My customer asked to export all users OOO message into csv file they want look at who set message external email address in OOO message.

I have a test where I configured OOO and tried running below cmd-let to export looks csv file does not capture text I am looking for.

Get-Mailbox testUser | Get-MailboxAutoReplyConfiguration | Export-Csv -NoTypeInformation e:\OOO_test.csv

when I open file in excel internalMessage column has only <html> and its wrap text if I tun off wrap text, I can see whole message like below 

"<html>

<body>

<div style=""font-size:13px; font-family:Tahoma"">

<p>Test Out Of Office <a href=""mailto:test@test.com"">test@test.com</a>

</p>

</div>

</body>

</html>

"

If press F2 and copy entire text in that cell and past on empty cell it print exactly what I want.
"Test Out Of Office test@test.com"
I wanted run this script for all users, anyone know how do I get OOO text? my export is wrong or I need to do something in excel to display the correct text?

Capture actions of script

$
0
0

Hello Tech gurus,

I have a script which disable forwarding applied on users:

 

Get-mailbox $_.alias | Where {$_.ForwardingAddress -ne $null} | Set-Mailbox -ForwardingAddress $null -DeliverToMailboxAndForward $false }

 

Can you please help me in extracting actions of script into outfile.log/.txt.

 

I would like to know if it is disabled for every user.

 

I thank you in advance for your assistance and guidance.

 

regards,

Gautam

Request for help - SendMail

$
0
0

Hi Tech Gurus,

 

Can you let me know how to add CC field in below mentioned command:

 

c:\Healthcheck.ps1  -ScriptFilesPath C:\folder -SendMail:$true -MailFrom:Gautam.verma@domain.com -MailTo:admin@domain.com -MailServer:smtp.domain.com

 

Or if I can add multiple addresses in MailTo field.

I thank you in advance for your guidance.

Regards,

Gautam

Viewing all 10624 articles
Browse latest View live