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

Filter on Mailboxes and disabled users in AD

$
0
0

Hi, 

 

I am kinda new to powershell. 

 

What I need. 

An Powershell command to retrieve all mailboxes sorted on accounts that is enabled in AD. 

We have an environment where people quits, moves and all sorts of things, so accounts in AD is disabled to be reactivated again in a month or a year. 

 

What's needed. 

To have an up2date list of all mailboxes which currently resides and have an active AD account.

 

What's been tried :

get-mailbox |?{$_.UserAccountControl -Match "AccountDisabled"} |FT Name,Database,UserAccountControl | Out-file C:\path.csv

Did not give any result

These seemed hopefull but commands are not present. 

Search-ADAccount -AccountDisabled | Out-file C:\path.csv 

Get-Aduser -Filter (enabled -ne $true) 

 

Any tips/tricks/winks ?

 

Regards

Jan 


Trying to Export User Emails From Journaling Mailbox

$
0
0

We have a customer who is looking to export all email associated with a user, the user has multiple email addresses, but all with the syntax 'user@xxx.xxx'.I am trying to run the following export command with no success.

New-MailboxExportRequest –Mailbox jmmfexch2 –ContentFilter {(participants –eq ‘*bingalls*’)} –FilePath “\\mfexch2\archives\whatever.pst”

It finishes quickly and generates a 256K empty .pst file

Any help appreciated,

Thanks,

Bob

New-mailboxexportrequest to export contacts folder to CSV file

$
0
0

Hello,

I'm having trouble exporting out the contacts to a .csv file. I have a UNC share created with the Exchange trusted subsystem with full control on the share and the ntfs permissions. I can do the export to .pst but I need it in csv format and am not sure how to first convert to string and then export the file to csv.

Help appreciated. Thank you

Gordon

Script To Add Prefix to all existing distribution groups

$
0
0

