How can I run a counter by number of times the script is run

So I've created a script for disabling exchange mailboxes and moving them to a disabled OU in AD.  I currently have this set to run once a week via scheduled tasks but instead would like to kick it up to nightly and improve on the logging.
Right now, the only items I record are the name of the person and the OU they were originally in.  I'd also like to include the groups they were a member of.  I could easily enough include all the groups they were a member of in the email but here
is the twist.
Since we are going to a nightly run of this script, we would want to keep at least a weeks worth of logs in a text file as a just in case.  After a week, the log would be cleared.  I know that would be a counter but I can't even wrap my mind around
how that would work.  Is it even possible?
#Finds all users who have the AD attributes
# wWWHomePage = Updated_by_GroupID
# msExchHideFromAddressLists = True
# msExchHomeServerName not empty
# emailaddress contains @MyDomain.com
# useraccountcontrol = 514 (disabled)
Import-Module ActiveDirectory
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
#Declare Variables
$users = $null
$ADgroups = $null
$username = $null
$user = $null
$LogFile = "C:\Scripts\TerminateUsersLogFile.txt"
$LogFile2 = "C:\Scripts\UserNamesMovedtoDisabledOU.txt"
$EmailLogTo = "[email protected]"
#Generates log file
Start-Transcript -path $LogFile
#Performs search for all users in AD filtering only AD user with wWWWHomePage = Updated_by_GroupID, msExchHideFromAddressLists = True, msExchHomeServerName not empty and emailaddress contains @MyDomain.com
$users = Get-ADUser -properties name, emailaddress -Filter {(HomePage -eq "Updated_by_GroupID") -and (msExchHideFromAddressLists -eq $true) -and (emailaddress -like "*@MyDomain.com") -and (msExchHomeServerName -ne "$null") -and (useraccountcontrol -eq "514")}
$users.name -Replace '^cn=([^,]+).+$','$1'
#loops through all users
foreach ($user in $users){
$user.name -Replace '^cn=([^,]+).+$','$1'
#Copies the current OU into the Notes field in the AD User Object.
$newvar = ($user).distinguishedname
set-aduser $user -replace @{info="$newvar"}
# Removes user from all AD groups except Domain Users.
$ADgroups = Get-ADPrincipalGroupMembership -Identity $user | where {$_.Name -ne "Domain Users"}
Remove-ADPrincipalGroupMembership -Identity "$($user)" -MemberOf $ADgroups -Confirm:$false
#Disables their Exchange Mailbox.
Disable-Mailbox -Identity $user.EmailAddress -Confirm:$False
#Moves their AD user object to disabled OU.
Move-ADObject -Identity "$($user.DistinguishedName)" -TargetPath "Disabled Users OU" -Confirm:$false
Write-Output $user.name >> C:\Scripts\UserNamesMovedtoDisabledOU.txt
Stop-Transcript
# Email the log file
$emailFrom = "[email protected]"
$emailTo = $EmailLogTo
$subject = "Terminated Users Cleaned in AD"
$content = Get-Content $LogFile2 | ForEach-Object {$_.Split("`r`n")}
$body = [string]::Join("`r`n",$content)
$smtpServer = "SMTP.MyDomain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
clear-content C:\Scripts\UserNamesMovedtoDisabledOU.txt

I apologize for the long delay in replying.  I thank everyone for their help but I'm still running into issues with the script.  Below is the script as it is right now.  I'm having issues with logging as the groups the associate is a member
of are not logging correctly.
#Finds all users who have the AD attributes
# wWWHomePage = Updated_by_GroupID
# msExchHideFromAddressLists = True
# msExchHomeServerName not empty
# emailaddress contains @MyDomain.com
# useraccountcontrol = 514 (disabled)
Import-Module ActiveDirectory
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
#Declare Variables
$users = $null
$ADgroups = $null
$username = $null
$user = $null
$LogFile = "C:\Scripts\CleanUpTermedUsers\TerminateUsersLogFile.log"
$LogFile2 = "C:\Scripts\CleanUpTermedUsers\UserNamesMovedtoDisabledOU.txt"
$EmailLogTo = "[email protected]"
#Generates log file
Start-Transcript -path $LogFile
#Performs search for all users in AD filtering only AD user with wWWWHomePage = Updated_by_GroupID, msExchHideFromAddressLists = True, msExchHomeServerName not empty and emailaddress contains @mydomain.com
$users = Get-ADUser -properties name, emailaddress -Filter {(HomePage -eq "Updated_by_GroupID") -and (msExchHideFromAddressLists -eq $true) -and (emailaddress -like "*@mydomain.com") -and (msExchHomeServerName -ne "$null") -and (useraccountcontrol -eq "514")}
$users.name -Replace '^cn=([^,]+).+$','$1'
#loops through all users
foreach ($user in $users){
$user.name -Replace '^cn=([^,]+).+$','$1'
#Copies the current OU into the Notes field in the AD User Object.
$UserOU = ($user).distinguishedname
set-aduser $user -replace @{info="$UserOU"}
# Removes user from all AD groups except Domain Users.
$ADgroups = Get-ADPrincipalGroupMembership -Identity $user | where {$_.Name -ne "Domain Users"}
Write-Output $user.name >> C:\Scripts\CleanUpTermedUsers\UserNamesMovedtoDisabledOU.txt
write-output $ADgroups.name >> C:\Scripts\CleanUpTermedUsers\UserNamesMovedtoDisabledOU.txt
echo $ADgroups.name
Remove-ADPrincipalGroupMembership -Identity "$($user)" -MemberOf $ADgroups -Confirm:$false
#Disables their Exchange Mailbox.
Disable-Mailbox -Identity $user.EmailAddress -Confirm:$False
#Moves their AD user object to disabled OU.
Move-ADObject -Identity "$($user.DistinguishedName)" -TargetPath "Disabled OU" -Confirm:$false
Stop-Transcript
# Email the log file
$emailFrom = "[email protected]"
$emailTo = $EmailLogTo
$subject = "Terminated Users Cleaned in AD"
$content = Get-Content $LogFile2 | ForEach-Object {$_.Split("`r`n")}
$body = [string]::Join("`r`n",$content)
$smtpServer = "smtp.mydomain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
Get-ChildItem -Path C:\Scripts\CleanUpTermedUsers\* -Include *.log | where-object { $_.LastWriteTime -lt $((Get-date).Adddays(-7))} | clear-content C:\Scripts\CleanUpTermedUsers\TerminateUsersLogFile.log
Clear-Content c:\Scripts\CleanUpTermedUsers\UserNamesMovedtoDisabledOU.txt

Similar Messages

  • Using Mountain Lion (OS 10.8), in Contacts, how can I show a count of number of contacts total and/or number of contacts in a group?

    Using Mountain Lion (OS 10.8), in Contacts, how can I show a count of number of contacts total and/or number of contacts in a group?

    If you scroll the list to the bottom, there might be a count. I haven't figured out why you sometimes get a count and other times you don't.

  • How can i activate my ipad mini? every time the error message is not going there. and the version has expired.

    how can i activate my ipad mini? every time the error message is not going there. and the version has expired.

    Try this link for activation problems ...
    http://support.apple.com/kb/ts3424
    If you had iOS 7 BETA installed, just go to developer.apple.com and log in using your developer account.  There are discussions about this issue.  Otherwise...  for non-developers, I'm afraid you're on your on.  Use Google.

  • How can I creat a control button that will allow the vi to run?

    Instead of pressing the run button, I want to creat my own run button that will allow my vi to run.
    Any idea?
    Thank you

    First you need to set the VI to Run When Opened (VI Properties>Execution). Then you create a front panel Boolean. On the diagram what you need to do is have some sort of idle state where nothing is done until the Boolean is pressed. It could be a separate while loop that doesn't exit until the Boolean is pressed, an Event Structure, or as part of a state machine. Look at the shippings examples Queued Message Handler, New Event Handler, Using Buttons for Options to name just a few.

  • Last night, mail suddenly lost all my emails, which were stored in mailboxes.  What happened and how can I find my lost files?  I have the latest MacBookPro, running Lion 10.7.2 all software updates installed

    Last night the mail application from Apple lost all my old emails, which were stored in mailboxes, neatly sorted by category.  What happened and how do I find them? 
    Details:  I shut down mail to run errands outside my office.  My late model MacBook Pro was on "sleep".  When I returned, I opened the application, and (RATS!) all the mailboxes were missing.  They just evaporated. 
    Operating system:  10.7.2 - all software updates installed and current as of 24 hours ago (12-30-11, 6 AM EST). 
    ln the mail program, the trash folder is OK and the sent folder is OK. 
    Yesterday, I did no maintenance on my mail folders.
    HELP! 

    1 - the sudden disappearance of my 22 mailboxes, used to sort the emails that I need to file for future use
    That was most likely the result of some kind of corruption, as I've already said, not a bug in Mail.  Have you repaired the hard drive with Disk Utility recently?  That wouldn't be a bad idea.
    2 - at random times, mail (or the server) says that my password is incorrect and I must reenter (fix:  usually I can quit mail, restart, and the connection is restored without reentering my password)
    This is a known issue, where a failure to respond promptly on the server's end mimics what happens when the password is rejected.  There's no need to quit Mail, just cancel when asked to enter the password, take the account back online and try again.
    3 - mail seems to resort the mail in my mailboxes at random time.  Several times a day, I must reset the sort to (a) by date; (b) by desending
    Never seen that before.  That points more to some kind of possible corruption in your Mail data or preference files.

  • How can i avoid Errors by folders with spaces in the script

    Hello!
    I have written (or better to say gathered) a script which should fix a problem in a network. Let me explain first what it should do.
    Let's say we have a folder named Test with a lot of subfolders, one for each user of the network, which also contain many, many subfolders. The problem is that some user accidentally Drag and Drop subfolder into other subfolder. (E.g. D:\test\userA
    is now in D:\test\UserB\UserA). And the next time User A wants to open his folder: It's gone. I really hope you can follow me because i am a little confused by myself right now. :)
     And here is the thing, a VB Script with Icacls that change the User-Authorization in the first Level of Subfolders, so that they can't Drag and Drop anymore, though they have Full access to the content of the folder. So far my script works as far as
    there a no spaces in the Foldername.
    D:\test\UserA works.
    D:\test\User A doesn't.
    Here is my Script so far (i am german, so pls don't bother on the german names):
    Dim objFSO, strLogFile, objLogFile
    Const ForWriting = 2
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    strLogFile = "D:\dir_log.txt" 'Log File to show what was changes
    If objFSO.FileExists(strLogFile) Then
       set objLogFile = objFSO.OpenTextFile(strLogFile, ForWriting, true)
    Else
       objFSO.CreateTextFile(strLogFile)
       set objLogFile = objFSO.OpenTextFile(strLogFile, ForWriting, true)
    End If
    read_two_subfolders "D:\test",objLogFile, 0 '
    objLogFile.close
    function read_two_subfolders(strFolderPath, objLogFile, intCounter)
    On error Resume Next
    Dim objUnterordner, objFolder
    if intCounter < 1 then 'Number of Subfolderlevel which should be changed
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder(strFolderPath)
    For each objUnterordner In objFolder.SubFolders
      objLogFile.WriteLine objunterordner.path
      read_two_subfolders objunterordner.path ,objLogFile, intCounter + 1
     Dim strFolder, strUser, strDomain
    strFolder = objunterordner.path
    strUser = "Testuser" 'User or Group
    strDomain = "Testdomain" 'Domain (should be left empty at local domains)
    SetPermissions    
    SetPermissions()   
     Dim intRunError, objShell, objFSOO    
     Set objShell = CreateObject("Wscript.Shell")   
     Set objFSOO = CreateObject("Scripting.FileSystemObject")  
     If objFSOO.FolderExists(strFolder) Then       
      intRunError = objShell.Run("icacls " & strFolder & " /inheritance:r /grant:r " & strDomain &"\" & strUser & ":RX ", 2, True)                
      If intRunError <> 0 Then           
       Wscript.Echo "Error assigning permissions for user" & strUser & " to folder" & strFolder       
      End If   
     Else       
      Wscript.Echo "error: folder" & strFolder & " does not exist."   
     End If
    Next
    End if
    End Function

    Hi LW,
    while I don't always see eye-to-eye with JRV, I really have to agree with him on this: Trying to make this work would probably be an act of futility. I highly recommend trying to learn powershell and do it there. Here are some links to commands that will
    get you started on your problem:
    Get-Help
    Get-Member
    Get-ChildItem
    Get-Acl
    New-AccessRule
    Set-Acl
    For producing something to order, you're best recourse is indeed a consultant however. I'd say this is more of a fish problem: Give a man to fish or teach him how to fish, so I highly recommend learning the skills for yourself. Your own skills will never
    abandon you.
    Cheers and good luck,
    Fred
    There's no place like 127.0.0.1

  • How can I do to acquire and save date in the same time and in the same file when I run continual my VI without interrupti​on.

    I've attached a VI that I am using to acquire amplitude from Spectrum analyzerse. I tried to connect amplitude ouput to the VI Write Characters To File.vi and Write to Spreadsheet File.vi. Unfortunately when I run continual this VI without interruption, labview ask me many time to enter a new file name to save a new value.
    So, How can I do to aquire and save date in the same time and in the same file when I run continual my VI for example during 10 min.
    Thank you in advance.
    Regards,
    Attachments:
    HP8563E_Query_Amplitude.vi ‏37 KB

    Hi,
    Your VI does work perfectly. Unfortunately this not what I want to do. I've made error in my last comment. I am so sorry for this.
    So I explain to you again what I want to do exactly. I want to acquire amplitude along road by my vehicle. I want to use wheel signal coming from vehicle to measure distance along road. Then I acquire 1 amplitude each 60 inches from spectrum analyzer.
    I acquire from PC parallel port a coded wheel signal coming from vehicle (each period of the signal corresponds to 12 Inches). Figure attached shows the numeric signal coming from vehicle, and the corresponding values “120” and “88” that I can read from In Port vi.
    So I want to acquire 1 time amplitude from spectrum analyser each 5
    period of the signal that I am acquiring from parallel port.
    So fist I have to find how can I count the number of period from reading the values “120” and “88” that I am acquiring from In Port (I don’t know the way to count a number of period from reading values “120” and “88”).
    Here is a new algorithm.
    1) i=0 (counter: number of period)
    2) I read value from In Port
    3) If I acquire a period
    i= i+1 (another period)
    4) If i is multiple of 5 (If I read 5 period)
    acquire 1 time amplitude and write to the same
    file this amplitude and the corresponding distance
    Distance = 12*i). Remember each period of signal
    Corresponds to 12 Inches).i has to take these
    values: 5,10,15,20,25,35,40,45,50,55,60............
    5) Back to 2 if not stop.
    Thank you very much for helping me.
    Regards,
    Attachments:
    Acquire_Amplitude_00.vi ‏59 KB
    Figure_Algorithm.doc ‏26 KB

  • Adding a counter that keeps track of the total number of times a loop has run, even if LabVIEW has been restarted.

    Hi all,
    I am writing a VI for measuring data and inserting it into a database. The measurements are controlled by a loop that runs once every minute. I want to give each measurement a unique id number and store this too in the database.
    To do this, I want to add a counter to this loop so that I can count the number of times the loop has executed in total. This is, even if the VI, LabVIEW or even th PC is restarted, I want the counter to keep track of the number of executions. If say, the loope executes two times and then the VI is stopped and restarted, I want the following number on the counter to be three.
    Does anyone have an idea about how to do this? I am gratefule for any help!
    Clara
    Message Edited by Clara G on 05-11-2010 08:21 AM
    Solved!
    Go to Solution.

    Not allowed to give away code but I can describe one of my "Totalizers" used to keep track of how much stuff has passed through a fliter so we know when to change it.
    THe Total izer is implemented as an Action Engine.
    It has three actions (methods)
    1) Init - Opens an ini file and reads the last values read and cahces these in shift registers. It also inits a timer so we now how long since the last file I/O.
    2) Update - Uses the data passed by the caller to update the totals. It also checks how long since the last save and if more than one minute it writes to the ini file (forced write).
    3) Read - returns the totals for display and evealuating if a an alarm should be triggered to change the filter.
    Note:
    THe pre-LV 8.6 version of the ini file exposed methods to allow writing to the file. The new ini functions do not expose that functionality and require closing the file.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • I need to install photoshop cs4 extended from a disk to a new computer because my old computer had a hard drive crash. There is no serial number on the back of the case.  How can I obtain a usable serial number?

    I have to install Photoshop CS4 extended on a new computer from a disk because my old computer had a hard drive crash.  There is no serial number on the back of the case.  How can I obtain a usable serial number?

    Find your serial number quickly
    You can activate software without following up and registering it... at least that was the case in the past.  The serial number is normally located on the disc case or a box inside the main box.  If you did not purchase the disc from Adobe then it is possible you would have dealt with a redemption code, in which case it would have been up to you to keep a record of the serial number, especially if you did not follow up and register the software.

  • I have a large number of photos imported into iPhoto with the dates wrong.  How can I adjust multiple photos (with varying dates) to the same, correct, date?

    I have a large number of photos imported into iPhoto with the dates wrong.  How can I adjust multiple photos (with varying dates) to the same, correct, date?

    If I understand you correctly, when you enter a date in the Adjust Date and Time window, the picture does not update with the date you enter.  If that is the case then something is wrong with iPhoto or your perhaps your library.
    How large a date change are you putting in?  iPhoto currently has an issue with date changes beyond about 60 years at a time.  If the difference between the current date on the image and the date you are entering is beyond that range that may explain why this is not working.
    If that is not the case:
    Remove the following to the trash and restart the computer and try again:
    Home > Library > Caches > com.apple.iphoto
    Home > Library > Preferences > com.apple.iPhoto (There may be more than one. Remove them all.)
    ---NOTE: to get to the "home > library" hold down option on the keyboard and click on "Go" > "Library" while in the Finder.
    Let me know the results.

  • HT3529 How can I remove my old phone number from my APPLE ID.

    How can I stop my old phone number recieve my iMessage of my apple ID.

    Turn off imessage in settings/messages, turn off Facetime in settings/facetime, delete the cloud account in settings/icloud and log out of your Apple ID in settings/itunes and app store.
    Delete the phone from your profile in https://supportprofile.apple.com if you registered your phone there

  • TS3367 How can I change my facetime phone number on my ipad? my apple id number is correct, but it is still showing up wrong in facetime.

    How can I change my facetime phone number on my ipad? my apple id number is correct, but it is still showing up wrong in facetime.

    Using FaceTime http://support.apple.com/kb/ht4319
    Troubleshooting FaceTime http://support.apple.com/kb/TS3367
    The Complete Guide to FaceTime + iMessage: Setup, Use, and Troubleshooting
    http://tinyurl.com/a7odey8
    Troubleshooting FaceTime and iMessage activation
    http://support.apple.com/kb/TS4268
    Using FaceTime and iMessage behind a firewall
    http://support.apple.com/kb/HT4245
    iOS: About Messages
    http://support.apple.com/kb/HT3529
    Set up iMessage
    http://www.apple.com/ca/ios/messages/
    Troubleshooting Messages
    http://support.apple.com/kb/TS2755
    Setting Up Multiple iOS Devices for iMessage and Facetime
    http://macmost.com/setting-up-multiple-ios-devices-for-messages-and-facetime.htm l
    FaceTime and iMessage not accepting Apple ID password
    http://www.ilounge.com/index.php/articles/comments/facetime-and-imessage-not-acc epting-apple-id-password/
    Unable to use FaceTime and iMessage with my apple ID
    https://discussions.apple.com/thread/4649373?tstart=90
    For non-Apple devices, check out the TextFree app https://itunes.apple.com/us/app/text-free-textfree-sms-real/id399355755?mt=8
     Cheers, Tom

  • How can i add a new viewer to 9iAS and push client to run it ?

    Dear All,
    I hosted a page on Oracle9iAS which has links to documents of different types of desktop applications, for example: MS word, Excel, AutoCad ......
    And i've a mutiformat viewer which i need to install it on Oracle9iAS to be run when a client tries to access any of the listed documents. So, how can i install this viewer to Oracle 9iAS and push client to run it ?

    Si vous avez utilisé la commande Save As Template depuis Pages, il y a forcément un dossier
    iWork > Pages
    contenant Templates > My Templates
    comme il y a un dossier
    iWork > Numbers
    contenant Templates > My Templates
    Depuis le Finder, tapez cmd + f
    puis configurez la recherche comme sur cette recopie d'écran.
    puis lancez la recherche.
    Ainsi, vous allez trouver vos modèles personnalisés dans leur dossier.
    Chez moi, il y en a une kyrielle en dehors des dossiers standards parce que je renomme wxcvb.template quasiment tous mes documents Pages et wxcvb.nmbtemplate à peu près tous mes documents Numbers.
    Ainsi, quand je travaille sur un document, je ne suis pas ralenti par Autosave.
    Désolé mais je ne répondrai plus avant demain.
    Pour moi il est temps de dormir.
    Yvan KOENIG (VALLAURIS, France)  mercredi 23 janvier 2011 22:39:28
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.2
    My iDisk is : <http://public.me.com/koenigyvan>
    Please : Search for questions similar to your own before submitting them to the community

  • How can I make Use of PS and Ai (offer) in spite of running Windows Vista ?

    How can I make Use of PS and Ai (offer) in spite of running Windows Vista ?

    Once you have signed up, you could - in theory - choose "other version" under the icon on the CC website and install CS6, but I'm not sure if that works for this special offer or only for "full" CC. Anyway, it seems simple enough to upgrade to Win 7 or Win 8 and perhaps you were planning on starting fresh, anyway...
    Mylenium

  • How can i add more a phone number in phone 4s

    Hi i'm new for IOS, i have got iphone 4s in my hand. i try to synchronize my contact list to iphone, it's work. but i would like to know how can i add more a phone number into a person in the list. default as show 1.mobile and 2.iphone
    Thanks

    If you have completed the info for a contact there will be additional spaces for more phone numbers. If you have not added a number yet, simply tap the word to the left of the blank phone number space to change the category.
    Stedman

Maybe you are looking for