Powershell: Script to Easily Find Objects in the SCCM Console

2017-07-27T00:01:04+00:00 January 9th, 2013|Uncategorized|

Recently, I had a need to delete an SCCM advertisement in the SCCM 2007 R2 console, in order to ensure it didn’t run on any of my test machines.  Now, I knew that it wouldn’t run, because it was not being advertised to any collections of which my test machine was a member.  But the advertisement was only a test, and I was trying to clean up after myself.

According to Microsoft (link: http://technet.microsoft.com/en-us/library/bb693527.aspx), the way to delete an advertisement from the SCCM console is to drill down through the console (System Center Configuration Manager / Site Database / Computer Management / Software Distribution / Advertisements) and right-click -> Delete the advertisement.  Normally, this is a pretty straightforward procedure…  IF you know where your advertisement is located.

You see, the SCCM console in which I was working divided the advertisements into sub folders based on the Publishers name, and I could not find a folder for the Advertisement I was trying to delete.

 Consol.Advertisements

 

Furthermore, subdividing the Advertisements as such also rendered the “Look For” search field in the console pretty useless; I would have to “Look For” my advertisement in every folder!

SCCM reports can be pretty helpful, and I was able to run a report that gave me just about every piece of data about the advertisement I wanted to delete – except the path to it; the information critical for deleting the advertisement.

A quick Google search led me to this link: http://blog.tyang.org/2011/05/20/powershell-script-to-locate-sccm-objects-in-sccm-console/.  Here, I found the Powershell script that helped me find my elusive advertisement.

The only inputs for this powerful and very useful script are the name of your SCCM site server, and the SCCM object ID, which can easily be found through the “All Advertisements” report in SCCM.  As it turns out, the folder that contained my advertisement had been accidentally moved under another folder. 

It’s great when you find the perfect tool for the job, as I did in this case.  I hope you find it as useful as I did. I intend to keep this one around for future use. 

Thanks, Tao!

 

Powershell: Get-ADUser Without Errors…

2017-07-27T00:01:04+00:00 January 2nd, 2013|Uncategorized|

I do a lot of scripting of mass-user searches, server and Home Folder validations, etc., where I rely on the Powershell command “Get-ADUser” in my loops.  And this is one of those cases where Powershell is very forgiving; and as such, things like this can be done a handful of different ways.  Of course, some are better than others…

The shortest and easiest form of the command is often fine enough to get the job done, but not always the best in certain situations.  For instance, if you have an IF loop where you are going through an expected list of users (perhaps from an input file) and trying to retrieve a certain attribute for each, you might be inclined to initially write the loop line something like this:

Get-ADUser -Identity $loopUserId

…and this is fairly standard, of course.  In the resulting loop, it would return something like the standard set of attributes in this capture (using a manual query in my lab for this example)

 However, if you are like me, you might occasionally want to watch the output of your scripts while they run; and you prefer to send nice results to screen (as well as to the output logs) for easy debugging and, well, entertainment. 

And this is where the problem arises with the simple format of the command; you soon become annoyed by all the red error messages for the users that have gone missing since your input file was created, as in the case of this intentional search for a non-existent user:

…this is because by default, the Get-ADUser command will give you a nice set of results when it succeeds, but an ugly red message when there is no result.  Yuck.  This simply won’t do; we don’t want to have to panic as if there were an actual *error* every time we get an empty result on each query in the loop!

Instead, we wish to just get a silent, non-return when there are no results.  So, another way to write the same command so that you don’t get any error messages is by using the -Filter option, like this:

Get-ADUser -Filter {SamAccountName -eq $loopUserId}

In this manual example, you can see that the results are the same as if using the earlier format of the command when successful:

…But this time, we get a nice, quiet, non-result in the event of an empty response; as in the case of the same failed search:

Much better!

Now, you can watch your loop output while having a nice… calm… lunch….

 

 

DFS Replication Validation Script…

2017-07-27T00:01:04+00:00 December 12th, 2012|Uncategorized|

The other day, while at the enterprise-level customer with whom I’m currently working, I ran into a situation where I needed to validate that certain parts of a DFS hierarchy were properly being replicated across the customer’s AD domain controllers.  As the administrators applied normal, routine DFS changes, the changes sometimes didn’t replicate properly across the enterprise — causing some segments of the DFS structure to not be visible or available. 

Apparently, the DFS problem was a result of using VMware guests as AD DCs.  I understand (from the customer) that a Microsoft hotfix is in the last stages of testing (at the time of this writing) and will be available for release “soon.”   It seemed that even though the DCs in question did not synchronize time with the ESX host upon which they reside, there is a default behavior in VMware Tools that assigns the host time value to the guest — at least up until the “do not sync” routine is processed during startup; after which the guest is then allowed to find its own time.  During this brief time window, the DFS Namespace service sometimes completes assembling its DFS target list and can find itself behind in time, relative to links it has been given by PDCE; which makes no sense to it, and it removes them from its listing.  And as a result, people can’t find their mapped drives or browse some of the DFS Tree.  (Note: I cannot take credit for this timing behavior investigation and results; and while I’d love to credit the folks who are due, I’m not permitted to.)  The customer remedied the situation with a temporary fix, but the real fix is the up-coming aforementioned patch.

Anyway, while the symptoms were being analyzed, I was working on other things and needed to work around the issue as much as possible while the solution was being chased.  So, I whipped up a simple little DOS script to go out and validate the top-levels of the DFS hierarchy across all domain controllers that carry them, in order to find out what would or wouldn’t be properly resolved.

For what it’s worth, I thought I’d pass the script along to you.  Here it is:

 

@SETLOCAL ENABLEDELAYEDEXPANSION
@set AdDomain=MyAdDomain.local
@set DirQuantity=17
@set DestPath=h:DcList.txt
@REM This requires elevated credentials, otherwise will fail...
@ipconfig /flushdns
@REM First we build the input file...
@nslookup %AdDomain% |findstr 
[0-9].*.[0-9].*|findstr /V /C:"Address: " > %DestPath% @ECHO As of 20121212, there should be %DirQuantity% DFS dirs on each server (actual, plus the "." and ".." items). @REM Now loop through the input file and check the DFS at the destination... @For /F "tokens=*" %%Q in (%DestPath%) Do @( @set MYDC=%%Q @set MYDC=!MYDC:Addresses: =! for /f "tokens=* delims=" %%A in ('dir /A:D \!MYDC!Corp ^|findstr /C:"Dir(s)"') do @set MYDIR=%%A for /f "tokens=* delims= " %%G in ("!MYDIR!") do @set MYDIR=%%G @REM Options A: Use this line if you wish to see all DFS sources: @ECHO For: !MYDC! !MYDIR:~0,9! @REM Option B: Use this line if you wish to see only those in violation @REM (note: there's a space and tab separator for spacing alignment): @REM @ECHO For: !MYDC! !MYDIR:~0,9! |findstr /V /C:"%DirQuantity% Dir(s)" )

What it does:

The script builds a domain controller list in a static, external file, then iterates through the list, attempting to quantify the available DFS path branches against a numeric count that you supply in another variable.  I provided two different “ends” to the script (one of them commented out), in order to give you a couple different ways to present the results.  Make sure to “set” the variables in the first few lines, to your locally-relevant information; especially the number of *expected* DFS hierarchies.

Of course, I wanted to write it to do more, but I pretty much ran up against the limits of what I *should* do in a DOS script.  I’ll make another version in PowerShell some day that iterates down the hierarchy and validates the entire structure, instead of just the top level… 

…Unless you beat me to it…  😉

There you go; enjoy!

🙂

 

 

Scripted Home Folder Management with PowerShell Pt. 6 – The Script!

2017-07-27T00:01:07+00:00 October 3rd, 2012|Uncategorized|

This is the last post in my series on scripting user and Home Folder management (see Part 1, Part 2, Part 3, and Part 4 and Part 5 for reference) — it was a lot of ground to cover, but we did it!  Thanks for hanging in there with me.  We’ve created the user and attributes, built the folder, set permissions, added the Home Folder attribute on the user object; all with PowerShell.  You don’t get much more real-world than that!

Now, as promised, it’s time to pull it all together into one example script.

Of course, now that we’re putting all the concepts from the previous posts together, we need to be smart and add a few smart/standard script things; like good use of variables, error checking, and so forth.  Specifically, the new things I’m introducing in this post are:

  • Use of variables  – To make the script portable and easily modifiable
  • Use of command line arguments – To accept the new user’s name as input arguments
  • Use of SubString – To generate a “UserName” (a.k.a. SamAccountName) from a first and last name
  • Check for pre-existing – To make sure we don’t attempt to create an already-existing user name

All of the items above are in the first section of the script below, and the remaining sections are where I pull in the concepts from the previous posts to get it all done.  I don’t want to go into great detail on these new items, but they are necessary to make the script flow correctly and be usable right away as-is.

So, here you go.  You can paste this right into a file (something like provisionNewUser.ps1), launch a PowerShell session, and run it with the new user’s First Name and Last Name on the command line (as explained early in the body of the script). 

And here’s my warning: Don’t ever do what people on the Internet tell you to do; if this script is scary to you, don’t run it.  In fact, only run this in a test lab, until you are comfortable with the specifics.  So there.

# Home Folder Provisioning Demo Script
# Jeremy Pavlov, Coretek Services, 20121003
#
# Execute in a powershell session, with the new user's First and Last names after the command, like this:
# .provisionNewUser.ps1 Jeremy Pavlov
# # Make sure you run this if not already loaded, for AD-based commands Import-Module ActiveDirectory # # Read in the first name and last name from command line inputs $FirstName = $args
[0] $FirstInitial = $FirstName.Substring(0,1) $LastName = $args[1] $LastInitial = $LastName.Substring(0,1) $UserName = "$FirstInitial$LastName" $MyDomain = "CoretekServices.local" $HomePrefix = "\$MyDomainCorpHomes" $DefaultUserOu = "ou=New Users,dc=CoretekServices,dc=local" # write "First name will be: $FirstName" write "Last name will be: $LastName" write "User name will be: $UserName" write "Home Folder will be: $HomePrefix$LastInitial$UserName" write "" # # See if the user exists $CheckUser = Get-ADUser -ldapFilter "(SamAccountName=$UserName)" # #If user exists, exit! if ($CheckUser -ne $Null) { write "User $UserName already exists! Exiting..." write "" exit } # write "Creating $UserName..." write "" New-ADUser -Path "$DefaultUserOu" -SamAccountName "$UserName" -Enabled $true -Name "$FirstName $LastName" -GivenName "$FirstName" -Surname "$LastName" -AccountPassword (ConvertTo-SecureString –AsPlaintext "ChangeMe123!" –Force) -ChangePasswordAtLogon $true # write "Create $HomePrefix$LastInitial$UserName ..." write "" New-Item -type directory -path $HomePrefix$LastInitial$UserName # write "Setting permissions on the $HomePrefix$LastInitial$UserName ..." write "" $acl = Get-Acl $HomePrefix$LastInitial$UserName $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$MyDomain$UserName", "DeleteSubdirectoriesAndFiles, Modify, Synchronize", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.AddAccessRule($rule) Set-Acl $HomePrefix$LastInitial$UserName $acl # write "Setting the Home Folder attribute for $UserName" write "" Set-ADUser -identity "$UserName" -homeDrive h: -homeDir "$HomePrefix$LastInitial$UserName" # write "...Complete!" write "" #

…and there you have it.  Now, of course, I could have dumped in a lot of other good practice stuff like input validations and things, or other additional neat features, but I’m only trying to demonstrate the core concepts here from our previous posts in this series.  I don’t want to over-whelm the example and make it difficult or — heaven forbid — boring (gasp!) to read.

But please, if you have a better way of doing it, make sure to drop a comment or two and help out others…

Now go create some users!

 

 

Scripted Home Folder Management with PowerShell Pt. 5

2017-07-27T00:01:07+00:00 September 26th, 2012|Uncategorized|

In my last post in this series on scripting user management (see Part 1, Part 2, Part 3, and Part 4 for reference), I left off with a couple different ways to set the Home Folder attribute, using DSMod or PowerShell.

But I thought it was important to spend a moment and stress that when you’re scripting these changes, it’s all about what you *have* available to use as the basis of your queries and changes.  What I mean is this:  If you only have the samAccountName (often called the User ID), you make the query/change one way; but if you have the CN (known as the User Name), then you do it another way.  Let me show you some examples…

DSMod

As shown in Part 4, if you have the CN — as DSMod requires — you can just make the call directly:

dsmod user "cn=Jeremy Pavlov,ou=Demo,dc=CoretekServices,dc=local" -hmdrv H: -hmdir "\MyCompany.orgDFSPathHomes$username$"

But what if you don’t know the CN, and all you have is the samAccountName?  Then in this case, you must use the samAccountName to first *get* the CN, then pipe the CN through to the DSMod command like this:

dsquery user -samid "JPavlov" | dsmod user -hmdrv H: -hmdir "\MyCompany.orgDFSPathHomes$username$"

In the above example, we’re using dsquery to simply retrieve the samAccountName, as represented by the samid flag; which returns a perfectly-formatted CN that is used as input for the DSMod.  The bottom line is that you can make the change no matter which format you have the User name!

PowerShell

On the PowerShell side of things, you have a similar flexibility.  The PowerShell example I used in Part 4 utilized the samAccountName (as represented by the -identity flag) instead of the CN, like this:

Set-ADUser -identity "jpavlov" -homeDrive h: -homeDir "\MyCompany.orgDFSPathHomesjpavlov"

But if you only have the CN to start with, then we have to go fishing.  We need to do a Get-ADUser with the -like option, and stuff it in a variable, prune that variable down to just what we want, and then pass it on to the Set-ADUser command.  Here’s one example how to get it done, like this:

$Dude = Get-ADUser -Filter 'Name -like "Jeremy Pavlov"'
$DudeSamId = $Dude.SamAccountName
Set-ADUser -identity $DudeSamId -homeDrive h: -homeDir "\MyCompany.orgDFSPathHomes$DudeSamId"

And with that, we’ll press pause, until next time…

Next time…  Let’s wrap this scripting up…  See you then!

Scripted Home Folder Management with PowerShell Pt. 4

2017-07-27T00:01:07+00:00 September 19th, 2012|Uncategorized|

If you’ve been following along in this post series (see Part 1, Part 2, and Part 3 of this series for reference), where I showed you how to create AD users, create soon-to-be Home Folders, and set permissions; all with PowerShell (and some other tools). 

Now, it’s time to stitch it all together by assigning the Home Folder attribute on our user object, and point the attribute to the folder we’ve prepared.  Yes, of course you could just set the Home folder “Connect To” options on the Profile tab of a User object in the Active Directory Users and Computers (ADUC) tool, but that’s not the point.  We want scripting!

So to pick up where we left off last time, all we really need to do is provide a Home folder attribute update on an existing user object.  Of course, we could have done this upon initial creation, but this series of posts is attempting to demonstrate the individual steps that you might encounter in the real world enterprise; either separately or together. 

There are various tools and ways to make our changes, including via the old method outlined in Part 1.  But I’d be remiss if I didn’t confess that much of the time I use good ol’ DSMod.  Here’s what a DSMod line would look like to update our user:

dsmod user "cn=Jeremy Pavlov,ou=Demo,dc=CoretekServices,dc=local" -hmdrv H: -hmdir "\MyCompany.orgDFSPathHomes$username$"

…note that I used “$” (dollar sign), which is a cool way to have the DSMod command utilize the “Windows 2000 User Name”, or the “samAccountName” as the value for this special variable.

*Aside: Why do I keep mentioning the DSMod / DSAdd methods?  I’ll tell you.  It’s because much of the time, I use scripting to parse certain inputs and then generate other scripts that I can hand out to other administrators (yes, script-generating scripts).  And while I can’t be certain that everyone will be familiar with script editing and the PowerShell modules for Active Directory, I can be pretty sure they’ll have a command prompt and DSMod.  There are other reasons, but the rest mostly come down to preference and how the result files look, etc.  So there you go.

However, the new Powershell method with the ActiveDirectory module is pretty nice and easy for this task, too.  Here is the PowerShell equivalent to the DSMod command above: 

set-aduser -identity "jpavlov" -homeDrive h: -homeDir "\MyCompany.orgDFSPathHomesjpavlov"

…or at least its close, although this time I used the “ID” instead of the “Name”.  I think this deserves some closer examination…  So next week, I’ll spend a some time covering alternative inputs/methods to the above, before we move on to troubleshooting and validation, and then sum the whole thing up.

Next time…  A couple more ways to to get it done…  See you then!

 

Updated 20120923:  command syntax fix

Scripted Home Folder Management with PowerShell Pt. 3

2017-07-27T00:01:07+00:00 September 12th, 2012|Uncategorized|

In this post, I’m following up on Part 1 and Part 2 of this series where I showed you how to create users (and set a few attributes) with PowerShell.  Now that you have your user created and configured, I’m going to show you a bit about Home Folder creation and permission assignment.  Remember that all of these basics are leading toward a single, simplified, scripted elements method of managing Home Folders in the Enterprise.

So let’s create a folder.  Of course, you know how to do that already, so I won’t belabor the point too much.  Picking up where we left off in the last post, you already have a PowerShell session going, with network access to the shares where the folders will be created.  And since PowerShell has native access to the filesystem via its own object paths, you can actually skip the fancy stuff and just do a good ol’ md:

md \serverShare$JPavlov

…or if you’re using a DFS structure, something like this…

md \MyCompany.orgDFSPathHomesJPavlov

I know, I know.  That’s not PowerShell.  So if you really want to use the benefit of PowerShell, you would use the New-Item command like this (sticking with our DFS structure from above):

New-Item -type directory -path \MyCompany.orgDFSPathHomesJPavlov

Okay, great.  At this point, we have a folder, but no permissions yet for the person who will use it.  In order to set the permissions, we’ll stick with PowerShell and…

1.) Build a variable with the existing permissions with the Get-Acl command:

$acl = Get-Acl \MyCompany.orgDFSPathHomesJPavlov

2.) Add-on the permission we want (your permissions may vary!):

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("CoretekServicesJPavlov", "DeleteSubdirectoriesAndFiles, Modify, Synchronize", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)

3.) And then stuff it all back on the folder with the Set-Acl command:

Set-Acl \MyCompany.orgDFSPathHomesJPavlov $acl

There you have it!  We’ve created the soon-to-be Home Folder for the user we created previously, and added permission we want.  So it’s out there if the user can browse around and find it…  But let’s help them out a little bit and deliver it as a mapped drive in the next post.

Next time…  Assigning this folder as the user’s Home Folder via the AD attribute.  See you then!

 

 

Scripted Home Folder Management with PowerShell Pt. 2

2017-07-27T00:01:07+00:00 September 5th, 2012|Uncategorized|

In this post, I’m following up on Part 1 of this series where I showed you how to create users (and set a few attributes) the basic way with Powershell.  Now, I’m going to show you an easier way to create users thanks to the new(ish) Powershell modules that came along in Windows Server 2008 R2.  In the up-coming parts of this series, we’ll continue on to Home Folder creation/management concepts and automation.  But for now, let’s get that user created…

To be honest with you, I have to admit that most of the time when I’m building a script loop and just need an easy output that looks nice, I’d just do the DSAdd tool like this:

dsadd user "cn=Jeremy Pavlov,ou=Demo,dc=CoretekServices,dc=local" -samId JPavlov -disabled no -fn Jeremy -ln Pavlov -pwd ChangeMe123! -mustchpwd yes

