Sunday, March 7, 2010

Checking For Updates

There are quite a few free utilities, add-ins, plug-ins, etc. that are either ubiquitous or at least my own preference to have on all computers. Keeping track of updates was a royal pain. Sometimes I'd get so busy for so long I'd neglect checking for months.
I wanted a script that checks Internet sites for updates rather quickly. I figured PowerShell would give me the power to do it. I finally found the code from Alex Angelopoulos at
WindowsITPro, but I'm not sure anyone thought to use it the way I wanted.
I prefer to leave my PowerShell security at the default level, which is to disable scripts from running. I use an old-fashioned CMD script as a wrapper-script to write my script, lower security, run the script, and finally delete the script and raise security back up.
The script requires maintenance, but it sure beats the old haphazard way. I edit the version-levels for each product to keep them current. The script checks the host web-page, tries to look for a version string, and if it can't find it, it is assumed the version has either changed to a newer one, or the version can no longer be found.

Some web-pages confound all my efforts to find a version I can query. That's because they have some very intricate layers of web-sites working together that make them hard to hack. I'm not trying to hack them - just query them - but their security precautions have made it impossible for me to check Apple's or Adobe's sites. The others are pretty straight-forward.
As usual, watch out for text-wrapping in the code window.


:: Allow PS scripts to run
powershell -command "& {Set-ExecutionPolicy -Scope LocalMachine Unrestricted -Force}"

:: Create Powershell script (from Alex K. Angelopoulos, WindowsITPro)
:: http://windowsitpro.com/article/articleid/99844/use-the-net-webclient-class-in-powershell-scripts-to-access-web-data.html
@echo Param( > ".\Get-WebString.ps1"
@echo [string]$Uri, >> ".\Get-WebString.ps1"
@echo $Encoding = "Default" >> ".\Get-WebString.ps1"
@echo ) >> ".\Get-WebString.ps1"
@echo $WebClient = New-Object System.Net.WebClient >> ".\Get-WebString.ps1"
@echo $WebClient.Encoding = [System.Text.Encoding]::$Encoding >> ".\Get-WebString.ps1"
@echo $WebClient.DownloadString($Uri) >> ".\Get-WebString.ps1"

:Sun Java Update 18
powershell -command ".\Get-WebString.ps1 http://www.java.com/en/download/manual.jsp" | find /i "Version 6 Update 18"
if %errorlevel%==0 goto :Diskeeper
"C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.java.com/en/download/manual.jsp

:Diskeeper
powershell -command ".\Get-WebString.ps1 http://www.diskeeper.com/Diskeeper/update-patch/update-patch.aspx" | find /i "Build-900"
if %errorlevel%==0 goto :Firefox
"C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.diskeeper.com/Diskeeper/update-patch/update-patch.aspx

:Firefox
powershell -command ".\Get-WebString.ps1 http://www.mozilla.com/en-US/firefox/ie.html" | find /i "US/firefox/3.6"
if %errorlevel%==0 goto :doPDF
"C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.mozilla.com/en-US/firefox/ie.html
:: http://wiki.mozilla-x86-64.com/Firefox:Download

:doPDF 7.1.330
powershell -command ".\Get-WebString.ps1 http://www.dopdf.com/" | find /i "7.1.330"
if %errorlevel%==0 goto :Paint.NET
"C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.dopdf.com/

:Paint.NET v3.5.4
powershell -command ".\Get-WebString.ps1 http://www.getpaint.net/" | find /i "v3.5.4"
if %errorlevel%==0 goto :IZArc
"C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.getpaint.net/

:IZArc
powershell -command ".\Get-WebString.ps1 http://www.izarc.org/download.html" | find /i "4.1"
if %errorlevel%==0 goto :CPU_Z
"C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.izarc.org/download.html

:CPU_Z
powershell -command ".\Get-WebString.ps1 http://www.cpuid.com/cpuz.php" | find /i "Z 1.53"
if %errorlevel%==0 goto :burnaware_free
"C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.cpuid.com/cpuz.php