I am looking for a script that will add a prefix of "DL_MBM_" to the front of all of our 551 distribution groups. Can anyone help me out? :( I am no scripting guru by any means.

Trying to get a list of users without an X500 address

$
0
0

Hi

I am trying to get a list of users who do not have an X500 address. All the users have an SMTP address, but need an X500 address in order for them to appear as contacts in another domain in another forest using the galsync method.

I managed to find a script which will display users with an SMTP address, and this seems to work. Same with displaying users with an X500 address. When I try to modify it so that it only displays users without an X500 address, it either displays nothing or it moans about the command I used.

Here is the script:

Get-Mailbox | Select-Object DisplayName,UserPrincipalName,@{Name="EmailAddresses";Expression={$_.EmailAddresses |Where-Object {$_ !(-LIKE) "SMTP:*"}}} | Sort | Export-Csv "C:\Users\$env:username\Desktop\test.csv"

Could someone help? I am not an expert in scripting, but I am learning. Slowly.

Any help will be gratefully received.

Anthony

returning a value from a drop-down

$
0
0

Hello,

I'm writing a script to create new users through a form (the normal user creation process is long and complex and therefore prone to human error), but I'm having issues capturing values from a drop-down.

Here is my code.... (sorry couldn't see how to insert it as a block of code!)

########################

# Edit This item to change the DropDown Values

[array]$DropDownArray = "John", "Peter", "Paul"

# This Function Returns the Selected Value and Closes the Form

function Return-DropDown {

 $Choice = $DropDown.SelectedItem.ToString()
 $Form.Close()
 Write-Host $Choice

}

[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")


$Form = New-Object System.Windows.Forms.Form

$Form.width = 300
$Form.height = 150
$Form.Text = ”DropDown”

$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown.Location = new-object System.Drawing.Size(100,10)
$DropDown.Size = new-object System.Drawing.Size(130,30)

ForEach ($Item in $DropDownArray) {
 $DropDown.Items.Add($Item)
}

$Form.Controls.Add($DropDown)

$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel.Location = new-object System.Drawing.Size(10,10)
$DropDownLabel.size = new-object System.Drawing.Size(100,20)
$DropDownLabel.Text = "Items"
$Form.Controls.Add($DropDownLabel)

$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(100,50)
$Button.Size = new-object System.Drawing.Size(100,20)
$Button.Text = "Select an Item"
$Button.Add_Click({Return-DropDown})
$form.Controls.Add($Button)

$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()

$FirstName = $Choice
$LastName = "Test"
$Name = $FirstName + " " + $LastName
#Get First Initial from Firstname.
#From position 0 select the first 1 character
$FirstInitial = $FirstName.Substring(0,1)
$Alias = $FirstInitial + $LastName
$Email = $Alias + "@daslaw.co.uk"

New-Mailbox -UserPrincipalName $Email -Alias $Alias -Database "NonTeam" -Name $Name -OrganizationalUnit "Test Team" -Firstname $FirstName -LastName $LastName -DisplayName $Name -ResetPasswordOnNextLogon $true

########################

I've cut the code back to try and locate the error and it seems as though the data is being written to the variable ($Choice) as it appears in the host screen using "Write-Host $Choice" but it looks as though it is being cleared after.

 

Script to show failed databases and send an email

$
0
0

Normal 0 false false false EN-GB X-NONE X-NONE MicrosoftInternetExplorer4

Hi

I usually check all the databases in the DAG to make sure there are none that have failed or suspended. The command i use is crude but works and displays the name e.g

db1\server1  failed suspended

db5\server4  suspended

db17\server6 failed

get-mailboxserver |Get-MailboxDatabaseCopyStatus |? {$_.status -ne"healthy"} |? {$_.status -ne "mounted"} | Sort-Object databasename

 

I wanted to just automate this and sent an emailing  me a list of all failed databases name/server and if there are no failed databases to tell me there are none.

Being a total novice i tried this and failed any help would be really great

 

$servers=get-mailboxserver

$dbcopystatus=$servers|Get-MailboxDatabaseCopyStatus

$nothealthy=$dbcopystatus|? {$_.status -ne"healthy"}

$nomounted=$nothealthy|? {$_.status -n e "mounted"}

$faulty=$nomounted| Sort-Object databasename

$output = If (@($faulty).count > 0)

    { Write-output “Failed disk $faulty"`n"}

    Else

    {  Write-output“No Disks are faulty”  `n"    }

 

Send-MailMessage -from "Exchange2010@abc.com" -to "admin@xyz.com" -Subject "bad db disk $((get-date).ToShortDateString())" -body $output -bodyashtml -SmtpServer"SMTP" -Priority high

 

Thanks

ian

Powershell to check the domains in the proxy address

$
0
0

Hello Guys,

I am looking for a script that will comapare a file of domains to all the proxy address list of the users in AD and let me know if any users has an additional domain proxy address.

Also powershell script to have output of the on-prem GAL to a CSV file.

 

Any suggestion is appreciated.

Thanks & Regards,

AB

 

 

 

 

 

 


Inbox Rules with multiple email-addresses in From parameter

$
0
0

Exchange 2010 SP3. I need to use the -From parameter in the Set-InboxRule Cmdlet with more than one address, but I can't get it to work. This is how I would have hoped it would work:

Set-InboxRule <RuleName> -Mailbox <Mailbox> -From "email-address1,email-address2"

But seems to me that email-address2 is ignored. Tried different delimiters with same result.

Can you Guys help me figure out, how to assign a multi-address value to the -From parameter? Thanks! :)

Get-MailboxStatistics -Server with -Archive doesn't work for me

$
0
0

I must be doing something wrong but here is my issue:

 

Get-MailboxStatistics -Server "exnameofserver"  #works fine and returns data

Get-MailboxStatistics -Server "exnameofserver" -Archive   #throws this error: "Parameter set cannot be resolved using the specified named parameters"

Same issue with -Database param btw

I know I can run a foreach with Identity but that will take 5 hours on the archives when the primarys data returns in a matter of a couple of minutes with all info I need.

Anyone know what I am doing wrong or a better way than foreach and 5 hours???

 

import users from database into active directory group

$
0
0

Trying to write powershell script to populate a group of users on a specific databse to an Active Directory group.  User in the database are in a child domain, the parent domain contains the group.

 

I have:

Import-Module ActiveDirectory

$ADGroup = "CN=testgroup,DC=test,DC=com"

$Users = get-mailbox -database server\database -IgnoreDefaultScope | select samaccountname

Add-ADGroupMember -Identity $ADGroup -Members $Users

Find enabled users in a given mailbox database

$
0
0

Get-Mailbox doesn't take parameter that filters by enabled/diabled

Get-ADUser doesn't take a parameter that filters by mailbox database

I tried

Get-Mailbox -Database db02 | Get-ADUser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))"

but that seems to return all enabled users and the second part doesn't seem to limit the input to the output of the first part.

Any ideas how this can be accomplished?

Automating settings on a room mailbox

$
0
0

Hi

I'm trying to create a script that will automate some of the settings for room mailboxes for our organization with a PowerShell script, however, I'm a newbie when it comes to this sort of thing and I'm struggling.

One of the guys who worked here while we were migrating to Exchange 2010 wrote a PowerShell script that asks for a number of parameters and then creates a shared mailbox based on those parameters, so I've made a copy and gone in and made some modifications which all work as expected.

I'm trying to create a second script that goes and changes things like the capacity, BookingWindowInDays and MaximumDurationInMinutes etc.

My problem is I don't know how to do the capacity bit.

At the top of my script I've got the following:

# Parameters below are where you enter the information of the rooms, which PowerShell will then use later on in the script

param(
    [parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false,HelpMessage="Room Name")][string]$Name,
    [parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false,HelpMessage="MANAGEMENT Group")][String]$MGRGroup,
 [parameter(Position=2,Mandatory=$true,ValueFromPipeline=$false,HelpMessage="USER Group")][String]$USRGroup,
 [parameter(Position=3,Mandatory=$true,ValueFromPipeline=$false,HelpMessage="Capacity")][String]$Capacity
    )

# Loads the ActiveDirectory module into PowerShell if it hasn't already been loaded. This is because the new-adgroup is an AD commandlet rather than an Exchange one  
  
Import-Module ActiveDirectory -ErrorAction SilentlyContinue

# Setup splatting hashtable
$NewSharedMailbox = @{
    "Shared" = $True
    "Name" = $Name
}
# Check parameters OK and add relevant parameters to splatting hashtable
$Recipient=Get-Recipient $Name -ErrorAction SilentlyContinue

How do I then set the capacity? When I do

# Set room mailbox 'standard config'

write-host
Write-Host -ForegroundColor Green "Setting Room Mailbox Standard Config"

try {get-mailbox -name $name | Set-Mailbox -ResourceCapacity $Capacity }
 catch {
     write-host
  write-host -ForegroundColor Green "Please wait..."
  }

PowerShell asks me for the identity of the Set-Mailbox.

Any advice would be greatly appreciated as its doing my head in! I thought I was making good progress with the create room script, but now I've hit a brick wall.

Thanks in advance!

Trying to restore a mail file from a recovery database

$
0
0

I am trying to recover an exchange mail file from a recovery database, I tried to browse the database but got no results

[PS] C:\>Get-MailboxDatabase rdb

Name                           Server          Recovery        ReplicationType
RDB                            CBSEXC001       True            None


[PS] C:\>Get-MailboxDatabase rdb | get-mailbox
[PS] C:\>

if I can't browse the mailboxdatabase, how do I know the users mailbox is there?

any information would be appreciated

sendAs, SendOnBehalfOf access and DL for a specific user

$
0
0

Hi-

Would you happen to have a script that will report the DL and the type of access (SendAs, SendOnBehalfOf) for a specific user?

I tried get-distributiongroup with the managedBy command, but that isn't exactly what I want, as this user may not always manage the group, but has rights to sendAs etc.

Any help would be appreciated.

Thanks!


mailbox search

$
0
0

Hi All

I am trying to create a monthly windows schedule task where mailbox deleted items are searched for last 30 days from the date the schedule is run.

This works
Search-Mailbox -Identity "user" -SearchDumpsteronly -SearchQuery {"Received: 04/01/15..04/02/15 "} -includeunsearchableitems -TargetMailbox searchresults -TargetFolder "test" -Loglevel Full

As i schedule task i do not want to add manual entry {"Received: 04/01/15..04/02/15 "} each time it has to run.


I have tried this and it has failed  

$start=(Get-Date).adddays(-30)
$end=(Get-Date).adddays(-1)
$start = “{0:dd/MM/yyyy} –f $start
$end = “{0:dd/MM/yyyy} –f $end
 
Search-Mailbox -Identity "user" -SearchDumpsteronly -SearchQuery  {("Received -lt $end") -and ("Received -gt $start")} -includeunsearchableitems -TargetMailbox searchresults -TargetFolder "test" -Loglevel Full

Also replaced {("Received -lt $end") -and ("Received -gt $start")} with
{received:$start..$end}

I have come to realise that searchquery does not like varibles date  e.g. $start and $end, if i add real dates 1/1/15 works fine. I have looked at $start and $end values and they appear to match the value that works e.g. 1/1/15

Would anyone know why searchquery behaves like this with date or how to fix it or if i am just doing something wrong

thanks

Ps apologies i did add something similar in an incorrect forum but have done a bit more testing since then based on information provided

Exchange 2010: Export Mailbox to PST using CSV

$
0
0

Hello - I'm in the process of exporting mailboxes from another exchange server from a company we acquired so I can import email into their new mailbox. I have a CSV formatted with headers old,new which has their old alias and new alias. I also only want to capture the last 60 days of email. However, I seem to be missing something in formatting as it keeps creating a new line instead of just executing the script. I'm at a loss and can't seem to get this working. Any help would be appreciated!

 

$sixty = get-date -format "M/d/yyyy" (get-date).AddDays(-60)
$UserList=Import-CSV C:\users.csv
FOREACH ($Person in $UserList) {
New-MailboxExportRequest -Mailbox $Person.old -ContentFilter {(MessageKind -eq 'Email') -and (Received -gt $sixty) -or (Sent -gt $sixty)} -FilePath "\\server\pst\"$Person.new".pst"
}

Little Script Help

$
0
0

Good day,

This is my very first post on the forums :)  I ran into the site when looking to figure out what I am doing wrong with my script.  I hope someone can maybe point me in the right direction. 

I have a list of users (about 500) who need an email alias added to their mailboxes (Exchange 2010) and so I figured I would create a script to do so.  The script imports the usernames from a CSV file and using a variable I concatenate what the new email address will look like. From there I use a simple For loop to run the command for each element of the array containing the imported data from the CSV.  The script looks as follows:

------------------------------

$UsrName = @()

$CSVPath = "C:\PowerShell\UsrEmail.csv";

$UsrName = Get-Content -path $CSVPath;

For ($i=0; $i -lt $UsrName.length; $i++) 

{

  $usridemail = $UsrName[$i] + "@company.com";

  $usridemail;

  Set-RemoteMailbox $UsrName[$i] -EmailAddresses @{Add="$useridemail"};   

}

------------------------------

Using the double quotes in the command, I expected it to evaluate the $useridemail variable and poof, I would be good to go.  However it doesn't appear to be the case.. I get the following error:


user@company.com

Cannot process argument transformation on parameter 'EmailAddresses'. Cannot convert value "System.Collections.Hashtable" to type "Microsoft.Exchange.Data.ProxyAddressCollection". Error: "Failed to convert  from System.String to Microsoft.Exchange.Data.ProxyAddress. Error: Error while converting string '' to result type Microsoft.Exchange.Data.ProxyAddress: The e-mail address cannot be empty."    + CategoryInfo          : InvalidData: (:) [Set-RemoteMailbox], ParameterBindin...mationException    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-RemoteMailbox

 

So with my limited understanding of powershell... from what I can see is that it is not evaluating the $useridemail variable when attempting to add the new email address to the mailbox.

I also have to apologize as I am sure there is a much more efficient way to write a script that does this, but my knowledge of powershell is fairly limited. Any help would be very appreciated.

If I run the set-remotemailbox command manually, and input the username and desired email address it works fine.  So there is something about that variable it doesn't like. 

Transportrule exporting as readable format

$
0
0

Hi,

Anyone tried exporting transportrules in readable format? I am looking to export (Export-TransportRuleCollection) to csv or HTML format so that I can use that for meeting discussion doc.. I tried get-transportrule and printing only few columns but its not useful I have 26 rules use different conditions, action and exceptions. so unsuccessful :(   

 

I read MS article for export and importing in xml format (https://technet.microsoft.com/en-us/library/bb629570(v=exchg.141).aspx)

Any help readable format.. appreciated. 

Thank you,

Raj

 

Get-Acl / Set-Acl - Error. Please help!

$
0
0

Hi, I want to copy files/folders recurse and with it copy also all ACLs. When i run the script it gaves me the following error. Any idea what am i doing wrong here?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
try {$Files = Get-ChildItem -Path $Source -Recurse -ErrorAction Stop$C = $Files.countif ($Files){
                        foreach ($Filein$Files) {try{$File | Copy-Item -Destination $Destination -ErrorAction stop  -Verbose$ACL = Get-Acl $File.FullName -ErrorAction stop -Verbose
                                Set-Acl -Path ($File.FullName).Replace($Source,$Destination) -AclObject $ACL -ErrorAction stop -Verbose
                            }catch{
                                write-warning "Error! $($file.Fullname)"
                                Write-error  $_
                            }
                        }

             }
             else {
                  Write-Warning "No files to move"
                 }
          }

        Catch{             
              $ErrorMessage = $_.Exception.Message

The Error message is below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
VERBOSE: Performing the operation "Copy File" on target "Item: C:\utdelat\A\Capsules\PinBoard\se0801.cpsx Destination: C:\utdelat\c\se0801.cpsx".
WARNING:Error! C:\utdelat\A\Capsules\PinBoard\se0801.cpsx
Copy-FilesACL : System.Management.Automation.ItemNotFoundException: Cannot find path 'C:\utdelat\c\PinBoard\se0801.cpsx' because it does not exist.
   at System.Management.Automation.LocationGlobber.ExpandMshGlobPath(String path, Boolean allowNonexistingPaths, PSDriveInfo drive, ContainerCmdletProvider provider, CmdletProviderContext context)
   at System.Management.Automation.LocationGlobber.ResolveDriveQualifiedPath(String path, CmdletProviderContext context, Boolean allowNonexistingPaths, CmdletProvider& providerInstance)
   at System.Management.Automation.LocationGlobber.GetGlobbedMonadPathsFromMonadPath(String path, Boolean allowNonexistingPaths, CmdletProviderContext context, CmdletProvider& providerInstance)
   at System.Management.Automation.PathIntrinsics.GetResolvedPSPathFromPSPath(String path, CmdletProviderContext context)
   at Microsoft.PowerShell.Commands.SetAclCommand.ProcessRecord()
   at System.Management.Automation.CommandProcessor.ProcessRecord()
At C:\Git\MoveFiles\Move-ACL.ps1:85char:1
Viewing all 10624 articles
Browse latest View live


Latest Images