Customising Exchange Activesync Powershell script

Hi All,
I have posted a question in forum for getting the activesync logs to check who has enabled/disabled activesync in Exchange 2007 but have not got the techincal result. So I am Planning to have a script in place to enable/disable activesync and maintain a
log to track of all changes with date and time.
http://social.technet.microsoft.com/Forums/en-US/exchangesvradminlegacy/thread/c4f58cef-b0f1-4313-b1ea-6ad82054daaa
Below is the script we have in place to enable/disable Activesync
$name=Read-Host Enter the SMTP address of the account to be ActiveSync ENABLED
$a = get-date
set-mailbox -id $name -CustomAttribute1 'Enable'
set-casmailbox -id $name -ActiveSyncEnabled $true -ActiveSyncMailboxPolicy 'Default - Default Policy + Encryption'
echo $a >> c:\temp\scripts\EAS\log.txt
get-casmailbox -id $name | ft -autosize PrimarySMTPAddress,ServerName,ActiveSyncMailboxPolicy,ActiveSyncEnabled | out-file -append c:\temp\scripts\EAS\log.txt
get-casmailbox -id $name | ft -autosize PrimarySMTPAddress,ServerName,ActiveSyncMailboxPolicy,ActiveSyncEnabled
I have seen many scripts in technet forum to enable or disable activesync. But I have a customise requirement.
But my requirement is
1. read a user to enable or disable activesync
2. Do u want to enable or disable active sync
3. If user wants to enable AS
   Then  below conditions
     if  AS is not enabled and if CA#1 is empty
         Enable ActiveSync and update CA#1 as Enable
    Else IF AS is enabled & CA#1 is empty/disable
         Inform like AS is already enabled for the user, but CA#1 is not updated/disable
         Do u want to update CA#1 -> If yes -> Update CA#1
    Else if AS is not enable & if CA#1 is updated as enable
         Inform like AS is not enabled for the user, but CA#1 is updated
         Do u want to enable Active sync
  Else
     inform both AS is enabled and CA#1 is updated.
4. If user wants to disable
     then the same logic but have to disable...
This will allow me to track admins who are enabling/disabling the requests and also will be very easy to manage AS.
Please help me with a script or the conditons to be added in the script and let me know if we can have some good output with the below information
1. Admin info - who has updated the AS & CA
2. Date and time
3. User info - whose details got updated.
Ahmed Ali

Please post your request in
Script Request
You will get answers and best solutions from many.
Regards Chen V [MCTS SharePoint 2010]