:burnaware_free
powershell -command ".\Get-WebString.ps1 http://www.burnaware.com/downloads.html" | find /i "2.4.4"
if %errorlevel%==0 goto :DeepBurner
"C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.burnaware.com/downloads.html

:DeepBurner
powershell -command ".\Get-WebString.ps1 http://www.deepburner.com/?r=download" | find /i "DeepBurner Free 1.9"
if %errorlevel%==0 goto :ImgBurn
"C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.deepburner.com/?r=download

:: It's longer, but I'm truncating many sections. You can extrapolate from here.
:: So on to the ending...

:END
del /q ".\Get-WebString.ps1"

:: Raise PS security back up
powershell -command "& {Set-ExecutionPolicy -Scope LocalMachine Restricted -Force}"
powershell -command "& {Set-ExecutionPolicy -Scope CurrentUser Undefined -Force}"
powershell -command "& {Set-ExecutionPolicy -Scope Process Undefined -Force}"


Why not use VersionTracker? Because my company blocks that site, and because that site has too many items, and not all the items I want. My script is just-right for me. While it runs, I can be doing other things. By running it once a week, I stay current.

Wednesday, February 3, 2010

Manually Killing Viruses, Part 4

This is the mop-up, or the repair. At this stage, all the viruses, worms, Trojans, rootkits, etc. are gone, but Windows is damaged. A repair-install often doesn't fix things. Installations often only look to see if something exists, and if it's already there, it wont' actually re-install.
Some Windows XP machines are infected because they don't have the latest patches or service packs. If there's an i386 folder on the hard drive, it would be wise to make sure it has the latest service pack applied. To find out at a glance, just look for a file starting with SP3 in i386. If all you can find is SP2, then try slipstreaming SP3 into the folder.
You might want to consider the SFC command. The right command can force all files to match a specific source.

If the problem is that you can't reach the Internet, check the "hosts" and "lmhosts.sam" files. They're in C:\Windows\System32\drivers\etc\ Open them with Notepad and make sure the only line in hosts is the standard loopback...
127.0.0.1 localhost
lmhosts.sam should be blank, but lines beginning with "#" are comments. All of lmhosts.sam is normally comments.
Malware can redirect valid Internet addresses to go to malicious sites instead.

Damaged Internet security suites, like McAfee and Norton Internet Security are usually damaged by malware, and you can't get to the Internet until the products are forensically removed. Luckily McAfee and Symantec/Norton each have removers.

You might also try repairing the winsock with WinsockFix, or something like it. Delete the network device(s) from Device Manager and rebuild them.
If you still can't get to the Internet, run all these commands in this order...
net use * /d /y
NET USE /persistent:no
ipconfig /release
net start lanmanserver
net start Server
net start lanmanWorkstation
net start Workstation
net start "Remote Procedure Call (RPC)"
net start RpcSs
net start "Plug and Play"
net start Telephony
net start wuauserv
net start Dhcp
net start "DHCP Client"
net start Dnscache
net start "DNS Client"
net start helpsvc
net stop NetSvc
net stop Netlogon
net start Netlogon
net start Netman
net start "Network Connections"
net start "Remote Access Connection Manager"
net start "Security Accounts Manager"
net start prepdrvr
net start LmHosts
net start TapiSrv
net start "TCP/IP NetBIOS Helper Service"
net start TermService
net start WebClient
net start Browser
netsh int ip reset
netsh winsock reset
netsh firewall reset
ipconfig /renew
arp -d *
nbtstat -R
ipconfig /flushdns
nbtstat -RR
ipconfig /registerdns
netdiag /test:winsock /v


If you can get to the Internet, but specific addresses are blocked, look in hosts or lmhosts.sam, as mentioned above, or look in the Registry under...
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains

As soon as you get to the Internet, you should update all anti-virus and anti-malware definitions, update Windows, or install/reinstall the protections that were removed.
As of this writing, these are my favorites, in this order...
Antivirus
Microsoft Security Essentials
Avast!
Anti-malware
Malwarebytes
Spybot
Rootkits
Rootkit Revealer
Panda

The Rootkit tools only reveal rootkits, they don't clean.
Plus, you have to know what you're looking at. Some of the items in the revealed list are not bad things, but good. But the list is normally short.

