Friday, February 26, 2010

Hiding the Executioner Follow Up

I noticed that one of my kids' PCs was on in the morning.  It's usually at a WoW login screen so I decided to double check my shutdown settings.  I found a missing "/f" to force the shutdown.  All corrected.  It also occurred to me that Windows 7 didn't have the keys I told you to modify.  For Windows 7 you simply create the appropriate keys and DWORD entries and it will hide your account.  Here's a sample registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ Winlogon \ SpecialAccounts \ UserList]
"executioner"=dword:00000000
 


Just make sure you change "executioner" to the username you selected to run your jobs.  Also, a space was inserted between each \ for readability.  Do a CTRL-H in notepad and replace " \ " with "\".

Wednesday, February 17, 2010

Hiding The Executioner (job.user)

It's a flurry of posts today.  Once you created the user to run your jobs you may have noticed you now get a Welcome Screen in XP (or maybe you already did), but Executioner shows up in the list.  There is a way to hide him/her ...

You need to modify the registry.  Run regedit and navigate to the following Key:

HKEY_LOCAL_MACHINE \ Software \ Microsoft \ Windows NT \ CurrentVersion \ Winlogon \ SpecialAccounts \ UserList

Under this key you simply create a new DWORD value – the name matches the users name exactly, and the value is one of the following (Decimal format)

0 – Hides the user just from the welcome screen
1 – The user is shown

 Now when you reboot things will be back to normal.  This is also a good way to use a regular privs user account but give yourself the CTRL-ALT-DEL hidden option of entering a Bill Admin username and password if required.

What's Greener Than S3? Shutdown.

I have a friend that started a Facebook group called, "Green is just a color."  This isn't a political blog so I won't venture into Al Gore's Inconvenient Truth here, but I will tell you that in the coldest Winter Cincinnati has suffered in a very long time, my combined gas & electric bill last month was only $95.  My motivation was green as in dollars.  I'm not so concerned about the Alaskan caribou and if you're a tree-huggin' Darwinist then you can appreciate that the caribou had as much a chance at evolving opposable thumbs as we did and they might well be drilling for oil in our grazing lands.  :)  That's a joke.  Settle down Cameron Diaz.

Many years ago I got divorced.  Now, what I'm about to tell you is not my ex's fault, but I have taken control of the things around me.  With regards to PCs, electricity consumption and this blog: I have unplugged my toaster, coffee maker, unused radios and I even turn off the surge protectors for unused equipment when I walk past them.

How does that relate to my PC?  It is a fact that PCs consume far less power today than they used to when in their low-power modes.  But what about the no-power modes?  Once upon a time it was deemed a far greater risk to turn a PC off every day than it was worth in the electricity to keep it on.  I guess with the amount of electricity they use in a mostly powered off mode that argument is still kind of valid.  I, however, enjoy the complete silence a room experiences only when everything is turned off.  We all know you can't rely on your kids to turn things off when they're done and as I've previously noted with my To Do list we're all very busy.  Who wants to remember to turn off the PC at night?  The PC wants to remember!  (If you tell it to.)

I have a scheduled shutdown of my PC that runs every day!  It's not just a brute force, turn everything off by God!  I've only been blogging for 17 days, but I think you can gather from my previous posts that I look for the graceful solutions when possible.

Schedule a shutdown in the same way you schedule your reboot before, but schedule this one to run nightly at 9:00 PM.  Your command will look a little different:

c:\windows\system32\shutdown.exe /s /t 60 /f

The /s tells the system to shutdown (not reboot.)  The /t 60 gives the user 60 seconds to override the command, but that's just a fail safe.  You'll see why.  The /f forces the shutdown.

The fail safe is just that, a fail safe.  When you create the nightly schedule for your task you need to set some advanced options.  We're going to start the job at 9:00 PM, but we're only going to let it execute after 60 minutes of inactivity!  That means the earliest the system would shutdown would be 10:00 PM.  In the advanced properties you also tell it to retry for 8 hours.  That's more than enough time to cover the weekend nights when the kids are up late playing World of Warcraft and by scheduling it daily I don't have to make exceptions for President's Day ;)  Unless the kids pull an all-nighter and make it to 5:00 AM I will wake up to a completely powered down, quiet house.