Similar Messages

  • Running Exchange 2010 PowerShell Scripts

    Hello,
    I have a PowerShell Script which calls PSSnapins for Exchange tools.  The Exchange Management Tools are installed on the Tidal Server
    The Script works fine by itself, I have executed it as the tidal users on the Tidal Server. I have also created a batch file to execute the Powershell script, which also works on the tidal server.
    However when I run the job in Tidal it doesn't run correctly by that I mean it will run the none Exchange pieces.  In the Output tab it shows:
    Add-PSSnapin : The Windows PowerShell snap-in 'Microsoft.Exchange.Management.PowerShell.E2010' is not installed on this machine.
    At E:\PowerShell\DailyChecks\Dag_daily.ps1:7 char:13
    + Add-PSSnapin <<<<  Microsoft.Exchange.Management.PowerShell.E2010
        + CategoryInfo          : InvalidArgument: (Microsoft.Excha...owerShell.E2
       010:String) [Add-PSSnapin], PSArgumentException
        + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.Ad
       dPSSnapinCommand
    Add-PSSnapin : The Windows PowerShell snap-in 'Microsoft.Exchange.Management.Powershell.Support' is not installed on this machine
    These Scripts also work via Windows Task Scheduler as written  I would really like to get these to work in Tidal.  We are Tidal 5.3.1. 
    Any help would be greatly appreciated.
    Lee Merrill

    I have struggled with a similar issue with Sharepoint snapin with performing a backup
    I can give a couple of suggestions
    Add snapin to default profiles
    We also see a difference in 64 vs 32 bit oprerations
    we had to add to both versions using a local profile.ps1 and adding a line
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
    C:\Windows\System32\WindowsPowerShell\v1.0
    C:\Windows\SysWOW64\WindowsPowerShell\v1.0
    Execute remotely
    Slightly different setup on our side
    I am trying to invoke-command on the remote sharepoint server =
    ( you have to set up psremoting, etc)
    Invoke-Command -ComputerName -scriptblock { E:\Backup\BackupSite.ps1}
    Similarly I  can execute the backup.ps1 with no issue on the server but can't from the tidal job.
    I'll let you know if we find a fix
    I am thinking double hop at this point and need to trust for delegation, etc
    Marc

  • Exchange ActiveSync powershell Report

    Good Day All,
    I am trying to run a a script, which pulls a report of all of our activesync devices and exports from powershell to .csv. The report runs fine but I have to manually format the result because the csv does not split into individual columns. Any assistance
    in getting the headers and linked info to split into individual columns would be highly appreciated.
    Below is the script:
    $Mailboxes = Get-Mailbox -ResultSize "unlimited"
    $Date = Get-Date
    $CSVPath = "c:\reports\ActiveSyncReport.csv"
    $CSVHeader = "DisplayName,Department,PrimarySMTPAddress,DeviceType,DeviceModel,DeviceOS,FirstSyncTime,LastSuccessSync"
    $CSVHeader | Out-File -FilePath $CSVPath -Encoding ASCII
    Foreach ($Mailbox in $Mailboxes)
    $ActiveSyncInfo = $null
    $ActiveSyncInfo = Get-ActiveSyncDeviceStatistics -Mailbox $Mailbox | Where-Object {$_.LastSuccessSync -ge $Date.AddDays(-30)}
    If ($ActiveSyncInfo -ne $null)
    $ADInfo = Get-ADUser -Identity $Mailbox -Properties "Department"
    $DisplayName = $Mailbox.DisplayName
    $Department = $ADinfo.Department
    $PrimarySMTP = $Mailbox.PrimarySmtpAddress
    $DeviceType = $ActiveSyncInfo.DeviceType
    $DeviceModel = $ActiveSyncInfo.DeviceModel
    $DeviceOS = $ActiveSyncInfo.DeviceOS
    $FirstSync = $ActiveSyncInfo.FirstSyncTime
    $LastSuccess = $ActiveSyncInfo.LastSuccessSync
    [String]$CSVAdd = $DisplayName + "," + $Department + "," + $PrimarySMTP + "," + $DeviceType + "," + $DeviceModel + "," + $DeviceOS + "," + $FirstSync + "," + $LastSuccess
    $CSVAdd | Out-File -FilePath $CSVPath -Encoding ASCII -Append

    Nevermind, I have managed to get it fixed, was not thinking properly. Incase it is useful to anyone else please see the below:
    $Mailboxes = Get-Mailbox -ResultSize "unlimited"
    $Date = Get-Date
    $CSVPath = "c:\reports\ActiveSyncReport.csv"
    $CSVHeader = "DisplayName;Department;PrimarySMTPAddress;DeviceType;DeviceModel;DeviceOS;FirstSyncTime;LastSuccessSync"
    $CSVHeader | Out-File -FilePath $CSVPath -Encoding ASCII
    Foreach ($Mailbox in $Mailboxes)
    $ActiveSyncInfo = $null
    $ActiveSyncInfo = Get-ActiveSyncDeviceStatistics -Mailbox $Mailbox | Where-Object {$_.LastSuccessSync -ge $Date.AddDays(-30)}
    If ($ActiveSyncInfo -ne $null)
    $ADInfo = Get-ADUser -Identity $Mailbox -Properties "Department"
    $DisplayName = $Mailbox.DisplayName
    $Department = $ADinfo.Department
    $PrimarySMTP = $Mailbox.PrimarySmtpAddress
    $DeviceType = $ActiveSyncInfo.DeviceType
    $DeviceModel = $ActiveSyncInfo.DeviceModel
    $DeviceOS = $ActiveSyncInfo.DeviceOS
    $FirstSync = $ActiveSyncInfo.FirstSyncTime
    $LastSuccess = $ActiveSyncInfo.LastSuccessSync
    [String]$CSVAdd = $DisplayName + ";" + $Department + ";" + $PrimarySMTP + ";" + $DeviceType + ";" + $DeviceModel +
    ";" + $DeviceOS + ";" + $FirstSync + ";" + $LastSuccess
    $CSVAdd | Out-File -FilePath $CSVPath -Encoding ASCII -Append

  • Exchange PowerShell script to get mailbox properties of user from a CSV file

    Hi Team,
    I've a CSV file with alias of numerous users and I want to get their mailbox sizes and other properties. These users are dispersed in various databases of same Exchange organization.
    Need a Powershell Script, Any help?
    Muhammad Nadeem Ahmed Sr System Support Engineer Premier Systems (Pvt) Ltd T. +9221-2429051 Ext-226 F. +9221-2428777 M. +92300-8262627 Web. www.premier.com.pk

    You can use this and modify it to what you need. Output to a file (IE: Export-CSV "path to file"
    If you need more specifics let me know. This one is for one user at a time but can be used to read a CSV file.
    # Notifies the user a remote session needs to be started
    Write-Host "Get a users mailbox size" -fore yellow -back red;
    Write-Host "Please wait while a remote session started" -fore red -back yellow;
    # Import a remote session with exchange
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeservername/Powershell/ -Authentication Kerberos
    Import-PSSession $Session
    Do {
    # Prompts user for a name
    $name = Read-Host "Enter a username"
    # Get the mailbox statistics for that user
    Get-MailboxStatistics $name | fl totalitemsize, storagelimitstatus, totaldeleteditemsize | out-default
    # Give the user a choice to test another or EXIT
    $Output = Read-Host "Press Y to continue or ENTER to exit"
    # Ends the program if the user does not press Y
    Until ($Output -ne "Y")
    HossFly, Exchange Administrator

  • Powershell Script for Exchange- Storagelimitstatus wont return any data.

    I am trying to run the following script using PowerGUI and its working but one piece. The storagelimitstatus isn't returning any data. Any impute would great.
    Here is what I wrote. 
    If (-not (Get-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue))
    {   Try { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction Stop }
        Catch { Write-Host "Unable to load Exchange tools because ""$($Error[0])""" -ForegroundColor Red ; Exit }
    Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,IssueWarningQuota, storagelimitstatus,ProhibitSendQuota,ProhibitSendReceiveQuota,@{label="TotalItemSize(MB)";expression={(Get-MailboxStatistics $_).TotalItemSize.Value.ToMB()}}, @{label="ItemCount";expression={(Get-MailboxStatistics
    $_).ItemCount}}, Database| Export-Csv "\\pc1417\c$\Scripts\UserMailboxSizes.csv" -NoTypeInformatio

    StorageLimitStatus is a property extracted by Get-MailboxStatistics and not Get-Mailbox.Try below and check if that works!
    Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,IssueWarningQuota,@{label="StorageLimitStatus";expression={(Get-MailboxStatistics $_).StorageLimitStatus}},ProhibitSendQuota,ProhibitSendReceiveQuota,@{label="TotalItemSize(MB)";expression={(Get-MailboxStatistics $_).TotalItemSize.Value.ToMB()}}, @{label="ItemCount";expression={(Get-MailboxStatistics $_).ItemCount}}, Database| Export-Csv "\\pc1417\c$\Scripts\UserMailboxSizes.csv" -NoTypeInformation
    Pavan Maganti ~ ( Exchange | 2003/2007/2010/E15(2013)) ~~ Please remember to click “Vote As Helpful&quot; if it really helps and &quot;Mark as Answer” if it answers your question, “Unmark as Answer” if a marked post does not actually answer your
    question. ~~ This Information is provided is &quot;AS IS&quot; and confers NO Rights!!

  • Exchange 2010 SP2 to SP3 Powershell script execution policies

    Hi,
    I have broken Labs when installing service packs on exchange 2010 servers because the powershell execution policies have been incorrectly configured. Once the WMI service has been stopped, the scripts within the SP haven't been able to start it up again. 
    I can't find any info on Powershell script execution policies in relation to the SP3 for 2010 prerequisites. Does anyone know what they should be set at? And why haven't these been at the top of the list of prerequisites for installations of service packs
    for exchange? 

    Hello,
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    I'm marking the reply as answer as there has been no update for a couple of days.
    If you come back to find it doesn't work for you, please reply to us and unmark the answer.
    Cara Chen
    TechNet Community Support

  • How to Export Team Site Site Pages to .aspx and for subsequent upload to other Team Site and Web Part Customisation included. (Powershell)

    Hi guys,
    Can i please technically know how to export an .aspx file (in Site Pages library of a team site) to local file?
    Basically, SharePoint Designer has this feature "Export File"
    i Need exactly the same feature that can be done in Powershell
    I tried the following
    $web = get-spweb "MY URL"
    $folder = $web.GetFolder("SitePages")
    $files = $folder.files
    #trying to download the first file
    [System.IO.File]::WriteAllBytes("C:\\LocalPath",$files[0].OpenRead(),$true)
    The file exported via this method is Clean HTML without the Web Part Customisation!
    I NEED the web part customisation in the exported files.
    Sample downloaded via above script
    <!-- Cropping -->
    <tr>
    <td id="_invisibleIfEmpty" name="_invisibleIfEmpty" valign="top" height="100%"> <WebPartPages:WebPartZone runat="server" Title="loc:LeftColumn" ID="LeftColumn" FrameType="TitleBarOnly"/> </td>
    <td id="_invisibleIfEmpty" name="_invisibleIfEmpty" valign="top" height="100%"> <WebPartPages:WebPartZone runat="server" Title="loc:MiddleColumn" ID="MiddleColumn" FrameType="TitleBarOnly"/> </td>
    <td id="_invisibleIfEmpty" name="_invisibleIfEmpty" valign="top" height="100%"> <WebPartPages:WebPartZone runat="server" Title="loc:RightColumn" ID="RightColumn" FrameType="TitleBarOnly"/> </td>
    </tr>
    <!-- Cropping -->
    I tried using WebRequest, it returns the  End HTML, which is not working too.
    Please if anyone has done this? Or is there any SharePoint Designer Developer here and is willing to share how to perform the export in SharePoint Designer via Powershell? API available?
    Much Appreciated!
    Cheng

    Hi,
    According to your post, my understanding is that you wanted to export Team Site Site Pages to .aspx and for subsequent uploaded to other Team Site and Web Part Customisation included using Powershell.
    You can export a specific file or object from the Export-SPWeb context.
    Export-SPWeb -identity "http://sharepoint" -ItemUrl "/default.aspx"  -Path "c:\default.aspx"
    Import-SPWeb -identity "http://sharepoint" -Path "C:\default.aspx"
    Here is a similar thread for you to take a look at:
    http://sharepoint.stackexchange.com/questions/56664/how-to-download-a-sharepoint-aspx-page-from-server-using-powershell
    More information:
    http://technet.microsoft.com/en-us/library/ee428301(v=office.14).aspx
    Best Regards,
    Linda Li
    Linda Li
    TechNet Community Support

  • Powershell script sends e-mail in ISE but not from powershell command line

    I have created a script that generates a report of all users who do not have photos in Active Directory. The script runs and sends an e-mail to a distribution list. It runs fine in ISE, but I cannot run it from command line or as a scheduled task. Any suggestions
    what I am doing wrong?
    #Starts Powershell Snap-In
    Start-Transcript -path c:\Scripts\StaffWithoutPhotos.txt
    add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 -erroraction silentlyContinue
    $mailboxes = $null
    $mailboxes = @(Get-Mailbox -OrganizationalUnit "Staff User Accounts" -ResultSize Unlimited | Where {$_.HasPicture -eq $False})
    Write-Host $mailboxes
    $report = @()
    foreach ($mailbox in $mailboxes)
    $mbObj = New-Object PSObject
        $mbObj | Add-Member -MemberType NoteProperty -Name "Display Name" -Value $mailbox.DisplayName
        $report += $mbObj
    Write-Host "Diagnostic Output"
    Write-Host "Before Mailbox value check"
    Write-Host $report
    Write-Host "After Mailbox Value check"
    if ($mailboxes -ne $null)
        Write-Host $report
        #Send the report generated to the e-mail list specified above
        $style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
        $style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
        $style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
        $style = $style + "TD{border: 1px solid black; padding: 5px; }"
        $style = $style + "</style>"
        #Start-Sleep -Seconds 5
        $smtpserver = "MAIL.contoso.com"
        $msg = new-object Net.Mail.MailMessage
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $msg.From = "[email protected]"
        $msg.To.Add("[email protected]")
        #$msg.To.Add("[email protected]") #Used for testing
        $msg.Subject = "Staff without Photos report"
        $msg.Body = "This report contains the list of users who do not currently have photos."
        $msg.Body += "<p>"
        $msg.Body += "After photos are available for these users please submit a request to have their accounts updated or send an e-mail to <a href='mailto:[email protected]?Subject=Staff%20Photo%20Updates' target='_top'> [email protected]
    </a> with <b>Staff Photo Updates</b> in the subject."
        $msg.Body += "<p>"
        $msg.Body += "This report runs on Fridays and will only send a message if we have Staff without Photos. For more information please contact your systems administrator."
        $msg.Body += "<p>"
        $msg.Body += $Report | ConvertTo-Html -Head $Style
        $msg.IsBodyHTML = $true
        $smtp.Send($msg)
    Stop-Transcript

    So after researching further and not receiving any more replies I decided to rewrite the script and attempt to use the send-mailmessage function. I have been unable to determine the reason for the original not script not working. We use a very similar script
    to my original code which works to generate a report and e-mail that report as an attachment and it works without any problems.
    After re-writing the script and using the send-mailmessage function I was able to get this report to work as expected. This has now been set up as a scheduled task to run on a server once a week. Here is the final code:
    Start-Transcript -path c:\Scripts\StaffWithoutPhotos.txt
    #Starts Powershell Snap-In
    add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 -erroraction silentlyContinue
    $mailboxes = $null
    $mailboxes = @(Get-Mailbox -OrganizationalUnit "contoso Staff User Accounts" -ResultSize Unlimited | Where {$_.HasPicture -eq $False})
    Write-Host $mailboxes
    $report = @()
    foreach ($mailbox in $mailboxes)
    $mbObj = New-Object PSObject
        $mbObj | Add-Member -MemberType NoteProperty -Name "Display Name" -Value $mailbox.DisplayName
        $report += $mbObj
    Write-Host "Diagnostic Output"
    Write-Host "Before Mailbox value check"
    Write-Host $report
    Write-Host "After Mailbox Value check"
    if ($mailboxes -ne $null)
        Write-Host $report
        #Send the report generated to the e-mail list specified above
        $style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
        $style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
        $style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
        $style = $style + "TD{border: 1px solid black; padding: 5px; }"
        $style = $style + "</style>"
        $smtpserver = "MAIL.contoso.com"
        $smtpFrom = "[email protected]"
        $smtpTo = "[email protected]
        $messageSubject = "Staff without Photos report"
        $Body = "This report contains the list of users who do not currently have photos."
        $Body += "<p>"
        $Body += "After photos are available for these users please submit a request to the Help Desk to have their accounts updated or send an e-mail to <a href='mailto:[email protected]?Subject=Staff%20Photo%20Updates' target='_top'> [email protected]
    </a> with <b><u>Staff Photo Updates</b></u> in the subject."
        $Body += "<p>"
        $Body += "This report runs on Fridays and will only send a message if we have Staff without Photos. For more information please contact your systems administrator."
        $Body += "<p>"
        $Body += $Report | ConvertTo-Html -Head $Style
        #Send the report
        send-mailmessage -from "$smtpFrom" -to "$smtpTo" -subject "$messageSubject" -body "$Body" -smtpServer "$smtpserver" -BodyAsHtml
    Stop-Transcript

  • Powershell script to update mailbox search

    I am trying to update a mailbox search using a powershell script:
    Stop-MailboxSearch -Identity "LitHolds" -confirm:$false
    $members = (import-csv -Path "Path"| ForEach-Object{$_.SamAccountName})
    foreach ($user in $members)
    Set-MailboxSearch -Identity "LitHolds" -SourceMailboxes $user.samaccountname
    Start-MailboxSearch -Identity "LitHolds" -confirm:$false
    I essentially have our sysadmins populating a csv file and then they run this script manually every night with the latest updates.  They are telling me that the mailbox search is empty.
    When I run the script I am getting a watson error immediately after with the following:
    WARNING: An unexpected error has occurred and a Watson dump is being generated: Value cannot be null.
    Parameter name: legacyDN
    Value cannot be null.
    Parameter name: legacyDN
        + CategoryInfo          : NotSpecified: (:) [Stop-MailboxSearch], ArgumentNullException
        + FullyQualifiedErrorId : System.ArgumentNullException,Microsoft.Exchange.Management.Tasks.StopMailboxSearch
        + PSComputerName        : Exchange Server Name
    What I don't understand is why it's looking for a legacyDN??
    Anyone able to do something similar?
    Chuck

    Hi Chuck,
    I would like to verify if you have a legacy Exchange.
    The LegacyDN property indicates the legacyDN of the mailbox and matches the legacyExchangeDN attribute of the user object in  Microsoft Active Directory.
    If there is any update, please feel free to let me know.
    Best regards,
    Amy
    Amy Wang
    TechNet Community Support

  • How can I Deny permissions to logon to Remote Desktop Session Host server in powershell script?

    I am need of some assistance please. I am a system admin and I am trying to create a script that will assist with the tedious tasks I have to do with disabling a user that no longer works for the company.
    I have created a script so far that will reset the users passwords and remove them from all groups (minus domain users).
    I am trying to make it where it will deny permissions to logon to Remote Desktop Session Host server as well as give full mailbox permission to the manager in Exchange Server 2010.
    I know with Exchange 2010, I will need to add the Powershell snapin. Is there a way for this to be added into the script? I am thinking to add the code:
    add-pssnapin Microsoft.exchange.management.powershell.e2010
    Is there another way to do this? Any help or recommendations would be much appreciated.
    $ou = Get-ADUser -SearchBase "<*OU info here*>" -Filter * |
    Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "<*Password here*>" -Force)
    foreach ($user in $ou) {
    $UserDN = $user.DistinguishedName
    Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
    if ($_.name -ne "Domain Users") {remove-adgroupmember -identity $_.name -member $UserDN -Confirm:$False} }

    Why not just disable the account?Why are you searching an OU foro users when you just want to terminate one user?
    You can remotely connect an exchange session and manipulate the mailbox permissions.  You do not load a snap-in except on the Exchange server.
    $Session=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<FQDN of Exchange 2013 Client Access server>/PowerShell/
    Import-PSSession $Session
    # exchange commands here
    \_(ツ)_/
    We have a checklist we have to go through with the tasks listed. We have to keep to the account enabled until HR changes
    the status which is usually 30-90 days depending. Managers sometimes need to access the accounts to retrieve information, etc. We put the users in an OU; once we are given permission from the manager we move forward in the removal. 

  • Schedule a powershell script

    Hi all,
    I have a problema scheduling a Powershell script using a batch file:
    I've tryed to do that with this two method:
    powershell -c ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'"
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1"
    The job works but inside the script there is the instruction:
    $Path = Get-Location
    This because the script create Log folder in same location where PS1 file is.
    Now scheduling the script using one of the method listed the script create the Log folder in path:
    C:\Windows\System32
    How ca n I prevent this and do the script create the folder in the same location where PS1 file is ?
    I hope to explain my problem
    Thanks

    If you're using Windows PowerShell 3.0, then you can take advantage of the automatic variable $PSScriptRoot to determine the location of the script. For instance, if I have a script that runs from C:\Scripts\myscript.ps1 and I want my script to create a
    text file in the same location, then I do not need to hard code this value. I just use $PSScriptRoot, such as: 
    Set-Content -Path "$PSScriptRoot\logfile.txt" -Value $Value
    This would create a text file called logfile.txt in C:\Scripts.
    Since you're working with Exchange (and possibly Windows PowerShell 2.0) you may need to stick with the $MyInvocation automatic variable and the Split-Path cmdlet, such as:
    Split-Path $MyInvocation.MyCommand.Path
    Test these outside of your script so you can learn a little about them, just be sure you put them into their own
    saved .ps1 file. They will not return anything if you throw them into the ISE or shell, unless they are part of a .ps1 file.
    Edit: Added script blocks for readability.

  • Is it possible to monitor State change of a .CSV file using powershell scripting ?

    Hi All,
    I just would like to know Is it possible to monitor State change of a .CSV file using powershell scripting ? We have SCOM tool which has that capability but there are some drawbacks in that for which we are not able to utilise that. So i would like
    to know is this possible using powershell.
    So if there is any number above 303 in the .CSV file then i need a email alert / notification for the same.
    Gautam.75801

    Hi Jrv,
    Thank you very much. I modified the above and it worked.
    Import-Csv C:\SCOM_Tasks\GCC2010Capacitymanagement\CapacityMgntData.csv | ?{$_.Mailboxes -gt 303} | Export-csv -path C:\SCOM_Tasks\Mbx_Above303.csv;
    Send-MailMessage -Attachments "C:\SCOM_Tasks\Mbx_Above303.csv" -To “[email protected]" -From “abc@xyz" -SMTPServer [email protected] -Subject “Mailboxex are above 303 in Exchange databases” -Body “Mailboxex are above 303 in Exchange databases" 
    Mailboxex - is the line which i want to monitor if the values there are above 303. And it will extract the lines with all above 303 to another CSV file and 2nd is a mail script to email me the same with the attachment of the 2nd extract.
    Gautam.75801

  • How to run Powershell script (function) through Windows Task Schduler ??

    Hello All,
    i have Powershell script which is created as a function. I have to give parameters to run the script. And it is working fine. Now i want to run this script through windows task scheduler but it is not working. I dont know how to call powershell function
    through task scheduler.
    From command line i run it like this:
    . c:\script\Get-ServiceStatusReport.ps1
    dir function:get-service*
    Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
    In windows Task scheduler I am giving this: it runs but i dont receive any output :
    Program/Script:
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    Parameter:
    -file ". 'Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService  "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail  mail01.xxx.gov.pk'"
    Please HELP !!!

    Thanks for the reply:
    The script is already saved as Get-ServiceStatusReport.ps1 .
    On powershell it does not run like .\Get-ServiceStatusReport.ps1 (parameter).
    But i have to call it as function:
    Like this:
    Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
    As you said:
    I tried to run it like this:
    Program/Script:
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    Parameter:
    -file "c:\script\Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService  "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail  mail01.xxx.gov.pk'"
    But its not working , on scheduler its giving error: (0xFFFD0000)
    Please HELP !!!
    WHOLE SCRIPT:
    function Get-ServiceStatusReport
    param(
    [String]$ComputerList,[String[]]$includeService,[String]$To,[String]$From,[string]$SMTPMail
    $script:list = $ComputerList
    $ServiceFileName= "c:\ServiceFileName.htm"
    New-Item -ItemType file $ServiceFilename -Force
    # Function to write the HTML Header to the file
    Function writeHtmlHeader
    param($fileName)
    $date = ( get-date ).ToString('yyyy/MM/dd')
    Add-Content $fileName "<html>"
    Add-Content $fileName "<head>"
    Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
    Add-Content $fileName '<title>Service Status Report </title>'
    add-content $fileName '<STYLE TYPE="text/css">'
    add-content $fileName "<!--"
    add-content $fileName "td {"
    add-content $fileName "font-family: Tahoma;"
    add-content $fileName "font-size: 11px;"
    add-content $fileName "border-top: 1px solid #999999;"
    add-content $fileName "border-right: 1px solid #999999;"
    add-content $fileName "border-bottom: 1px solid #999999;"
    add-content $fileName "border-left: 1px solid #999999;"
    add-content $fileName "padding-top: 0px;"
    add-content $fileName "padding-right: 0px;"
    add-content $fileName "padding-bottom: 0px;"
    add-content $fileName "padding-left: 0px;"
    add-content $fileName "}"
    add-content $fileName "body {"
    add-content $fileName "margin-left: 5px;"
    add-content $fileName "margin-top: 5px;"
    add-content $fileName "margin-right: 0px;"
    add-content $fileName "margin-bottom: 10px;"
    add-content $fileName ""
    add-content $fileName "table {"
    add-content $fileName "border: thin solid #000000;"
    add-content $fileName "}"
    add-content $fileName "-->"
    add-content $fileName "</style>"
    Add-Content $fileName "</head>"
    Add-Content $fileName "<body>"
    add-content $fileName "<table width='100%'>"
    add-content $fileName "<tr bgcolor='#CCCCCC'>"
    add-content $fileName "<td colspan='4' height='25' align='center'>"
    add-content $fileName "<font face='tahoma' color='#003399' size='4'><strong>Service Stauts Report - $date</strong></font>"
    add-content $fileName "</td>"
    add-content $fileName "</tr>"
    add-content $fileName "</table>"
    # Function to write the HTML Header to the file
    Function writeTableHeader
    param($fileName)
    Add-Content $fileName "<tr bgcolor=#CCCCCC>"
    Add-Content $fileName "<td width='10%' align='center'>ServerName</td>"
    Add-Content $fileName "<td width='50%' align='center'>Service Name</td>"
    Add-Content $fileName "<td width='10%' align='center'>status</td>"
    Add-Content $fileName "</tr>"
    Function writeHtmlFooter
    param($fileName)
    Add-Content $fileName "</body>"
    Add-Content $fileName "</html>"
    Function writeDiskInfo
    param($filename,$Servername,$name,$Status)
    if( $status -eq "Stopped")
    Add-Content $fileName "<tr>"
    Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$servername</td>"
    Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$name</td>"
    Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$Status</td>"
    Add-Content $fileName "</tr>"
    else
    Add-Content $fileName "<tr>"
    Add-Content $fileName "<td >$servername</td>"
    Add-Content $fileName "<td >$name</td>"
    Add-Content $fileName "<td >$Status</td>"
    Add-Content $fileName "</tr>"
    writeHtmlHeader $ServiceFileName
    Add-Content $ServiceFileName "<table width='100%'><tbody>"
    Add-Content $ServiceFileName "<tr bgcolor='#CCCCCC'>"
    Add-Content $ServiceFileName "<td width='100%' align='center' colSpan=3><font face='tahoma' color='#003399' size='2'><strong> Service Details</strong></font></td>"
    Add-Content $ServiceFileName "</tr>"
    writeTableHeader $ServiceFileName
    #Change value of the following parameter as needed
    $InlcudeArray=@()
    #List of programs to exclude
    #$InlcudeArray = $inlcudeService
    Foreach($ServerName in (Get-Content $script:list))
    $service = Get-Service -ComputerName $servername
    if ($Service -ne $NULL)
    foreach ($item in $service)
    #$item.DisplayName
    Foreach($include in $includeService)
    write-host $inlcude
    if(($item.serviceName).Contains($include) -eq $TRUE)
    Write-Host $item.MachineName $item.name $item.Status
    writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
    Add-Content $ServiceFileName "</table>"
    writeHtmlFooter $ServiceFileName
    function Validate-IsEmail ([string]$Email)
    return $Email -match "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
    Function sendEmail
    param($from,$to,$subject,$smtphost,$htmlFileName)
    [string]$receipients="$to"
    $body = Get-Content $htmlFileName
    $body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
    $body.isBodyhtml = $true
    $smtpServer = $MailServer
    $smtp = new-object Net.Mail.SmtpClient($smtphost)
    $validfrom= Validate-IsEmail $from
    if($validfrom -eq $TRUE)
    $validTo= Validate-IsEmail $to
    if($validTo -eq $TRUE)
    $smtp.UseDefaultCredentials = $true;
    $smtp.Send($body)
    write-output "Email Sent!!"
    else
    write-output "Invalid entries, Try again!!"
    $date = ( get-date ).ToString('yyyy/MM/dd')
    sendEmail -from $From -to $to -subject "Service Status - $Date" -smtphost $SMTPMail -htmlfilename $ServiceFilename

  • What's the standard header in PowerShell scripts (documentation)?

    Can anyone tell me what the "standard header" that I see in a lot of PowerShell scripts is all about? I have been unable to find any explanation so far.
    Here's a snippet:
    <#
    .SYNOPSIS
    Counts the Grateful Dead shows in my archives
    .DESCRIPTION
    This script looks at my GD archive, and uses folder names to
    determine show type (aud, sbd, etc), and checks to see what
    shows have checked MD5s
    .NOTES
    File Name : count-gdshows.ps1
    Author : Thomas Lee - [email protected]
    Requires : PowerShell V2 CTP3
    .LINK

    The help data can be used inside a function body or in a script. A script is not much different than a function, actually you can think of it as a function *without* a name, the name is the script name. You can a function like:
    function foo
    <# 
    .SYNOPSIS 
        Counts the Grateful Dead shows in my archives
    #>
       param($a,$b)
       $a+$b
    And execute it like:
    foo -a 3  -b 4
    or write the function body in a script file called foo.ps1 :
    ## foo.ps1 ##
    <# 
    .SYNOPSIS 
        Counts the Grateful Dead shows in my archives
    #>
       param($a,$b)
       $a+$b
    and execute it like so:
    .\foo.ps1 -a 3 -b 4
    they give the same output. Windows 7 is goiung to RTM soon and as you probably know PowerShell v2 ships with it, so you can switch to v2 in the very near future. I'm working with v2 since the CTP versions (on my production machine) and it is working very good, lots of new exiting stuff!
    As for functions vs scripts... it depends. On my personal machine I save my functions in various ways. I categorize them and save each bunch in a seperate script file (i.e. utilities.ps1, exchange.ps1, ad.ps1 etc). Some files I use more on a regular basis so I dot-source them in my profile, other scripts I load when I need. v2 introduced a module concept so the next evolution of my script files will turn into modules.  I also implement some functions in ps1xml files, these are used to extend objects , via PowerShells' Extended Type System (ETS), you can find an example on my blog (http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2009/05/31/getting-certificates-expiration.aspx).
    Shay Levy [MVP]
    http://blogs.microsoft.co.il/blogs/ScriptFanatic
    PowerShell Toolbar

  • Powershell script for mailbox permissions

    Hello,
    Part of my tasks as an Exchange admin is to give access to shared mailboxes. The access usually are:
    Send AS
    Receive As
    Send on Behalf Of
    Full mailbox
    Is there a powershell script out there that does all of the above?
    thanks,
    Alexis

    Hi,
    Probably not prewritten, but you can check the repository for starters:
    http://gallery.technet.microsoft.com/scriptcenter
    EDIT: I should mention - this isn't too hard to write, so this could be a good opportunity to learn how to get around in the EMS.
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

Maybe you are looking for

  • FTP Adapter : Issue with Non English Text.

    Dear All, We are trying to read a file which contains Korean Language and write into a different folder in a CSV format. The output file contains "???" inplace of Korean text. We can see the invoke to FTP adapter contains Korean text as part of it's

  • Order in SAP CRM

    Hi Friends, Please tell me step by step procees in SAP-CRM to create an order.If possible explain with a scenario.send me documents if any. Regards, Jayapal.

  • HT1040 Unable to 'buy' book

    Hi.  I have created a book in iPhoto'11, I am now trying to buy it.  When I select 'buy' my order comes up, with just the cost no other details.  If I select 'checkout' it does nothing.  Help!  Am I missing something?  I'm in Australia.

  • Can't open a saved interactive form

    I have developed an interactive form using ABAP WebDynpro. While I have the form displayed (with or without having filled in any values), I use the "save" button on the standard Adobe toolbar (i.e. not anything I programmed myself) to save the form t

  • Which scenerio we use at new and on change....

    i which scenerio we use at new then on change.... basically what is the difference b/w them...