…but the future is here, and the future is PowerShell; and you and I have to get over it.  Powershell gives us better portability, variable management, etc., etc…  So onward and upward. 

And with recent versions of Windows 2008 R2, Microsoft provides the new “ActiveDirectory” module; making user creation/management activities as easy to do as the DSAdd/DSMod tools.  Here’s what I mean…

Open a Powershell session, and import the ActiveDirectory module like this:

Import-Module ActiveDirectory

Note: You need to have network access to an Active Directory server running AD Web Services for this module to work. 

Loading this module is the equivalent of launching the “Active Directory Module for Windows PowerShell” option on Windows 7 and Server 2008, but if you’re scripting you’ll want to make sure you load the module explicitly.  And, as a result, you have a ton of new AD tools available to you. 

You can get a good look at the majority of the new AD tools by using this command:

Get-Command *-AD*

Finally, using the New-ADUser command, we create that user with what is pretty much the equivalent of the DSAdd above (I used the same options to help clarify):

New-ADUser -Path "ou=Demo,dc=CoretekServices,dc=local" -SamAccountName "JPavlov" -Enabled $true -Name "Jeremy Pavlov" -GivenName "Jeremy" -Surname "Pavlov" -AccountPassword (ConvertTo-SecureString –AsPlaintext "ChangeMe123!" –Force) -ChangePasswordAtLogon $true