Special Consideration:  If you do this there are other jobs on your PC that may need adjusting.  Windows Update is scheduled to run at 3:00 AM.  You need to move that to 9:00 PM.  No worries though as "inactivity" means human activity (interactivity).  Windows Update can run and finish before 10 and your PC can still shutdown.

Automating Maintenance

Now that we have our job user, what else can we do?  How many times do you hear, "Hey, my PC is running really slow.  Can you look at it?"  We all run through the simple things first, right?  So, you run defrag just to see how bad it is.  Upon realizing defrag hasn't been run since the day the machine was purchased you decide it's also prudent to do a chkdsk.  For the life of me I can't understand why these things aren't configured to run automatically.  I guess I should credit Windows 7 because it is scheduled to run every Wednesday at 1:00 AM on my laptop and I had nothing to do with it.  That said, my laptop is never on at 1:00 AM Wednesday ;)

Most of the PCs I support are still running Windows XP.  Try as I may people just don't have the money to upgrade.  So, as I get these requests for repair I always drop a couple of maintenance jobs on them.

Drag & drop defrag.exe on to the Task Scheduler and change the user to my job user a.k.a. Executioner.  In reality it's named something much more bland: job.user.  For real.  I set the schedule to run on Tue, Thr, Sat & Sun at 7:00 PM.  More on that in a moment.  You'll have to modify the command to include C: and -f (C-drive and force the defrag.)

c:\windows\system32\defrag.exe C: /f

I also schedule chkntfs.exe in the same way.  I only do this weekly on Sat & Sun at 11:00 AM.  chkntfs needs the parameters C: and /C to tell it which drive and to scan upon reboot.  That is quickly followed by a scheduled reboot (shutdown.exe) at 11:05 AM on the same days.  Shutdown needs /r /t 0 /f (reboot, wait 0 seconds and force).

c:\windows\system32\chkntfs.exe C: /C

c:\windows\system32\shutdown.exe /r /t 0 /f

I typically use Sat & Sun in my schedules because the systems can be off through the week depending on kids' functions, happy hour, etc. :P

Why early evening and weekend mornings?  In my next blog post, "What's Greener Than S3?" you'll find out.  Until then suffice it to say it's a good choice.  Of course, that's what I use for my PCs.  You can still use middle of the night times for family, friends and neighbors.

Tip: I have even scheduled the defrags of our servers disks in the middle of the night.  Servers need luvin' too ...


Tuesday, February 16, 2010

Who can run what, when?!

I am a big fan of encapsulation.  I like it in OO code and I like it in my operating system and applications where I can implement it.  What do I mean?  I mean I always run SQL Server and Agent under a user account rather than the 'Local Administrator' account.  I do this for IIS' application pools and I do it for scheduled jobs on the system.  Previously I posted a cleanup script and talked about how it was scheduled to run every Monday morning.  I pretty much left it at that, but it recently occurred to me that there was some struggle around making that happen without having administrative privileges on the server.

In our domain, or locally on a machine (as required), I create a standard non-privileged user account to run scheduled jobs under.  For the sake of this post we'll call that user "executioner."  Go create your executioner account now and open Scheduled Tasks.

If you created your own .vbs file to do cleanup work as I did you'll quickly learn that it works as described.  But who wants to run that script when they login every Monday morning?  Or what if it needs to run at 1:00 AM every night?  I don't know about you, but I want to be snugly in bed at 1:00 AM.  You can create the stub of a scheduled job simply by dragging your .vbs file onto the schedule tasks window.



Double click your newly scheduled task in the Scheduled Tasks window.  Change the username field from to "[{machine name}|{domain name}]\{account name}.  You did use Executioner, right?! ;)  If I created a local account mine would read:

nofear\Executioner

And if I created a domain account it would read:

kulai.local\Executioner

Change your schedule and click "OK."  You'll be prompted to enter "Executioner's" password.