Oh, one more thing... If you encrypted the hard drive, and a virus ruined your computer, none of this is likely to work at all. Reformat. Encryption at the hard drive level is a nasty bit of business. Not worth it, in my opinion. If you have data that critical, stick it on a secure USB drive. I have one that requires a password, plus a fingerprint. That's should work for paranoid data. I highly recommend avoiding entire hard drive encryption, unless it's a secondary drive.

Friday, January 29, 2010

Manually Killing Viruses, Part 3

Hunting for viruses in the Registry...
The most obvious startup location in the Registry is...
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
and
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

The following are normally empty...
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunServices
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunServicesOnce
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce

It gets more complex beyond that...
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows /v AppInit_DLLs (this is normally blank)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
The "Shell" and "UserInit" values often are edited by viruses, sometimes loading worms or Trojans.

If the computer is un-bootable, and you're booted of a Rescue CD, then you need to load Registry hives off the hard drive. To do this, you need to launch Regedit and expand HKEY_USERS. With HKEY_USERS highlighted, click "File", "Load Hive...", and browse to C:\WINDOWS\system32\config\. Make sure you're loading from the correct drive, or you're wasting your time. If booted from a rescue CD, the Rescue CD's Windows folder will be the default. Make sure you pay attention and get to the correct, infected, hives. Give them sensible names.
Load "SOFTWARE" and "SYSTEM", naming them something that makes sense. Or name them anything beginning with any letter after "S" so that alphabetically the hives you load always drop below the other normal hives. This is because you'll be doing searches and it's faster to search only the loaded hives.



Next, load all the user profiles which create HKEY_CURRENT_USER when users are logged on. These hives are called NTUSER.DAT and are stored at the root of every profile...
C:\Documents and Settings\%username%\NTUSER.DAT


Some don't realize that HKEY_CLASSES_ROOT is identical to HKEY_LOCAL_MACHINE\SOFTWARE\Classes. When you load the "SOFTWARE" hive, you effectively get full access to HKEY_CLASSES_ROOT through the ...\Classes key.
Look into every startup location as mentioned above.

In the System hive, you'll be looking for malicious services. It helps to have a healthy Windows XP machine to compare with. Still, there is some guess-work. Proprietary OEMs like to add tons of mostly legitimate craplets. That's what I call the 30-50 odd-ball "goodies" that HP, Gateway, Sony, Dell, etc. like to infest new computers with so that they run like crap. Since these things usually cause more degradation that value, if you accidentally break one of these, thinking it's a virus, no real harm done.

You need to look at all the suspicious DLL's and EXE's that you carved out of \Windows\ and \System 32\. Copy the names and search the loaded hives. This is how you find where they're activated. In doing this, you sometimes find out that the files are okay, and you can put them back. Other times, you get confirmation that they're malicious.

When you're done, always unload the hives. If you forget, things usually tend to unload okay anyways, but sometimes it will corrupt the hives (or the logs) and make things worse.


This whole set of posts is abbreviated. There really are too many sneaky places in the Registry to launch threats to mention all of them. Many replace Windows files with malicious files, diverting normal functions. Others create new services and functions.

Finally, check C:\boot.ini to see if anything is bogus.

When you believe you've carved the worst out, try booting off the normal hard drive.

Tuesday, January 26, 2010

Manually Killing Viruses, Part 2

It helps to have a healthy example of every OS to compare a viral computer with. Not sure exactly what the healthy Registry key should be? Look on your XP example machine.
And of course you have to have another computer connected to the Internet to Google any questions. Look up info on files, Registry values, viruses, cleaning and repair advice in various situations...

So we left off with temp files deleted and you sorted the Windows and System 32 folders to see what the most recently modified files were. And you moved suspicious files to a dormant folder we named C:\Suspicious.
You can also do the same inside the Program Files folder. You can move entire folders.

Browse to every Startup folder in every profile on the computer and look for links to suspicious executables.
Check all Favorites, QuickLaunches, Desktops, etc. for evil links.
Check Microsoft Office Startup folders for C:\Program Files\Microsoft Office\Office12\STARTUP and \XLSTART and every profiles startup folders for Word and Excel.

