Script that enables mail users and kicks out two csv files

I am working on a script that will mainly be used as a scheduled task to enabled mailuser by calling the update-recipient command. 
But before it calls that command it will get for various issues that can cause errors.
Missing PrimarySMTP
Display name having a space at front or back.
The external email address being blank.
I have IF statements setup to check for those and then call a function that will save into an array the issue for that user. 
Here is the script
<#
.SYNOPSIS
Enable-MailUsers Synced Mail Users in the Exchange environment
THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE
RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
Version .9, 30 June 2014
.DESCRIPTION
This script mail-enables Synced Mail Users and creates a CSV report of mail users that were enabled.
The following is shown:
* Report Generation Time
.PARAMETER SendMail
Send Mail after completion. Set to $True to enable. If enabled, -MailFrom, -MailTo, -MailServer are mandatory
.PARAMETER MailFrom
Email address to send from. Passed directly to Send-MailMessage as -From
.PARAMETER MailTo
Email address to send to. Passed directly to Send-MailMessage as -To
.PARAMETER MailServer
SMTP Mail server to attempt to send through. Passed directly to Send-MailMessage as -SmtpServer
.PARAMETER ScheduleAs
Attempt to schedule the command just executed for 10PM nightly. Specify the username here, schtasks (under the hood) will ask for a password later.
.EXAMPLE
Generate the HTML report
.\Enable-MailUsers.ps1 -SendMail -MailFrom [email protected] -MailTo [email protected] -MailServer ex1.contoso.com -ScheduleAs SvcAccount
#>
param(
[parameter(Position=0,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Send Mail ($True/$False)')][bool]$SendMail=$false,
[parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail From')][string]$MailFrom,
[parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail To')]$MailTo,
[parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail Server')][string]$MailServer,
[parameter(Position=4,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Schedule as user')][string]$ScheduleAs
# Sub Function to neatly update progress
function _UpProg1
param($PercentComplete,$Status,$Stage)
$TotalStages=5
Write-Progress -id 1 -activity "Mail enabled Objects" -status $Status -percentComplete (($PercentComplete/$TotalStages)+(1/$TotalStages*$Stage*100))
#Sub Function create ErrObject output
function _ErrObject{
Param($name,
$errStatus
If(!$err){
Write-Host "error detected"
$script:err = $True
$ErrObject = New-Object -TypeName PSObject
$Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
$Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
$script:ErrOutput += $ErrObject
# 1. Initial Startup
# 1.0 Check Powershell Version
if ((Get-Host).Version.Major -eq 1)
throw "Powershell Version 1 not supported";
# 1.1 Check Exchange Management Shell, attempt to load
if (!(Get-Command Get-ExchangeServer -ErrorAction SilentlyContinue))
if (Test-Path "D:\Exchsrvr\bin\RemoteExchange.ps1")
. 'D:\Exchsrvr\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
} elseif (Test-Path "D:\Exchsrvr\bin\Exchange.ps1") {
Add-PSSnapIn Microsoft.Exchange.Management.PowerShell.Admin
.'D:\Exchsrvr\bin\Exchange.ps1'
} else {
throw "Exchange Management Shell cannot be loaded"
# 1.2 Check if -SendMail parameter set and if so check -MailFrom, -MailTo and -MailServer are set
if ($SendMail)
if (!$MailFrom -or !$MailTo -or !$MailServer)
throw "If -SendMail specified, you must also specify -MailFrom, -MailTo and -MailServer"
# 1.3 Check Exchange Management Shell Version
if ((Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction SilentlyContinue))
$E2010 = $false;
if (Get-ExchangeServer | Where {$_.AdminDisplayVersion.Major -gt 14})
Write-Warning "Exchange 2010 or higher detected. You'll get better results if you run this script from an Exchange 2010/2013 management shell"
}else{
$E2010 = $true
$localserver = get-exchangeserver $Env:computername
$localversion = $localserver.admindisplayversion.major
if ($localversion -eq 15) { $E2013 = $true }
#Get date
$filedate = get-date -uformat "%m-%d-%Y"
$filedate = $filedate.ToString().Replace("0", "")
#Get the valid users that are not mail-enabled
_UpProg1 1 "Getting User List" 1
#$Users = Get-mailuser -ResultSize unlimited -OrganizationalUnit "R0018.COLLABORATION.ECS.HP.COM/Accounts/AbbVienet/Users" | ?{$_.legacyexchangeDN -eq ""}
$i = 0
$output = @()
$errOutput = @()
$err = $False
#2 Process users
ForEach ($User in $Users){
$i++
_UpProg1 ($i/$Users.Count*100) "Updating Recipients" 2
If ($user.ExternalEmailAddress -eq $null){
_ErrObject $user.Name, "Missing External Email Address"
ElseIf($user.DisplayName -NotLike "* "){
_ErrObject $user.Name, "DisplayName contains a trailing space"
ElseIf($user.DisplayName -NotLike "_*"){
_ErrObject $user.Name, "DisplayName contains a Leading space"
ElseIf($user.PrimarySmtpAddress -eq $null){
_ErrObject $user.Name, "Missing Primary SMTP address"
Else{
#Disable EmailAddressPolicy on these users
Set-Mailuser $User.Name -EmailAddressPolicyEnabled $false
#pass to Update-recipient
Update-Recipient $User.Name
$LEDN = Get-MailUser $User.Name | Select {$_.LegacyExchangeDN}
If ($LEDN -ne ""){
$object = New-Object -TypeName PSObject
$X500 = "x500:" + $LEDN.'$_.LegacyExchangeDN'
$object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $User.Name
$object | Add-Member -Name 'x500' -MemberType Noteproperty -Value $X500
$output += $object
#Creating CSVFile Output
_UpProg1 99 "Outputting CSV file 3" 3
$CSVFile = "c:\scripts\Mail-enable\Mailenabled_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
If($err){
$ErrCSVFile = "c:\scripts\Mail-enable\ProblemUsers_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
$errOutput | Select-Object Name, Comment | ConvertTo-CSV -NoTypeInformation > $ErrCSVFIle
$Output | ConvertTo-Csv -NoTypeInformation > $CSVFile
if ($SendMail)
_UpProg1 95 "Sending mail message.." 4
If($err){
Send-MailMessage -Attachments $CSVFile,$ErrCSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
Else{
Send-MailMessage -Attachments $CSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
if ($ScheduleAs)
_UpProg1 99 "Attempting to Schedule Task.." 4
$dir=(split-path -parent $myinvocation.mycommand.definition)
$params=""
if ($SendMail)
$params+=' -SendMail:$true'
$params+=" -MailFrom:$MailFrom -MailTo:$MailTo -MailServer:$MailServer"
$task = "powershell -c \""pushd $dir; $($myinvocation.mycommand.definition) $params\"""
Write-Output "Attempting to schedule task as $($ScheduleAs)..."
Write-Output "Task to schedule: $($task)"
schtasks /Create /RU $ScheduleAs /RP /SC DAILY /ST 22:00 /TN "Enable Mail Users" /TR $task
The Problem is that when I look at the $errOutput I see things but when I pipe the $erroutput to convertTo-CSV I get this within the CSV file. I think its because I an calling a function to do the updating. But not sure.
Jeff C

Hi Jeff,
Any updates? If you have any other questions, please feel free to let me know.
A little clarification to the script:
function _ErrObject{
Param($name,
$errStatus
If(!$err){
Write-Host "error detected"
$script:err = $True
$ErrObject = New-Object -TypeName PSObject
$Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
$Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
$script:ErrOutput += $ErrObject
$errOutput = @()
_ErrObject Name, "Missing External Email Address"
$errOutput
_ErrObject Name "Missing External Email Address"
$errOutput
If you have any feedback on our support, please click here.
Best Regards,
Anna Wang
TechNet Community Support

Similar Messages

  • Script that enables Remote Management and adds user

    I need to make a script that can enable Remote Management and add a user to control it.
    I have tried to watch which plist files it uses so I could edit those.
    It writes some text in com.apple.RemoteManagement.plist and com.apple.ARDAgent.plist bit I can't find where the user is added.
    Any ideas guys
    Thanks

    No need to mess around with .plists. ARD has a command-line admin tool. The syntax is a little funky, but this should give you an idea:
    $ sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/k ickstart -activate -configure -access -on -users john -restart -agent -privs -all
    This is all covered in more detail in Apple's technote.

  • Trying to install adobe photoshop on macbook pro but at 50% it gives error message and kicks out dis

    trying to install adobe photoshop on macbook pro but at 50% it gives error message and kicks out disc

    copy the disc contents to a desktop folder and click setup in that desktop folder.
    if that fails what ps version are you trying to install and what is your os version?

  • Sharepoint 2010 User getting kicked out of share point multiple time , can some one help me what coule be reason

    using SharePoint 2010 > under marketing > task, user getting kicked out of share point multiple times. don't know the reason, does any one have any idea,  learning about SP,  any help will be appreciated.

    try this one:
    http://sharepointsolutions.blogspot.com/2008/06/how-do-i-make-our-sharepoint-site-stop_17.html
    if fixed the issue fine other wise could you please check the ULS logs/ application ?IIS logs at the same time user kicked out.
    Please remember to mark your question as answered &Vote helpful,if this solves/helps your problem. ****************************************************************************************** Thanks -WS MCITP(SharePoint 2010, 2013) Blog: http://wscheema.com/blog

  • Converted vinyl to digital but now when I try to burn the music to a cd it says there is a writing error and kicks out the disc.

    Just converted a bunch of my dad's old vinyl to digital via the ion ez vinal converter.   However when I went to burn the music, which sound fine over the computer, to a cd it says there is a writing error and kicks out the disc.  Can I correct this somehow without having to import these all again?

    Update yrou OS to 10.6.8.
    The problem is not with iTunes or the file so you won't need to import them again.
    Try a different brand of disc.

  • Without flash, it seems that us iPad users are copping out on lots of browsing activity. When are we going to get a flash compatible plug in? Very frustrating...

    Without flash, it seems that us iPad users are copping out on lots of browsing possibilities on the Internet. When are we going to get a compatible flash plugin??

    It will never happen. Adobe announced sometime ago that they will no longer develop Flash for mobile devices, so once again, it is never going to happen for iOS devices.
    There are browsers in the App Store that allow for some Flash content. Photon, Sky Fire, Puffin, look at a couple of those,

  • How do I compare two csv files and not disable the user if the username is found in the 2nd file using powershell?

    Hi Guys
    I have two csv files with the following headers and I need to import both files into the script to check whether the StaffCode is present in the Creation/Renewal of Contract csv in a DisableAccount Script so I can stop any action to disable the account as
    the staff has renewed the contract with the company so the account should not be disabled.
    However my accounts are still being disabled. I am not sure now to construct the query so that it detects that the account is to be left alone if the staffcode is present in both files
    I does recognize that the $staffcodeN in the renewal file matches the $staffcode in the termination file
    but still proceeds to disable or set an expiry date to the account anyway based on the termination file. 
    How do I stop it from doing that?
    1)In the Creation/Renewal of contract file the following headers are present
         -  TranCode,StaffCode,LastName,FirstName,SocialSecurityNo,DateJoin,Grade,Dept,LastUpdateDate,EffectiveDate
    2)In the Disable of contract file the following headers are present
        - TranCode,StaffCode,LastName,FirstName,SocialSecurityno,LastDateWorked,Grade,Dept,LastUpdateDate,
    My data is not very clean , I have a-lot of special characters such as = , ' ,/ and \ characters to remove first before i can compare the data
    Thanks for the help in advance.
    Yours Sincrely
    Vicki
    The following is a short snippet of the code 
    $opencsv = import-csv "D:\scripts\Termination.csv"
    $opencsv2 = import-csv "D:\scripts\RenewContractandNewStaff.csv"
    foreach ($usertoaction in $opencsv) 
    $Trancode = $usertoactionTranCode
    $StaffCode = $usertoaction.StaffCode.replace("=","").replace('"','')
    $LastName = [string]$usertoaction.LastName.Replace("/","\/").Replace(",","\,")
    $FirstName = [string]$usertoaction.FirstName.Replace("/","\/").Replace(",","\,")
    $socialsecurityno = $usertoaction.SocialSecurityNo.replace("=","").replace('"','')
    $DateJoin = $usertoaction.DateJoin.replace("=","").replace('"','')
    $LastDateWorked = $usertoaction.LastDateWorked.replace("=","").replace('"','')
    $Grade = [string]$usertoaction.Grade
    $Dept = [string]$usertoaction.Dept
    $LastUpdateDate = $usertoaction.LastUpdateDate.replace("=","").replace('"','')
    $AccountExpiry = [datetime]::Now.ToString($LastDateWorked)
    foreach ($usertoaction2 in $opencsv2) 
    $TrancodeN = $usertoaction2.TranCode
    $StaffCodeN = $usertoaction2.StaffCode.replace("=","").replace('"','')
    $socialsecurityNoN= $usertoaction2.SocialSecurityNo.replace("=","").replace('"','')
    $DateJoinN = $usertoaction2.DateJoin.replace("=","").replace('"','')
    $GradeN = [string]$usertoaction2.Grade
    $DeptN = $usertoaction2.Dept
    $LastUpdateDate = $usertoaction.LastUpdateDate.replace("=","").replace('"','')
    $EffectiveDate = $usertoaction.EffectiveDate.replace("=","").replace('"','')
    $LastName2 = [string]$usertoaction2.LastName.Replace(",", "").Replace("/","").trim()
    $FirstName2 = [string]$usertoaction2.FirstName.Replace("/","").trim()
    # Use DirectorySearcher to find the DN of the user from the sAMAccountName.
    $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
    $Root = $Domain.GetDirectoryEntry()
    $Searcher = [System.DirectoryServices.DirectorySearcher]$Root
    $Searcher.Filter = "(sAMAccountName=$samaccountname)"
    $doesuserexist1 = $Searcher.Findall()
    if ($doesuserexist1 -eq $Null)
    {Write-Host $samaccountname "account does not exist"}
    elseif ($StaffCodeN -match $staffcode)
    write-host "user has renewed the contract, no action taken"
    else
    if(($lastupdatedate -ne $null)-or($LastDateWorked -ne $null))
                        write-host "Setting Account Expiry to"$accountexpirydate
    #$ChangeUser.AccountExpires = $accountexpirydate
               #$Changeuser.setinfo()
    if ($UserMailforwarding -ne $null)
    #Set Account expiry date to Last Date Worked
    # $ChangeUser.AccountExpires = $accountexpirydate
    # $Changeuser.setinfo()
     write-host "staff" $displayname "with staff employee no" $samaccountname "has                          
    mailforwarding" 
    Write-host "Please disable the account manually via Active Directory Users & Computers and 
    Elseif ($accountexpirydate -lt $todaysdate)
    #disable the account

    Hi Vicki,
    This Forum has an insert-codeblock function. Using it will make your script far more readable
    Your script is missing some parts, it is impossible to follow the problem.
    You are performing the same string cleaning action on $opencsv2 for each element in $opencsv, when doing it once should suffice. Why not start it all by cleaning the values and storing the cleaned values in new arrays?
    The Compare-Object function is great, why not take it out for a stroll on these lists, it might just safe you lots of unnecessarily complicated code ...
    You are creating a new $Domain, $Root and $Searcher object each iteration, when doing it once should suffice. Probably not much of a time-saver, but every little thing contributes.
    Try pinpointing the problem by doing extensive logging, not only by writing which action was taken, but writing the inidividual information (variables, mostly) before evaluation occurs. Your if/elseif/else looks sound, so if it's still not doing what you
    want, the ingoing data must be different from what you think should be there.
    Cheers,
    Fred
    There's no place like 127.0.0.1

  • Read two CSV files and remove the duplicate values within them.

    Hi,
    I want to read two CSV files(which contains more than 100 rows and 100 columns) and remove the duplicate values within that two files and merge all the unique values and display it as a single file.
    Can anyone help me out.
    Thanks in advance.

    kirthi wrote:
    Can you help me....Yeah, I've just finished... Here's a skeleton of my solution.
    The first thing I think you should do is write a line-parser which splits your input data up into fields, and test it.
    Then fill out the below parse method, and test it with that debugPrint method.
    Then go to work on the print method.
    I can help a bit along the way, but if you want to do this then you have to do it yourself. I'm not going to do it for you.
    Cheers. Keith.
    package forums.kirthi;
    import java.util.*;
    import java.io.PrintStream;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import krc.utilz.io.ParseException;
    import krc.utilz.io.Filez.LineParser;
    import krc.utilz.io.Filez.CsvLineParser;
    public class DistinctColumnValuesFromCsvFiles
      public static void main(String[] args) {
        if (args.length==0) args = new String[] {"input1.csv", "input2.csv"};
        try {
          // data is a Map of ColumnNames to Sets-Of-Values
          Map<String,Set<String>> data = new HashMap<String,Set<String>>();
          // add the contents of each file to the data
          for ( String filename : args ) {
            data.putAll(parse(filename));
          // print the data to output.csv
          print(data);
        } catch (Exception e) {
          e.printStackTrace();
      private static Map<String,Set<String>> parse(String filename) throws IOException, ParseException {
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(filename));
          CsvLineParser.squeeze = true; // field.trim().replaceAll("\\s+"," ")
          LineParser<String[]> parser = new CsvLineParser();
          int lineNumber = 1;
          // 1. read the column names (first line of file) into a List
          // 2. read the column values (subsequent lines of file) into a List of Set's of String's
          // 3. build a Map of columnName --> columnValues and return it
        } finally {
          if(reader!=null)reader.close();
      private static void debugPrint(Map<String,Set<String>> data) {
        for ( Map.Entry<String,Set<String>> entry : data.entrySet() ) {
          System.out.println("DEBUG: "+entry.getKey()+" "+Arrays.toString(entry.getValue().toArray(new String[0])));
      private static void print(Map<String,Set<String>> data) {
        // 1. get the column names from the table.
        // 2. create a List of List's of String's called matrix; logically [COL][ROW]
        // 3. print the column names and add the List<String> for this col to the matrix
        // 4. print the matrix by inerating columns and then rows
    }

  • Adobe story does not export lines of dialogue that are amrked with (CONT'D) into a csv file.

    For some reason Adobe story does not export lines of dialogue that are marked with (CONT’D) into a csv file. The rest of the dialogue exports fine, bit the bits that are marked with (CONT’D) do not show up in the dialogue column !. Can this be changed with some settings or is this a bug? The script was imported from an FDX file. If anyone has a fix for this, please, let me know.
    Thenk you.

    Thanks for reporting this issue.
    This is indeed a bug.
    Just to get correct data in csv, a workaround for this issue could be to replace word 'CONT'D' with a place-holder word, perform an export-to-csv and then change it back.
    1. Press Ctrl+F in script to open Find/Replace
    2. Replace word 'CONT'D' with a placeholder word, say 'TEMPCONTD'
    3. Export the script to csv
    4. Now replace the placeholder word with 'CONT'D'

  • By using OID how to unzip the folder and load bunch of .csv files

    Hi All
    bellow is the my scenario.
    in my scenarion we have created FTP folder that will load the .zip files(Every Day).
    .zip files that will contain bunch of .csv file (flat files) and by using OID need to extract the .zip file and load the all .csv files into target database. source data is .csv files and target data is oracle10g. Dose it will possible by using ODI?? please suggest me...
    Thanks in Advance
    Zakeer

    Hi,
    i'm interrested on this way of reading multiple files, i tried to follow those steps but i'm getting an error while running the package:
    ODI-1226: Step vReadFile fails after 1 attempt(s).
    ODI-1236: Error while refreshing variable VOUCHER_CUSTOMER_DATA_INTEGRATION.vReadFile.
    Caused By: java.lang.NumberFormatException: For input string: "#Activity_report_name"
    the variable vReadFile can't recognize the other variable Activity_report_name.
    the refreshing query for vReadFile is :
    select     file     C1_FILE
    from      TABLE
    /*$$SNPS_START_KEYSNP$CRDWG_TABLESNP$CRTABLE_NAME=files_namesSNP$CRLOAD_FILE=C:\/files_name.txtSNP$CRFILE_FORMAT=DSNP$CRFILE_SEP_FIELD=0x0009SNP$CRFILE_SEP_LINE=0x000D0x000ASNP$CRFILE_FIRST_ROW=#Activity_report_nameSNP$CRFILE_ENC_FIELD=SNP$CRFILE_DEC_SEP=SNP$CRSNP$CRDWG_COLSNP$CRCOL_NAME=fileSNP$CRTYPE_NAME=STRINGSNP$CRORDER=1SNP$CRLENGTH=50SNP$CRPRECISION=50SNP$CRACTION_ON_ERROR=0SNP$CR$$SNPS_END_KEY*/
    any suggestion plz
    regards

  • Can someone please help, I have a dvd disk containing lecture videos, on a Windows pc it works fine, and the disk opens to the dvd menu. However on my macbook pro running Mountain Lion, it opens as a data disk, with video and audio in two seprate files??

    Can someone please help, I have a dvd disk containing lecture videos, on a Windows pc it works fine, and the disk opens to the dvd menu. However on my macbook pro running Mountain Lion, it opens as a data disk, with video and audio in two seprate files??

    You may need a 3rd party application to view the DVD in a wWindows format such as
    http://flip4mac-3.en.softonic.com/mac
    https://www.macupdate.com/app/iphone/5758/vlc-media-player

  • I purchased an audiobook and there are two parts/files to it.  I-Tunes is only finding one of the files.  How do I get it to find and consolidate the files under one book title?

    I purchased an audiobook and it has two parts/files to it.  I-Tunes only shows on file under the book title.  How do I get i-Tunes to find and associate the two files under one book title?

    Thanks very much I have contacted them via this. Just hope they respond quickly- rather annoing! Greatly appreciated though

  • Are there any self-service tools that enable business users to insert, update, and delete data in SQL Server without using SSMS?

    Our IT department spends way too much time maintaining simple reference tables that could easily be maintained by business users, if they had some simple tools that gave them limited access to only the tables they need.  Looking for something other
    than SSMS or MS Access.  These are not tech-savvy users.  They dabble in Excel and Access, and they know their data pretty well, but wouldn't be comfortable with SQL.  Generally the data would initially be in Excel (but not always).

    Create a separate FileGroup on your UAT/pre-prod environment for those Business Users and allocate limited space for them to read/write data here. I expect they create their own reference tables here which are small enough in size. SQL Server does not have
    concept of Quota like Oracle has, so you need to tie back FG with Data Steward user groups using separate mechanism to make sure they have limited rights here. 
    As IT - you verify business changes every sprint and push them to Production. 
    Best Regards
    Shrikant Kulkarni 
     

  • Script to find a user and restart two services

    I am looking to make a script to first find a user that is connected to a server (list) the to stop Spooler, then stop cpsvc. Once the services are stopped, the script would then clear out the folder on "C:\Windows\System32\spool\PRINTERS"
    Directory. Once that was done, the script would then start Spooler and cpsvc. At the end it would echo the services were restarted and to try to print now.
    Lee Mossolle

    A user cannot stop and start services and cannot delete files in the system folders.
    There is no need to look for the services in that way  You will have to do this remotely.  Just find the services if they exisit and stop them then remotely delete the contents of the spooler folder.
    PowerShell remoting would be the easies way to do this.
    strComputer = WScript.Arguments(0)
    WScript.Echo "Running Against Remote Computer Named: " & strComputer
    set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name = 'cpsvc' OR Name = 'spooler'")
    for Each objService in colListOfServices
    objService.StopService()
    objService.StartService()
    Next
    Until you understand how yor code will work avoid over coding.  It just adds confusion and errors.   The above is functionally equivalent to what you posted. 
    I suspect there may be a dependency between cpsvc and spooler.  In that casr yo can only kill them in the correct order.  This will require to loops of a more sophisticated scripting approach.
    We can also use the 'Forse' argument and retriev the master service (spooler) and force it to stop all dependent services.  We would then retrive all services and start them. We can also just retrieve the dependency list and use that.
    The code is simple and will allow the dependencies to be added if needed.
    You can also use PowerShell which is much easier.
    Get-Service spooler -computer remotepc | Stop-Service -force
    Get-Service spooler -computer remotepc | Start-Service
    We can wrap this in a function for convenience.
    ¯\_(ツ)_/¯

  • Help with mail users and setup 10.6 mail server bound to 10.8 Open Directory

    We have a 10.7 Open Directory server which was upgraded from 10.6.  We have had some Open Directory issues since the upgrade.  I am manually creating a 10.8 server as a replacement for the 10.7 server.  All settings for services are running as expected and we are ready to turn over to the new server except for a problem with the ability to receive email.
    Setup in both the original and the replacement has the OD server with DNS running with a correct MX record pointing to our 10.6 mail server.
    In the replacement OD server the mail users were created as network users, with no userhome, with access to the mail service, and email addresses given. 
    The mail server was unbound from the original OD server, bound to the replacement OD server without SSL exactly as with the original, and restarted.
    Initially the mail service said that mail clients had the wrong name or password.  Opened WGM 10.6 on the MAIL server and checked the OD records.  They showed the mail users not having the checkbox saying they were set up to receive mail selected.  Selected the checkbox to receive mail.
    Now the mail client seems to connect to the server correctly but does not show the emails in the system for the users.  It is as though there is no email and the account is brand new.
    Unbind the mail server from the replacement OD server, rebind it to the original OD server, and restart.
    Mail clients connect and receive the mail in the accounts as expected.
    Any ideas?
    Thanks

    I figured out what the mail server is doing.  It has created new email stores for each of the new users.  If we bind to the original OD it uses the original set of email stores.  If we bind to the replacement OD it uses the new set of email stores.
    I have tried to make sure that the userIDs match in each OD but that did not help.
    The server is working for each OD.  Does anyone know if I can tell the 10.6 mail server to use the old emails in the mailstore for the new user in the new OD?
    If nothing else I can solve the problem by archiving the emails and copying them into the new user when running the new OD.

Maybe you are looking for

  • External hard drives and iphoto

    hi. i have an external hard drive where i would like to store some of my very large photo library. i would like to use iphoto but it seems like when i use "add to library" for a folder on my external drive it copies all the photos from that folder to

  • Power cord

    i am just curious if i should leave the computer plugged in while im at home. it stays plugged in unless i leave with it...is this good or bad?

  • Relocating Masters from one ext. drive to another...

    I am seeking some advice to Aperture (latest version): So far the folder of my Master-files has been relocated to an external hard disk, Consequently, in the event of reediting my pictures, I shall have to connect the said hard disk, when/if I would

  • Excel ActiveX: Server Execution Failed Error

    I'm using my own ActiveX VIs to control Excel. I take a text file and create a chart from some of the columns, then print the chart. I'm getting a "server execution failed" error when I call PrintOut on the chart object. I understand this error stems

  • Typical problem with BLOB.

    while i am using blob to store file content (for word documents more than 400 kb) iam facing this error. java.sql.sqlexception : ORA-01401:INSERTED VALUE TOO LARGE FOR COLUMN if it is some pdf files more than this size it is uploading. pls help me in