All set?  Right click on your job and choose "Run."  It should fail.  :(  I guess that's no so bad.  It's what we want actually.

If you examine the filesystem  using filemon.exe from http://live.sysinternals.com you'll notice that Executioner is failing when trying to open cmd.exe.

Grant Read & Execute permissions to Executioner and try again.  Viola!  Now you have a mostly-non-privileged user account to run your local jobs.

Tuesday, February 9, 2010

Redlight - Greenlight

There were a couple of tweaks that were missing from yesterday's post.  One of the things I've worked hard to do in my work environment is create visual queues throughout our servers that should raise red flags about the role of the machine you're currently working on plays.

One of the ways is to put a background image on every desktop, including the RDP login screens that identify the common name for the server color coded to it's role in Development (green), Test (yellow) or Production (red).


Props to FlamingText.com for their service.  It's there that I make all my images.  HERE is a link to their site with the fields pre-populated to create a yellow on black image with the white drop shadow.  Just change the text and submit your image for creation (http://goo.gl/mKqE).

In addition to that I color the command prompt text to match with the following .reg file:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"DefaultColor"=dword:0000000c
# 0c = Red = Production
# 0e = Yellow = Test
# 0a = Green = Dev
# 0b = Blue = DRP


You probably also noticed that each machine "common name" is descriptive.  If you work like I do you have at least 2 monitors full of stuff, multiple RDP sessions open and a stream of people meandering by your desk.  So, when I switch back to a RDP window that I opened hours ago, the desktop is covered and I open a command prompt with RED text I am reminded that I am on a Production server.  Time to slow down and double check what I'm doing.

Speaking of common names: make things easier for your users.  Who wants to remember LAX-VSI-X-WEB1 or LAX-VSI-X-DB2K8 (Los Angeles, Virtual Server Instance, DRP, Web1 or DB2k8) when DRPWEB or DRPDB can get you there?  Use CNAMES in your DNS servers to keep it as simple as possible.

Monday, February 8, 2010

Quick Registry Tweaks

I'm sure, if you're reading this blog you're probably the resident IT geek around your friends and family.  That means you've probably done your fair share of system rebuilds for one reason or another.  I had my very own mother "punch the monkey" not long ago and spent a fair amount of time cleaning her system until she noted, "you could just erase everything.  There's nothing on there I need."  *sigh*  Well, that repair could have taken me 1 hour instead of 4 hours + 1 hour ;)  C'est la vie.

One of the things I hate about system builds is getting all the settings back the way I like them.  That started a quest for me a few years ago to compile all those tweaks into 1 registry file that I can apply to any system and have all my preferences set the way I like them.  Since I build all the systems for my immediate friends and family I'll just assume they like them too because they've never known anything different!

Here are the things that the registry file does:

  1. Adds an "Open with Notepad" option to the explorer context menu
  2. Adds a "CMD Prompt from HERE" option to the explorer context menu
  3. Adds "Copy To" and "Move To" options to the explorer context menu
  4. Turns OFF XP's search assistant making it operate like Windows 9x/2k
  5. It increases the maximum number of IE connections to 8.  Default is 2 or 3.
  6. It unhides all hidden, system, very hidden files and shows all file extensions
  7. It shows the full path in the window title and address bars
  8. Turns on the "Status Bar" in explorer
  9. It removes all the Windows XP visual affects (making the system faster)
  10. Turns on Tree View by default in Explorer
  11. Turns off the unused Desktop Icon notification
This is offered WITHOUT WARRANTY.  I have used it on every PC that I own.  I have used it on every PC at work.  It has worked perfectly for me.  Your mileage might vary.

Windows Registry Editor Version 5.00
# General Security Tweak(s)
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentcontrolSet\Control\Lsa]
"RestrictAnonymous"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentcontrolSet\Control\SecurePipeServers\win reg]

[HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers]

# Add Copy To and Move To to the Explorer Context Menu
[HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\Copy To]
@="{C2FBB630-2971-11D1-A18C-00C04FD75D13}"

[HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\Move To]
@="{C2FBB631-2971-11D1-A18C-00C04FD75D13}"

# Open Explorer in Folder List View
[HKEY_CLASSES_ROOT\Folder]
"EditFlags"=dword:000003d2
"BrowserFlags"=dword:00000008

[HKEY_CLASSES_ROOT\Folder\shell]
@="explore"

# Add Open with Notepad to the Explorer Context Menu
[HKEY_CLASSES_ROOT\*\shell]