And that’s it!  You have a new user with your standard attributes set correctly.  I like this one-line method because it looks much cleaner when you are building import scripts that must be distributed to other folks, or when you want to insert some other command between each line (if you’re looping), etc.; it’s neat.

On a side note, there’s also a way to read in the contents of a formatted CSV, and pump it into the New-ADUser command; but my goal here is to show you concepts that ultimately can be combined into an multifaceted script.

Next time…  Home Folder creation and permission assignment.  See you then!

 

 

Scripted Home Folder Management with PowerShell Pt. 1

2017-07-27T00:01:07+00:00 August 29th, 2012|Uncategorized|

I’ve been doing tons of scripting for the project on which I’m working lately.  And I thought it’d be cool to spend a few posts in a row covering a few base elements of PowerShell-based user and Home Folder management, and build up toward a script for user and folder creation/deletion that you can easily use. 

I don’t intend to get fancy with this; in fact, I intend to make is simple as possible, and maybe kick around a few alternative methods to do the same tasks.  My goal is not to teach PowerShell, but to show you you can script these things easily.

So join me on the journey!  But let’s get there in small steps.  We’ll start at the start, with user creation.  Open a PowerShell session, and let’s get to it…

In order for this article series to work, I have to make some assumptions: I’ll assume you have the proper rights, a test environment, the proper PowerShell modules, and a Windows 7 or Server 2008 R2 computer.