If they have a legal copy of McAfee, you can download the latest McAfee definitions, expand them, and run a commandline scan. Example for the SuperDAT definition file named "sdat5873.exe"...
- Download the DAT or SuperDAT to the McAfee installation folder. Also download the latest engine.
- Then open a command prompt at the same path and run the following command...
sdat5873.exe /e
- Then run 5400eng.exe to update the McAfee engine. If this fails, you're dead in the water until you get the computer booted the hard way.
These files will not expand unless you have a legal McAfee license.
You may not get much feedback when the def's expand, so open Task Manager and watch until sdat5873.exe drops out of memory. On a slow computer, it can take 15 minutes. On a fast computer, it can take 20 seconds.
- Assuming all went well, and both the engine and the def's are expanded, you should see quite a few files, one being scan.exe and several ending in .dat. In the same command-prompt path, launch a scan with the following command...
scan.exe /adl /all /noexpire /clean /rpterr /report c:\ScanRpt.txt
This can take an hour.

You can do the same sort of things for Norton/Symantec - download various stand-alone tools and start scanning.
You can also scan using tools that come on the UltimateBootCD4Win. There are all sorts of anti-virus and anti-malware scanners on the CD.

While that's churning, you can browse suspicious files some more.
One of the crafty things malicious hackers do is they might take legitimate Microsoft files and rename them. So you might do a cursory glance and file properties and see that it is labeled as a Microsoft file. It looks legit. But pay attention. Sometimes they'll take something like tftp.dll and rename it to something else, like ftfp.dll. Their code might use trivial ftp to open a conduit for the hacker to take control of your computer, or send your passwords or credit card account numbers. So make sure that the file name matches the what the properties say it is. A mismatch is definitely suspicious.
To avoid DLL-hell, Windows will sometimes keep multiple copies of one DLL on the hard drive. They obviously have to have different names. Depending on what version of a DLL is required, Windows will register a DLL by an alias, and then when loaded into memory, an alias'd DLL is loaded with the proper name so that the program works. So just because a DLL has a different name doesn't necessarily prove that it's bad, but if it looks suspicious, like tftp does, you should move it to the C:\Suspicious folder.

This concludes part 2.
Next, we'll get to the Registry.
Only a geek would think this is fun.

Monday, January 25, 2010

Manually Killing Viruses, Part 1

This is mostly for Windows XP, since I've never personally seen OSX, Vista, or Windows 7 with a virus. The latter three can get viruses, but they tend not to because they have a far better OS design.

I was recently presented with the most virus-infested junk-heap I've ever seen. First, it was clogged with cat hair and dust. Second, it REEKED of cigarette smoke! Every time I turned it on, I gagged.
This computer was running Windows Media Center Edition SP3, but it was unbootable. It kept prompting to restore from the Sony recovery partition that would reformat the hard drive. This would have nuked about 2,000 songs, video clips, and movies. It would also have taken several licensed products with it, including Office 2007.

Geek Squad wanted $200 just to "look" at it. No offense - they're just making a living. I'm sure they would have just reformatted and handed it back with a $300-$400 bill. I fixed it for $40, since she was a friend and co-worker.

My primary tool in these situations is the Ultimate Boot CD 4 Windows. This developed from BartPE, which is almost an historical name, now. But those of us who participated in developing it felt like pioneers. I may have been the first person to build a bootable USB stick, with Windows XP on it, but the computer I was trying to use wasn't USB-bootable as Dell had claimed. Two weeks after someone else had succeeded, I got a Dell D800 that I successfully booted my USB stick to - the same one that had been built three weeks before.

Enough nostalgia...
Booting to the UltimateBootCD4Win allows you to be a virtual god. The viral hard drive is dormant - nothing on the hard drive is running.
I boot from a 4GB USB stick. The boot-image is only 512MB - the USB boot-image limit. But that doesn't matter. The boot image ends up being drive X: and the rest of the space on the USB stick is whatever drive letter is available after the other drives have been enumerated.