[HKEY_CLASSES_ROOT\*\shell\opennotepad]
@="Open with Notepad"

[HKEY_CLASSES_ROOT\*\shell\opennotepad\command]
@="C:\\WINDOWS\\system32\\NOTEPAD.EXE %1"

# Increase IE connections to 8
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
"MaxConnectionsPerServer"=dword:00000008

# Show the Status Bar
[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main]
"StatusBarOther"=dword:00000001

# Show Hidden, Very Hidden & Protected Operating System Files
# Show File Extensions
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
"Hidden"=dword:00000001
"HideFileExt"=dword:00000000
"SuperHidden"=dword:00000000
"DisableThumbnailCache"=dword:00000001
"ShowSuperHidden"=dword:00000001
"WebViewBarricade"=dword:00000001

# Show the full path in the address and title bar
# Turn of Clippy the Search Assistant
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\CabinetState]
"Settings"=hex:0c,00,02,00,1b,01,e7,77,60,00,00,00
"FullPath"=dword:00000001
"FullPathAddress"=dword:00000001
"Use Search Asst"="no"

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\CabinetState]
"Use Search Asst"="no"

# Turn off the unused icons on your desktop notification
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\CleanupWiz]
"NoRun"=dword:00000001

# Add CMD prompt from here to the Explorer context men

# Not friendly with Windows 7 -- will replace with update
# do not uncomment the following 2 key insertions
#[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\Command Prompt]
@="CMD prompt from here"

#[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\Command Prompt\command]
@="Cmd.exe /k pushd %L"

# Enable Quick Edit in CMD windows
[HKEY_CURRENT_USER\Console]
"QuickEdit"=dword:00000001

[HKEY_USERS\.DEFAULT\Console]
"QuickEdit"=dword:00000001

# Turn off visual effects to improve performance
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects]
"VisualFXSetting"=dword:00000002

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\AnimateMinMax]
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\ComboBoxAnimation]
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\CursorShadow]
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\DragFullWindows]
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\DropShadow]
"DefaultValue"=dword:00000001
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\FontSmoothing]
"DefaultValue"=dword:00000001
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\ListBoxSmoothScrolling]
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\ListviewAlphaSelect]
"DefaultValue"=dword:00000001
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\ListviewShadow]
"DefaultValue"=dword:00000001
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\ListviewWatermark]
"DefaultValue"=dword:00000001
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\MenuAnimation]
"DefaultValue"=dword:00000001
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\SelectionFade]
"DefaultValue"=dword:00000001
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\TaskbarAnimations]
"DefaultValue"=dword:00000001
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\Themes]

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\TooltipAnimation]
"DefaultValue"=dword:00000001
"DefaultApplied"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects\WebView]
"DefaultApplied"=dword:00000001



Cut and paste the code above into a file with a .REG extension.  Then you can double-click the file to apply the changes.

Saturday, February 6, 2010

SUBST, Java and Beer ...

I've recently picked up the coding bug again.  I had started going through some C# material and then my girlfriend bought me an Android based phone for Christmas.  Android development is done in Java.  Here was my first experience and a crafty DOS trick that solved my problem.

The "Head First Java" book discourages the use of an IDE while you're learning Java.  The thought is learn the language then learn the tool.  I'm on board so I fired up Notepad++ and entered my code (see below).  I have a shared Dropbox folder setup for Android development.  Nice way to get full versioning and I have it shared with a group of developers for collaboration/help if required.

The book claims their BeerSong.java code will compile and run.  Taking nothing for granted I typed the code in and tried to compile it.  It compiled.  Well, it compiled after I changed "While" to "while."  I've been using M$ stuff too long ;)

Now I had a BeerSong.class file, but it would not run.  My first error was this:

Exception in thread "main" java.lang.NoClassDefFoundError: BeerSong

There were 2 issues.  I made the rookie mistake of trying to execute the code with:

java BeerSong.class

As any old Java salt will be glad to point out, "You don't execute the .class file.  You execute the BeerSong bytecode and it will find the .class file!"  At least it's a common mistake ;)

Mine still did not run.  *sigh*  Turns out I needed a CLASSPATH statement in my environment variables to tell Java where to find my .class files.