For this first method in Part 1, we are going to show you how to do it with just native Powershell, using the ADSI provider, without any additional Powershell modules.  It’s like learning how to do the work on paper before you use a calculator…  😉

First, set up a variable that opens an LDAP connection to the server, using the ADSI provider (note, “LDAP” is case-sensitive) and specifying the OU where we’ll be creating our new User object:

$MyConnection = 
[ADSI]"LDAP://ou=Demo,dc=CoretekServices,dc=local"

Next, set up a variable that defines what you’re creating, along with a few critical attributes:

$MyObject = $MyConnection.create("User","cn=Jeremy Pavlov") 
$MyObject.Put("givenName","Jeremy")
$MyObject.Put("surname","Pavlov")
$MyObject.Put("samAccountName","JPavlov")

Finally, the command to make it happen:

$MyObject.SetInfo()

…and with that, the user is created in a “disabled” state.  So let’s fix that and set a password, using the same object and connection calls:

$MyObject.PsBase.Invoke("SetPassword","ChangeMe123!")
$MyObject.PsBase.InvokeSet("AccountDisabled","$false")
$MyObject.SetInfo()

But, as you may or may not expect, the act of setting the password in the previous step also clears the requirement for the user to change the password at first login… but we definitely want the user to do that.  So let’s set it back with one final step:

$MyObject.pwdLastSet = 0
$MyObject.SetInfo()

Okay, okay, I know what you’re saying, “…Man, that’s alot of work…”  And I’ll admit,this is the hard way.  So I’ll show you some easier ways in the next post.

(Updated 20120903; fixed syntax typos, split some content to next week’s post)

Next time…  A couple easier creation options…  See you then!

 

 

XP DOS Batch File Date Tip…

2017-07-27T00:01:07+00:00 August 15th, 2012|Uncategorized|

A little while back, I wrote this tip on DOS Batch File Date Tips for Windows 7 and Server 2008.  I was asked for a clarification for XP as well (due to the minor differences), so I’m writing this as an alternate version of the same previous post.

No matter what people think, DOS batch scripts are just as alive and needed as ever.  And for all the tasks we create on Windows servers, we still commonly need to gather application output, rotate logs, etc.

So when running a script that exports results to a log/results file, I always prefer to date my file names for easy tracking and history.  My preferred date arrangement for filenames is the date in reverse format: YYYYMMDD, or 20120809.  And since the DOS date command isn’t as friendly or flexible as the Linux/Unix date command (with which you may easily format the output in myriad ways), it’s best to do the next-best thing: use the date *variable*.

Most folks don’t even know that your Windows system is keeping a real-time variable for the date, but it certainly makes sense that it would be necessary.  Go ahead, pull up a command prompt and type: echo %date%

…and on a Windows XP workstation, you’ll get a result like this: 08/09/2012

So what we need to do now is to utilize string manipulation, grab the date elements we want, and flip the order around to get the arrangement we need:
set todaysdate=%date:~6,4%%date:~0,2%%date:~3,2%

The structure above is this: There are 3 sections, all of which use the date variable.  The first section moves in 6 characters, and grabs 4 for the year.  The second starts at 0 (zero, the beginning) characters and grabs 2 (for the month), and the third moves in 3 and grabs 2 (for the day).  As a result, we have reverse-date!

Then we can set a variable to use the combined date variable in the filename like this:

set exportfile=C:tempexportmyexport-%todaysdate%.txt

…now just call the %exportfile% in your batch file when you redirect your output, and viola!!  Here’s what it looks like when you echo %exportfile%:

C:tempexportmyexport-20120809.txt

Enjoy…

😎

 

 

Load More Posts