The strategy/mentality is thus... Every virus in the past 10 years seems to be a "blended threat", meaning you never get infected with just one bug. You end up with a virus, a few worms, and a Trojan or two. There's often a root-kit installed, too.
So, booting from the UltimateBootCD4Win, I browse to the C: drive.
- Save time and delete all temp files...
-- C:\Windows\Temp
-- C:\Documents and Settings\%userprofile%\Local Settings\Temp
-- C:\Documents and Settings\%userprofile%\Local Settings\Temporary Internet Files\Content.IE5\ (delete all folders and index.dat, but leave desktop.ini)
Do a searching delete of all files ending in .tmp, .del, .dmp, .chk, or beginning with tilde (~).
Now look at all the old Windows patch folders that collect in the Windows folder. Delete every old folder and log file that you know you'll never want to uninstall. Usually that means keeping anywhere from 3 months to a year - no more.
This saves time from then on when running scans and searches because now there are fewer files on the hard drive. And you probably broke several viruses in the process.
- Next, analyze the contents of C:\Windows\ and C:\Windows\System32\, sorting by date/time. Some legit files update every second, like the Windows XP licensing file wpa.dbl, so this is an example of an important good file. Many of the others will be viruses. Don't just start deleting everything unless you know for sure. If you don't know for sure, then try moving them to a folder, like C:\Suspicious\. Recreate the folder structure inside there. Wherever you take a file, drop it in the same folder, like C:\Suspicious\Windows\System32\. That way when you're finished, and you decide some files are safe, you can put them back.

This concludes part 1 - the easy preliminary steps. It gets more complex in following chapters.

Friday, November 27, 2009

Running Repetitive Remote Tasks

In my support of computers, I very often have to run scripts to perform tasks on all the machines in my area. Sometimes I have to query the Registry for the version of Adobe Reader or Acrobat, sometimes I have to copy a file to every computer, or change a service start from "automatic" to "manual".

Whatever it is, I had a method for generating a list of all my computers, then I would edit with Notepad using Edit/Replace. When I started doing that, I thought I was so efficient, but I wasn't, really. I had to start from scratch every time. It was a simple process but a little tedious.

Here's how I would generate a list of all the computers in Finance. The first letter of all machines began with "F". So I use "net" and "find" to filter...

net view | find/i "\\f" >> fin.txt


After years of editing these things, and needing to update old scripts for doing the same thing a year later, it got to be a mess. For one thing, computers come and go, so I had to regenerate the list of computers repeatedly. Why not just have one master list? Maintain that one list. Use "call" to process it.

Unfortunately, this new way requires three scripts, not one, so it seems more complicated, at first, but in constant use, it's actually much easier.
To keep things sorted and easy to see, I name all the first scripts starting with "1_".
The master list is called "2_FinancePC_List.bat", and that doesn't change - that's my master list that is always kept up-to-date whenever I surplus a PC or get new ones online.

I'll use a query for Adobe as an example.

The first script is short and easy to edit. I can copy the first file from another query and then rename it. So I usually only have to edit the name of the query and the name of the report...
(Warning: some lines might be "wrapped".)

:: =======================
:: Edit the "set" values
:: =======================
title Adobe Query
set CmdPath=D:\RemoteCommands\Queries
set CmdFile=3_AdobeQuery.cmd
set RptFile=Adobe_Report.txt

del /q %CmdPath%\%RptFile%
time /T >> %CmdPath%\%RptFile%
call "D:\RemoteCommands\2_FinancePC_List.bat"
time /T >> %CmdPath%\%RptFile%
start notepad.exe %CmdPath%\%RptFile%


For convenience, the report gets launched in Notepad upon completion.

You can see the real query trigger is "call "D:\RemoteCommands\2_FinancePC_List.bat"". Variables are set in the first script, and passed to the second script. So for each new query, I don't need to edit the master list. That much is generic and part of my seperate, on-going inventory process.

Here's a shortened version of the second file to give you the idea...

call %CmdFile% F1118 "Gotta Gno"
call %CmdFile% F1119 "Betty Whine"
call %CmdFile% F1120 "Bob Bobster"