That's easy enough, but this is ugly:

set CLASSPATH=C:\Users\bill.mote\Documents\My Dropbox\_AYDABTU.Development\PROJECT.target\BILL\HeadFirstJava\Chapter1

Enter our old friend SUBST.  If you're an old timer you probably remember using that command back in the early 90's to point 1 drive to another.  You can also point a directory to a drive letter!  Try this:

subst b:\ "C:\Users\bill.mote\Documents\My Dropbox\_AYDABTU.Development\PROJECT.target\BILL\HeadFirstJava\Chapter1"

Now you have a drive letter, B, mapped to your path.  Set your CLASSPATH ...

set CLASSPATH=b:\

Now try to run java BeerSong.  Worky!

Just for fun, here's the BeerSong code:

public class BeerSong {
    public static void main (String[] args) {
        int beerNum = 99;
        String word = "bottles";
       
        while (beerNum > 0) {
       
            if (beerNum == 1) {
                word = "bottle"; // singular, as in ONE bottle.
            }
           
            System.out.println(beerNum + " " + word + " of beer on the wall");
            System.out.println(beerNum + " " + word + " of beer.");
            System.out.println("Take one down.");
            System.out.println("Pass it around.");
           
            beerNum = beerNum -1;
           
            if (beerNum > 0) {
                System.out.println(beerNum + " " + word + " of beer on the wall\n");
            } else {
                System.out.println("No more bottles of beer on the wall");
            }
        }
    }
}

 
And, the output.  Notice the grammar problem in the output? :)

Friday, February 5, 2010

Microsoft's Really, Really Hidden Folders

Did you know there are folders on your hard drive that Windows does not reveal even when you have all the settings set to reveal everything?  It's this kind of tom-foolery that infuriates me and keeps me in a job.

Did you know that when you tell IE to clear its cache it does not cleanup all the files?  Similarly, did you know that when you delete messages in Outlook Express and empty the deleted items that it does not delete those messages either?  Okay, not that anyone is using OE any more, but still ...
If we've identified a number of folders that M$ works hard to hide then are there others that we haven't found?

Don't believe me?  Try it for yourself ...




Look in your IE Internet Options to determine the location of your Temporary Internet Files.  Open that folder in Explorer.


Do you see a "content.IE5" folder?  Me neither.


Double check your settings.  I'm set to view everything ...


Go back to explorer and add "\content.IE5" to your address bar.  Sure enough.  There's your cached data.



Alrighty then.  Lets delete our cached data in IE.




Finally, lets go look in one of those folders.  It's not a monolith, but it is full of files.  Nice.


I found this to be true as far back as Win98 and, unfortunately, I captured all these screens on my Windows 7 machine this morning.


Thursday, February 4, 2010

SQL Backup Compression & File Cleanup

SerkTools did a nice job discussing how to compress SQL backups using GZIP so I won't cover that.  The article can be found here.

The problem with compressing the backups in SQL 2005 and prior is that SQL doesn't know how to clean those files up.  There are other places in my environment that I need to do housekeeping so I have scripted a .vbs application that can be scheduled with the task scheduler.  My general rule of thumb is: any server, service, application or process must clean up after itself.

Here's my code:

dim path, interval, duration, fso, folder, x, y

path = "D:\MSSQL\Backup"
interval = "H"                                   
duration = 25 ' 25 is intentional due to an assumed rounding issue

set fso = CreateObject("Scripting.FileSystemObject")
set folder = fso.GetFolder(path)
for each x in folder.SubFolders
    for each y in x.Files
        if DateDiff(interval, y.DateLastModified, Now) >= duration and Weekday(Date) = 2 then y.delete
        ' This file should run only on Monday.  If it is run any other day it will
        ' not delete any files.  This is by design.  --BMO
    next
next
set y = nothing 
set x = nothing 
set folder = nothing 
set fso = nothing

I create weekly full backups early Monday morning.  I create differential backups every other day of the week and I capture transaction log backups throughout the day.  Prior to switching from daily fulls and compressing the backup jobs they consumed ~665 GB per week.  Now they consume only 29 GB (95+ % less space).  That's why I run my cleanup job only once per week.