Of course, this list is pretty long, but all lines are similar. Only the computer name and end-user name are different, and those are passed as parameters "%1" and "%2" to to third script.

The last script is the meat-and-potatoes, and it begins with "3_".

:: Avoid the full time-out wait for each PC that is offline...
@ping -n 1 %~1
if errorlevel 1 goto There

:: Adding the "findstr" command strips out the extraneous two lines the REG QUERY command produces...
@echo %~1 %~2 >> %CmdPath%\%RptFile%

dir /s /b "\\%1\c$\Program Files\Adobe\Acrobat.exe" >> %CmdPath%\%RptFile%
dir /s /b "\\%1\c$\Program Files\Adobe\AcroRd32.exe" | findstr /i Reader

reg query "\\%1\HKLM\SOFTWARE\Adobe\Acrobat Reader\5.0\InstallPath" /ve | findstr /i REG_SZ >> %CmdPath%\%RptFile%
reg query "\\%1\HKLM\SOFTWARE\Adobe\Acrobat Reader\6.0\InstallPath" /ve | findstr /i REG_SZ >> %CmdPath%\%RptFile%
reg query "\\%1\HKLM\SOFTWARE\Adobe\Acrobat Reader\7.0\InstallPath" /ve | findstr /i REG_SZ >> %CmdPath%\%RptFile%
reg query "\\%1\HKLM\SOFTWARE\Adobe\Acrobat Reader\8.0\InstallPath" /ve | findstr /i REG_SZ >> %CmdPath%\%RptFile%
reg query "\\%1\HKLM\SOFTWARE\Adobe\Acrobat Reader\9.0\InstallPath" /ve | findstr /i REG_SZ >> %CmdPath%\%RptFile%
reg query \\%1\HKLM\SOFTWARE\Classes\Installer\Products\68AB67CA7DA73301B7449A0100000010 /v ProductName | findstr /i REG_SZ >> %CmdPath%\%RptFile%
goto END

:There
@echo %~1 - offline - %~2 >> %CmdPath%\%RptFile%
goto END

:END


Here is a sample of what the report looks like...

F1118 Gotta Gno
\\F1118\c$\Program Files\Adobe\Acrobat 6.0\Acrobat\Acrobat.exe
F1119 Betty Whine
\\F1119\c$\Program Files\Adobe\Acrobat 8.0\Acrobat\Acrobat.exe
F1120 Bob Bobster
\\F1120\c$\Adobe\Reader 9.0\Reader\AcroRd32.exe
REG_SZ C:\Program Files\Adobe\Reader 9.0\Reader


With this info, I know who is in the most dire need for upgrades. Depending on the schedule of the end-users, I can conveniently work the upgrades in.

Monday, November 23, 2009

Free Hard Drive Space

Here's a routine that checks a hard drive for free space.
If there's less than about 1GB, turn the window red and report.

@echo.
@echo Checking disk space...
@echo.
@FOR /f "tokens=3 delims=/ " %%G IN ('dir c:^| findstr free') DO (set FreeSpace=%%G)
@FOR /f "tokens=1,2,3,4 delims=," %%i IN ("%FreeSpace%") DO (set FreeVar1=%%i& set FreeVar2=%%j& set FreeVar3=%%k& set FreeVar4=%%l)
@set x=%FreeVar1%%FreeVar2%%FreeVar3%%FreeVar4%
:: Convert bytes to megabytes...
@set /A x/=1048576
@echo.
@If %x% LSS 1000 echo Drive C: only has %x%MB left!& color cf& @echo.& @pause

Above +2,147,483,647, script math fails to be accurate.
2,147,483,647 converted to gigabytes is 1.9999GB, but because it rounds down, it rounds to 1GB.
Since this script is looking for sizes below 1GB, and it's silent above that, it will produce accurate reports.

Saturday, November 14, 2009

Scripts are Super-Lists

Techs do lots of tasks repeatedly. Some lists get very long, like ones for building a computer and all the settings you want to change from the defaults. It's a good idea, when there are tons of things to remember, to make a checklist. This way you guarantee that every computer is built the same.

In the beginning, building a computer in my company (they didn't use Group Policy, nor Roaming profiles) took me a few days (end-users were spoiled and could download and install anything from the Internet, and I was required to migrate all their "toys" and settings).
My job was absolutely overwhelming. Everyone who had my job before me quit - all of them. Too many rude, over-demanding end-users, and my boss backed them, not me.
I soon started scripting. I had scripts for this task, scripts for that task, etc. There were so many scripts for so many things. My build-times got down to a day-and-a-half. This is still a long time, in tech-speak, but I was getting things under control.

Most companies don't allow end-users to play on their computers, and they use Group Policy and Roaming profiles. Building a computer consists of dumping an image to the hard drive and delivering. It's all cookie-cutter - no headaches for techs. If end-users want to play, they should bring a deck of cards.

I got very efficient, I thought. The stress subsided to where it was almost tolerable. My boss saw this, and then dumped an additional department of end-users onto my plate. Back to the impossible hi-stress mode. People with emergencies had to wait up to three days, if I had multiple emergencies going on simultaneously.

That's when it dawned on me that my scripting needed to go to the next level. My collection of scripts needed to be streamlined. To do this, my scripts had to use checks. If "this", then do "this", else do "that". Three scripts became one here, two other scripts became one, etc, but I kept thinking up new tasks that could be scripted. There was one that I ran more often, though. It was my "main" script.

Today, that script is nearly 1200 lines (including blank lines and comments) and is so comprehensive that it will check Adobe versions, Flash, Sun Java, IE version, Office service pack level, check for hard drive errors, etc, etc, etc. And it will even ask if I want to install or upgrade and will call that task. If a computer is new without updates, it will take over an hour to run this script, depending on the installs needed. If a computer is fully up-to-date, this script takes seconds to run, skipping sections that don't apply.
This script allows me to do several hours worth of work in a very short time. And because scripts don't forget, like my busy and aging mind does, nothing gets neglected.
Now it can take me as little as 30 minutes to build a computer and migrate all the user's stuff from the old PC to the new one, right down to the Desktop icon positions on the screen. Other than the end-user's unique data and settings, eveyr computer in my area ends up the same.

Another thing my super-script does is, when I find a problem - or potential problem - I can add certain tweaks to this script. This is proactive and keeps machines healthy.

My stress levels have dropped significantly because I can do an impossible workload using scripts. The workload is no longer impossible.

My company is slowly locking-down what end-users are allowed to do, they've started using Group Policy, Windows Updates are automatic, and they're discussing Roaming profiles. That will help, but I've learned under stress how to get every tiny detail "just right", so my maintenance-and-update script will never be obsolete. It just gets more refined as the years go by.

Eventually, I would like this script to end up being programmed in Visual Basic as an interface tool, calling xml files where options are stored, and allowed any tech to customize what happens, including calling scripts of their own.

Friday, November 13, 2009

32GB eSATA Thumbdrives

Many months ago, I bought a 32GB OCZ Throttle drive. It was awesome!

I like to use the Ultimate Boot CD for Windows (UBCD4Win). I've been using this on USB mostly for Ghosting and anti-virus scanning. Booting off USB is usually fast. (For some odd reason, booting of USB is sometimes slower than booting off a CDROM.)
The bad news about the UBCD4Win is that it boots off an ISO image, which is old technology and limited to 512MB. My collection of stuff is larger than 512MB, but I discovered that I can store the rest of my stuff outside the ISO and it is perfectly accessible as a separate drive after booting off my half-gig ISO. So it's easy to drop anti-virus updates onto it at any time with no hassles.
I was actually one of the geeks who worked on Bart's PE when booting off USB was impossible. I was damn nearly the first person to boot off USB back when the largest drive was 128MB, but the computer I was using was purported to be capable of booting off USB, but wasn't. Someone else beat me to it. Two weeks later, with a Dell D800, my 128MB stick booted up, but I would have had it by a week.
Today, think how fast you could boot the UBCD4Win off an eSATA drive! Vroom!

But I digress...
My OCZ worked for about 2 weeks. Then the eSATA stopped working. This was a surprise. OCZ is very good quality, but this one died. In fact, I suspect it blows every eSATA port it gets plugged into. I have a brand-new Windows 7 supercomputer, and the eSATA doesn't work. I suspect my OCZ blew it. We got a small handful of computers at work that each had eSATA ports, and my OCZ doesn't work on any of them. I suspect I blew them also by plugging my bad OCZ into them. Bummer!

Now I've bought a Kanguru 32GB eFlash. I can't get the eSATA to work, right out of the box, but like I said, I suspect my OCZ blows every eSATA port it gets plugged into, so my supercomputer at home might be bad. I've checked the BIOS and there are NO SATA settings!! Apparently everything is completely automatic when it comes to IDE and SATA on this ASUS motherboard.
So now I wonder - did I blow my new eSATA thumbdrive? Or is it just not initializing because the port is dead?

On to other things...
The USB end works on both drives, so they aren't useless.
The Kanguru partition was garbage. When I right-clicked to create a text file (just for testing), it wouldn't let me. So I created a blank text file on my computer and copied it to the Kanguru. That worked. Then I opened the text file and typed "test" and tried to save, but it wouldn't let me. Weird. It's not read-only, because I just copied this text file to the drive, but I can't create a new text file via right-click, and I can't save from within Notepad.
So I repartitioned and reformatted. Now it works fine - except for eSATA.

But eSATA is probably a waste, with USB3 on the horizon.

Friday, November 6, 2009

PowerShell beginner

I'm just now beginning to learn PowerShell. It's been confusing because too much of the material doesn't tell the details. They shove snippets at you without telling you, "This only works with Windows 7, not in XP", or "This won't work with the default, restricted settings for PowerShell security."
A PowerShell script file ends with the .ps1 extension.

I developed a method to run scripts without permanently lowering my computer's security. You launch scripts from an old-fashioned batch script. The script calls PowerShell, commands security to be lowered just enough to execute the script(s), then raises it back up again. I would also end the .ps1 script by raising the security, in case there's ever a problem returning to the initial batch script.

Try this...
LaunchPSScript.cmd

powershell -command "& {Set-ExecutionPolicy Unrestricted -force}"
@set /p ScriptName=What's the name of your Power Shell script? :
powershell -command .\%ScriptName%
@pause
:: Return the security policy to default, restricted.
powershell -command "& {Set-ExecutionPolicy Restricted -force}"

Run this batch file from the same folder where the PowerShell script resides.
Copy the full name of your script and when prompted, paste the name and hit Enter.

Here's a simple PowerShell script you can use to test this out...
EventLogQry.ps1

clear-Host
# PowerShell script to find Error messages in the System eventlog.
get-EventLog system -newest 2000 | where {$_.entryType -match "Error"}

# Return the security policy to default, restricted.
Set-ExecutionPolicy Restricted -force


With default PowerShell security restrictions, calling the PowerShell script by itself will produce an error like the following...
File EventLogQry.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
At line:0 char:0

Unfortunately, this doesn't work on Windows 7, only on Windows XP.
First, you have to right-click the batch script and "Run as administrator. Okay - no problem.
Second, what breaks it is that the script doesn't run from the path where the script resides. In XP, if you store and run the file from C:\Scripts\PowerShell>, it runs from that path. Not so for Win7. Win7 doesn't care where you run it from, it defaults to C:\Windows\System32>. If I have to hard-code the path, it ruins the convenience of this system.
Third, the command to lower security, or to raise security is squirrelly because I have no permissions on HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell. The weird thing is that the Set-ExecutionPolicy command won't work on my Win7 machine from the PowerShell console, nor from a .ps1 script, but it will work from a batch script. This seems to be a gaping hole in Microsoft's grand scheme, but if it's consistent across Win7 versions and default settings, I'll use it.

I don't mind learning new ways to support Windows 7, but I hope there IS a way to support Windows 7. That was the problem with Vista - unsupportable in a corporate environment. To protect the computer from malicious scripts, Microsoft has set roadblocks just about everywhere. Many things just won't work without a GUI (Graphical User Interface) interruption. I'm really struggling to figure out how to support Windows 7 without lowering security permanently. If there's a way to leave all settings at default, and still operate, that's preferable.