I want the job run on Monday to ensure all my backups have had an opportunity to be written off-site and to tape.  There was nothing from stopping the job from being run on the wrong day so I added the bit of code that checks the day of the week.

DOS and DATES

Have you ever needed a date at the command prompt but need it in a different format? Sometimes the date a file was created or modified just isn't what you need. SQL, for instance, names its files with yyyymmdd date format in the name. Well, here's how to take a date and reformat it for use in your DOS batch files:


FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B 
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET DATE=%yyyy%%mm%%dd%


Of course you can set the DATE environment variable we created in any format you need.  Here's a practical application to copy SQL's dated backup files to a DRP location:

robocopy \\Server1\SAN_DBData d:\nightlyBACKUPS *%DATE%*.BAK /s /r:0 /w:0 /nfl /ndl /np /log+:CopyNightlyDBBackups.LOG


Wednesday, February 3, 2010

Doing Things Remotely


Have you ever needed to move data from one remote server to another?  There's no reason to move the data to my machine as a broker to the other server, but that's exactly what happens when you execute a copy from one network share to another -- or from one UNC patch to another.  This problem is exasperated if the link between your machine and the servers is much slower.

There are a number of tools available from Sys Internals that are fantastic.  I'll focus on "psexec" today.  All of the tools can be downloaded in 1 archive or executed live from http://live.sysinternals.com.

What is psexec?  It's an application that allows me to remotely connect to another machine and execute a command or run a script.  Given the scenario above we can actually tell Server1 to initiate a copy to Server2 without putting our machine in the middle.  Since those 2 servers are connected via gigabit Ethernet it makes no sense to drag the files, in both directions, across a 10 mbit/sec WAN connection.

Why not just RDP to one of the servers and execute the command locally?  Maybe the job is going to take longer than a couple of minutes due to size or quantity of data pieces that must be moved.  If you log out of the RDP session your copy is stopped.  Even if you close the RDP window that doesn't stop another admin from kicking you off.  Executing the remote action from my PC gives me more control of the process.





Let's get started ...

Create a folder to hold the files and add that folder to your system's PATH environment variable.  Do this for the server on which you wish to execute this tool as well.

I'm a huge fan of robocopy.  We'll use examples that utilize it, but you could as easily do the same for xcopy.  If you're going to use robocopy make sure you put the .exe in a folder that is in the PATH environment variable as well.

The syntax can be seen by executing psexec /? at a command prompt.  Here's an example of a copy from Server1 to Server 2.  We'll copy .bak files (for no particular reason):


psexec \\Server1 robocopy c:\somepath \\Server2\c$\somepath *.bak /s /e /w:0 /r:0



You can specify different user permissions if necessary for the psexec command.  You do so by inserting -u {domain\}username between \\Server1 and robocopy.  

Since this isn't a robocopy how-to lesson I won't go in to all the options available.  Suffice it to say that it's a very robust tool and worth your effort to download it and use it.

What else can be done?  Of course you can execute programs you drop on the system.  We've already demonstrated that.  You can also execute anything pre-existing on the system.  For instance, you could stop & start a service (or restart for that matter):


psexec \\Server2 net stop SomeServiceName
psexec \\Server2 net start SomeServiceName


If you've thought of a different use please share!

Tuesday, February 2, 2010

Stupid Ping Tricks

Is there a way to tell if a server is up with a DOS bat file? Yes! I've used this to wait for a network resource to become available before continuing a script.

:PING
ping -n 1 -w 50 192.168.11.1 > nul
if errorlevel 1 goto PING


Is there a way to tell if a server is up with a .vbs file? Yes! I'm using a modified version of this to return a 1 or a 0 for MRTG trending.


On Error Resume Next
strTarget = "10.123.30.12" 'IP address or hostname
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 1 -w 50 " & strTarget)
strPingResults = LCase(objExec.StdOut.ReadAll)

'WScript.Echo strPingResults

if err.number > 0 then
WScript.Echo "ERROR"
End If

If InStr(strPingResults, "reply from " & strTarget) Then

WScript.Echo strTarget & " responded to ping."

Else

WScript.Echo strTarget & " did not respond to ping."

End If