Showing posts with label command. Show all posts
Showing posts with label command. Show all posts

Thursday, March 20, 2014

Dave's Top 10 Windows Command-Line Goodies

I'll admit it, I like geeky "Top 10" lists.  The irony of saying "Windows" and "command-line" in the same sentence also fits nicely with how my wobbly brain works, so I couldn't resist.  While scripting is obviously in a class of its own with regards to flexibility, scale and so on, the built-in tool set provided within Windows 8 (and Windows Server 2012) is still worthy of some healthy respect.

The commands listed below are some that I use quite often, and by that I mean pretty much every day. On a typical day I will have two CMD consoles open, a PowerShell ISE console and at least one or two instances of some code editor application like TextPad or Visual Studio Express.  Regardless, I will often jump back to one of my CMD consoles to do something that involves one of the items mentioned below.  Maybe there's a few in here you haven't tried yet.

1. CMDKEY

I use this for managing my credential mappings between my laptop, my home domain environment, my various "work" environments, and TS/RDP environments.  To list saved credentials, use "cmdkey /list".  You can narrow down the list to one target, such as a server you connect to by SMB or RDP named "fubar", by typing "cmdkey /list:fubar".  To add a new explicit mapping, such as connecting to server "fubar" from your tablet which is not part of the same domain or workgroup, use "cmdkey /add:fubar /user:dave /pass:p00rb@$taRd".  For more information about this command, type "cmdkey" and press Enter.

Example: save login credentials for domain server "serverXYZ" from your workgroup laptop...
cmdkey /add:serverXYZ /user:dave /pass:Ih@teP@$$wordZ

2. WINRS

This is another command I find extremely helpful.  There are a few times where it doesn't shine as brightly as I'd like, but that's rare.  One such example (and don't let this put you off) is invoking a utility like "SendSchedule.exe" on a remote box, even when the associated XML config file is in the appropriate location.  You just get nothing.  Again, this is not worth tarnishing this powerful utility.

What does it do?  Magical stuff.  That's what.  It's basically a remote shell wrapper, and lets you execute tasks on the remote computer as if you're on that remote computer.  So if you have a script, say "dosomething.ps1" sitting in the c:\stuff folder on serverXYZ, and you're on your laptop named "dingy8", you can open a command console (or PowerShell console) and type:

winrs -r:serverXYZ powershell.exe c:\stuff\dosomething.ps1

Then watch the results unfold as if you were logged onto serverXYZ and running the script directly.

There's way more to this command than I can possibly blurt out here, so try "winrs -?" to begin exploring.

3. PUSHD and POPD

This one has been around almost as long as me.  Same for its cousin: popd.  The pushd command creates a temporary "ad hoc" drive mapping to a specified share.  So if just need a drive letter, under the context of whatever the command console is running as, just type "pushd " and bang! you have a Z: drive and it's the current drive as well.  So why does this do any better than "net use"?  Well, to disconnect "net use" you have to use "net use" again and provide some more key strokes.  In some cases, you forget and leave the drive mapped even after repeated logins.  The pushd command only lasts until you either log off (or "sign out" in Windows 8 parlance), or use "popd" to release any pushd mappings.

Example: map a temp drive to share \\serverXYZ\stuff --> pushd \\serverXYZ\stuff

4. SC

The sc command is another golden-age oldie that provides command-line control over the Windows Services environment.  SC allows you to stop, start, create, delete, and modify Windows Services.  Nuff said.

Example: Check on the status of the WinRM service --> sc query winrm
Example: Stop the WinRM service -->  sc stop winrm
Example: Change WinRM startup to manual -->  sc config winrm start:demand

for more information, type "sc /?"

5. SCHTASKS

Like the sc command, this is one is a counterpart to a common GUI tool.  This one provides management features for Scheduled Tasks (hence the abbreviated name: "SCHeduled TASKS").  You create, delete, modify, list, export and import scheduled task jobs with incredible detail and control.  In many cases, it's easier to shove a command string using schtasks through a shell operation from within a script, than to use the direct API alternatives like WMI and .NET, but it depends on your circumstances of course.

Example: List all scheduled tasks on remote computer "Abc123": schtasks /s abc123 /query
Example: Run task "doit" on remote computer "abc123":  schtasks /s abc123 /run /tn doit

6. SHUTDOWN

Ah, this is a most powerful, yet most simple command tool.  Almost as flexible as "psshutdown" and some other third-party tools, it lets you request or "force" a shutdown, logoff or restart of a remote computer, as well as the local computer.

Example: Restart remote computer "abc123" in 30 seconds --> shutdown -m abc123 -r -f -t 30
Example: Restart "abc123" with a custom display message to the current users...
shutdown -m abc123 -r -f -t 30 -c "IT rulers are kicking you minions off in 30 seconds!"

7. REG

If you haven't heard of this command already, you might have guessed that it has something to do with the Registry.  Yep.  This cool gadget provides command-line capabilities for reading, writing, importing and export registry keys and values and a little more as well.

Example: Display installed apps...
reg query hklm\software\microsoft\windows\currentversion\uninstall /s

Example: Import a .reg file
reg import regfile.reg

Example: Import a .reg file into 32-bit view on a 64-bit computer:
reg import regfile.reg /reg:32

8. ROBOCOPY

Oh boy.  What can I say about this command that hasn't already been said?  Once you get used to it, xcopy and the like will be flushed down the drain for good.  Powerful.  Flexible.  Simple.  Incredibly useful.  And it was one command I was happy to see rolled into the base operating system configuration, where it was once relegated to Resource Kit add-ons.

One scenario I use this in quite often is wrapping in a .bat script to synchronize remote project folders to a central location, and then invoke the 7-Zip command-line interface to archive the backup content into .zip files and offload them to attached or removable storage.  For me it's just another redundant redundancy of backups, in addition to server backups, DropBox, Google Drive and One Drive.

Example: backup only .vbs and .ps1 files which are newer than those already backed up, or added since last backup, from \\server123\stuff to d:\archives\scripts...
robocopy \\server123\stuff *.vbs *.ps1 d:\archives\scripts /xo /s

One interesting aspect to robocopy is showing the "help" information.  On older versions, "robocopy  /?" or "robocopy /???" and get very different results.  However, on Windows 8 and Windows Server 2012 both options were merged to produce the same results.

9. MSG

This sneaky little turd hijacked the old "net send" command like a stealthy ninja.  Not quite a easy to implement due to the choke collar placed on the messenger service since Windows XP was taken out in a boat and shot in the head (GodFather homage).  I wrote a blog post some years back on nothing but how to implement msg in a Windows 7 environment and enable the plumbing using a GPO.

If you don't have a GUI IM product in use, such as Communicator or Lync (same thing, different lipstick), and don't have an IRC app in use, this is another means to annoy your coworkers.

Example: tell my son Zach to get to bed, while he's uploading guitar demos at his computer in his bedroom...  msg zachary /server:zachspc /v "bed time dude!"  (the /v option says to wait for him to click the 'ok' button to indicate he read it).

10. MSTSC and MSRA

Holy crap, these are powerful and offer everything from really simple/basic/easy usage to up arguably complex yet powerful usage.  MSTSC is the Remote Desktop utility.  So instead of navigating the Start Menu or Start Screen for Remote Desktop, and entering a computer name to access, you can invoke it from a command-line aspect.  It also offers command-line options for dealing with multiple monitors (/span and /multimon), shielding credentials (/restrictedAdmin) and invoking a preconfigured connection file.

Example: Remote into serverXYZ -->  mstsc /v serverXYZ

MSRA is the command-line counterpart to Windows Remote Assistance.  There are ton of options for this command (type msra /? for a list of them), but /offerra is the most commonly used of them.

Example: Initiate a Remote Assistance offer to the user on computer "fubar5"...
msra /offerra fubar5

You can go crazy with msra and invoke email invitations, password protection on assistance offers, and much more.

Conclusion

There are obviously many more command-line tools available on Windows 8 and Windows Server 2012 I could have included.  Some that come to mind, which I also use quite often, include MSIEXEC, WEVTUTIL, WBADMIN, WMIC, OPENFILES, FTYPE, DRIVERQUERY, REGINI and FINDSTR.  I won't argue that there aren't better alternatives outside of what comes built into Windows, even many that are "free", but it's nice that these still exist for times when you need them.

Cheers!

Saturday, December 29, 2012

Top 20 Commands Every Windows 7/8 Server 2008 / 2012 Administrator Should Know

TechRepublic posted a list of "10 Windows 7 Commands Every Administrator Should Know", which is very good, and it includes the following:
  1. sfc
  2. sigverif
  3. driverquery
  4. nslookup
  5. ping
  6. pathping
  7. ipconfig
  8. repair-bde
  9. tasklist
  10. taskkill
I would have combined 9 and 10 with a "/" delimiter and added (at least) "reg.exe".  I mean, most administrators use it much more frequently, and with more urgency, than pathping or repair-bde.  Not to discount the value of those two, but there are others that really should be included. I guess I would have probably named that list "10 Windows 7 Commands That Would Be Helpful for Administrators To Know".  A little longer obviously, so how about "10 neat-o Windows Commands"?

In any case, I know this doesn't fit the "top 10" format, but maybe a "top 20" would be more suitable?  I could've just said to open a CMD console and type "HELP" and press Enter.  That will display a summary of CLI commands which are all extremely useful in particular situations.  But that would be un-administratively lazy of me, so I picked out ten of them to use for my add-on list.  For each command, just enter it with a trailing "/?" or "/help" or "-help" or "-?" (Microsoft is so standardized on the dash-or-slash thing).
  1. reg
    • For adding, editing, deleting, importing, exporting, loading and unloading items in the Registry
  2. cacls / icacls
    • For viewing and modifying ACL's (security descriptors / permissions settings) on Files and Folders.
  3. regini
    • For managing ACL's on Registry keys
  4. set
    • For viewing environment variable assignments, as well as assigning new variable/values
  5. shutdown
    • For initiating a shutdown, restart or logoff on a local, or remote, computer
  6. netsh
    • For viewing and managing network adapter and firewall configuration settings
  7. msg
    • For sending CLI alerts to other users or computers over the network (replaces the older "net send")
  8. schtasks
    • For viewing and managing (create, modify, enable/disable, delete) Scheduled Tasks
  9. diskpart
    • For viewing and managing logical disk partitions
  10. systeminfo
    • For displaying computer properties and configuration settings
Regardless, both lists are worth tucking away in your brain if you "manage" Windows clients and/or servers for a living.  Even if you do it as a hobby it's not going to hurt.  The list could easily go on and on.  I didn't include WMIC or PowerShell, which some would argue are equally, or more, important than these legacy CLI tools.

Sunday, April 29, 2012

Project Taphouse

There's not really a Project called "Taphouse", at least not that I'm working on.  But I'm calling it that because I can't really discuss what it's really for or for whom it is being built.  However, it has been (and still is) an interesting project.  It's forced me to drill into Google for lots of command goodies I knew about, but hadn't used in a long time.  Many I hadn't had to use in the way I'm using them now either.  So I thought I'd share some of this in case it's helpful to others.

Here's the basis of the requirement:

The Requirements

"Mobile tablets or laptops will be used to collect inventory data from remote locations using a wireless handheld barcode scanner device.  The remote locations will not always have accessible WiFi, nor a reliable 3G or 4G signal.  Further, testing at locations that have 4G LTE coverage indicates excessive battery drain when using active LTE communication.  Requesting a client-based inventory collection tool that can download configuration updates, as well as upload inventory data, but only when attached to the base network.  Material costs must be kept to absolute minimum."

This led to five minutes of head-scratching, a little Google searching, and finally an "a-ha!" moment:

A local web app using a local database.  The web app will offer the means for capturing inventory scan data, manual entry (when needed), and provide upload/download capability when connectivity allows.

The Ingredients
  1. Windows 7 tablet or laptop
  2. Local IIS instance and virtual directory configuration (windows authentication, disable anonymous authentication, to allow tracking of entries by logged on user)
  3. ASP or ASP.NET web app
  4. SQL Server 2008 R2 Express
  5. Coffee
  6. Sugar snacks
  7. Bad music
(Note: steps 2, 3, 4 can be done in any order, but it helps to move step 5 to step 1 sometimes)

The Deliverable
  1. A packaged installation that can be easily deployed to laptops or tablets, either manually, or via Configuration Manager advertisement, to enable user to begin capturing inventory data at remote locations in the field.
The Chunks
  • Step 1 is easy enough.  
  • Step 2 was interesting.  First I used the DISM command to install and configure IIS, the necessary component features, and Windows Authentication.
  • Step 3 involves creating the virtual directory target folder, copying in the web app content files, and then using APPCMD to create and configure the web site and virtual folder settings
  • Step 4 involves creating a configuration (response) file for installing SQL Express 2008 R2 to allow for silent installation on other computers.
Install and Configure IIS features

dism /Online /Enable-Feature /FeatureName:IIS-WebServerRole
dism /OnLine /Enable-Feature /FeatureName:IIS-WebServer
dism /OnLine /Enable-Feature /FeatureName:IIS-ApplicationDevelopment
dism /OnLine /Enable-Feature /FeatureName:IIS-ISAPIExtensions
dism /OnLine /Enable-Feature /FeatureName:IIS-ASP
dism /OnLine /Enable-Feature /FeatureName:IIS-WebServerManagementTools
dism /OnLine /Enable-Feature /FeatureName:IIS-Security
dism /OnLine /Enable-Feature /FeatureName:IIS-WindowsAuthentication

Create Virtual Folder


I created the folder "inventory" beneath "c:\inetpub\wwwroot", but you could put it anywhere really.  The main thing is to poing the "/PhysicalPath:" parameter to the appropriate location.  The APPCMD command is easy to use for creating and configuring the virtual directory.  For this project, I'm building the virtual directory under the Default web site.

appcmd add vdir /app.name:"Default Web Site/" /path:/inventory /physicalPath:c:\inetpub\wwwroot\inventory

appcmd set config "Default Web Site" /section:windowsAuthentication /enabled:true /commit:apphost

appcmd set config "Default Web Site" /section:anonymousAuthentication /enabled:false /commit:apphost

Install SQL Server 2008 R2 Express

Actually, the first step is to launch the installer (.exe) from a CMD console using /Action=Install /UIMode=Normal  - This enables the "Ready to Install" step in the left-hand vertical list of steps shown in the installation dialog.  For whatever reason, if I simply double-click the .exe and run the installation "normally" it doesn't show this feature.  You need the "Ready to Install" feature because it's the only place the shows the path to the "ConfigurationFile.ini" response file it creates, and allows you to abort a "real" installation at the final step and keep the .INI file.

Once you have the .INI, the CMD syntax for using it is pretty simple, but you still need to make some very minor modifications to the .INI first.

INI modifications

Add:  IACCEPTSQLSERVERLICENSETERMS=1
Change:  QUIETSIMPLE to "True"
Change:  SECURITYMODE to "SQL"  (you don't have to do this, but I prefer to)
Add:  SAPWD=[enter a strong password here]
Change:  TCPENABLED to "1"
Change   NPENABLED to "1"

You could set QUIET="True" for no dialog display, but I like to see some progress since it's pretty slow and pauses a few times along the way.

The installation syntax (assumes both files are in the same folder):

SQLEXPRWT_x86_ENU.exe /ConfigurationFile=ConfigurationFile.ini


But wait - There's more!


After installing the database, I still need to automate the setup of the database schema, create tables, users and grant permissions.  I created some T-SQL scripts and saved them in a folder.  Then I use the SQLCMD command to execute them using the default "sa" user account (note that I've replaced the actual password with "**" below, but you have to specify the actual password)


cd "\Program Files\Microsoft SQL Server\100\Tools\Binn"
sqlcmd -U sa -P ** -S %ComputerName%\INVENTORY -i 1_create_database.sql -o "%temp%\1_sql.log"
sqlcmd -U sa -P ** -S %ComputerName%\INVENTORY -i 2_create_login.sql -o "%temp%\2_sql.log"
sqlcmd -U sa -P ** -S %ComputerName%\INVENTORY -i 3_create_user.sql -o "%temp%\3_sql.log"
sqlcmd -U sa -P ** -S %ComputerName%\INVENTORY -i 4_create_table.sql -o "%temp%\4_sql.log"
sqlcmd -U sa -P ** -S %ComputerName%\INVENTORY -i 5_grant_user_privs.sql -o "%temp%\5_sql.log"
sqlcmd -U sa -P ** -S %ComputerName%\INVENTORY -i 6_sample_data.sql -o "%temp%\6_sql.log"

As an example of the T-SQL script, this is "1_create_database.sql" taken from the project at build 3...

( NAME = N'Inventory', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL10_50.INVENTORY\MSSQL\DATA\Inventory.mdf' , SIZE = 2048KB , FILEGROWTH = 1024KB )
 LOG ON
( NAME = N'Inventory_log', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL10_50.INVENTORY\MSSQL\DATA\Inventory_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)
GO
ALTER DATABASE [Inventory] SET COMPATIBILITY_LEVEL = 100
GO
ALTER DATABASE [Inventory] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [Inventory] SET ANSI_NULLS OFF
GO
ALTER DATABASE [Inventory] SET ANSI_PADDING OFF
GO
ALTER DATABASE [Inventory] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [Inventory] SET ARITHABORT OFF
GO
ALTER DATABASE [Inventory] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [Inventory] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [Inventory] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [Inventory] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [Inventory] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [Inventory] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [Inventory] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [Inventory] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [Inventory] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [Inventory] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [Inventory] SET  DISABLE_BROKER
GO
ALTER DATABASE [Inventory] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [Inventory] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [Inventory] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [Inventory] SET  READ_WRITE
GO
ALTER DATABASE [Inventory] SET RECOVERY SIMPLE
GO
ALTER DATABASE [Inventory] SET  MULTI_USER
GO
ALTER DATABASE [Inventory] SET PAGE_VERIFY CHECKSUM 
GO
USE [Inventory]
GO
IF NOT EXISTS (SELECT name FROM sys.filegroups WHERE is_default=1 AND name = N'PRIMARY') ALTER DATABASE [Inventory] MODIFY FILEGROUP [PRIMARY] DEFAULT
GO

And, here' an example of the T-SQL script, "5_grant_user_privs.sql" taken from the project at the same build...

use [Inventory]
GO
GRANT DELETE ON [dbo].[AuditInventory] TO [InvUser]
GO
use [Inventory]
GO
GRANT INSERT ON [dbo].[AuditInventory] TO [InvUser]
GO
use [Inventory]
GO
GRANT SELECT ON [dbo].[AuditInventory] TO [InvUser]
GO
use [Inventory]
GO
GRANT UPDATE ON [dbo].[AuditInventory] TO [InvUser]
GO
use [Inventory]
GO
GRANT DELETE ON [dbo].[Collections] TO [InvUser]
GO
use [Inventory]
GO
GRANT INSERT ON [dbo].[Collections] TO [InvUser]
GO
use [Inventory]
GO
GRANT SELECT ON [dbo].[Collections] TO [InvUser]
GO
use [Inventory]
GO
GRANT UPDATE ON [dbo].[Collections] TO [InvUser]
GO

Conclusion

I haven't described the download and upload aspects yet, but I will in the near future.  Those features are interesting in and of themselves.  But for now, hopefully this will keep you entertained (or put you fast asleep).

As I've said many times before: Microsoft gives you tons of goodies to help automate almost any task.  The combination of silent installation capabilities, scripts, commands like DISM, APPCMD, SQLCMD, and the ability to string it all together in a simple BAT script, opens the door to unlimited possibilities.  You can wrap all this in a nice .MSI using InstallShield as well, but I wanted to show that it's possible to do all this with absolutely ZERO cash spent on software product licensing (besides Windows itself).  One final note, if you wrap all this in a script, be sure to run the script using "Run as Administrator".

Cheers!


Monday, April 18, 2011

Script Tip of Day: NET HELPMSG

The next time you see an error shot back at you from a script or command console request and wonder what the number means, try using NET HELPMSG X (where X is the number)

For example: net helpmsg 1619 (one of my favorite msiexec errors)…

This installation package could not be opened.  Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.

(by the way, the most common causes for this irritating error are either a bad path+filename request sent to the msiexec parameter inputs, or the file/folder permissions are blocking access)

No, this isn't a new feature. It's one of those things that's been around forever but everyone forgets about until it's rediscovered.  So, just in case you forgot about it, here you go. Smile

Thursday, December 16, 2010

Systems Management Interfaces

I'm sure I'm missing a bunch of other items, but this is a rough start anyway.  I was thinking of what "things" a system admin deals with most often, as it pertains to local vs remote management of each item.  The two that bother me most are Power Plans and Scheduled Tasks.  I sure hope Microsoft decides to clean those up within WMI.  On an even more grandiose delusion I have: I'd love to see them standardize their command syntax and syntactical structures.  Just compare the SC, SCHTASKS and POWERCFG commands (use /? for each).  Holy crap!   And the first person who chimes with "PowerShell is the standard command structure…": Wrong!  It's a bandaid on an amputated leg.  You don't add tools to fix a problem.  You replace them.  It's called efficiency.  I'm cranky tonight.  Going for a walk in the icy slush, which makes me even crankier because cold weather SUCKS!

  COMMAND REMOTE IMPORT EXPORT WMI (root/) WMIC
Scheduled Tasks SCHTASKS YES YES YES ? JOB
Services SC YES NO NO CIMV2, Win32_Service SERVICE
Registry REG YES YES YES DEFAULT, StdRegProv REGISTRY
Event Logs WEVTUTIL YES YES YES CIMV2, Win32_NTLogEvent NTEVENT
Power Plans POWERCFG NO YES YES CIMV2\Power -
Computer Serial Number - - - - CIMV2, Win32_SystemEnclosure SYSTEMENCLOSURE
Drive Mappings NET USE NO NO NO CIMV2, Win32_LogicalDisk NETUSE
Shared Folders NET SHARE YES NO NO CIMV2, Win32_Share SHARE

Friday, December 3, 2010

REG.exe vs REG.exe

I don't know this never hit me before today, but REG.exe got a shot of steroids after Windows XP.  The changes are awesome and I have become so comfortable with how it behaves on Windows 7 that I forgot that /F wasn't available on XP.  Damn if that isn't a powerful little feature.

WINDOWS XP

C:\>reg query /?
 
Console Registry Tool for Windows - version 3.0
Copyright (C) Microsoft Corp. 1981-2001.  All rights reserved
 
 
REG QUERY KeyName [/v ValueName | /ve] [/s]
 
  KeyName    [\Machine\]FullKey
    Machine - Name of remote machine,  omitting defaults to the current machine Only HKLM and HKU are available on remote machines
    FullKey  - in the form of ROOTKEY\SubKey name ROOTKEY  [ HKLM | HKCU | HKCR | HKU | HKCC ]
    SubKey  - The full name of a registry key under the selected ROOTKEY
  /v  query for a specific registry key ValueName  - The name, under the selected Key, to query if omitted, all values under the Key are queried
  /ve query for the default value or empty value name <no name>
  /s  queries all subkeys and values
 
Examples:
 
  REG QUERY HKLM\Software\Microsoft\ResKit /v Version
    Displays the value of the registry value Version
 
  REG QUERY HKLM\Software\Microsoft\ResKit\Nt\Setup /s
    Displays all subkeys and values under the registry key Setup
 
 
WINDOWS 7
 
C:\ >reg query /?
 
REG QUERY KeyName [/v [ValueName] | /ve] [/s] [/f Data [/k] [/d] [/c] [/e]] [/t Type] [/z] [/se Separator]
 
  KeyName  [\\Machine\]FullKey
           Machine - Name of remote machine, omitting defaults to the current machine. Only HKLM and HKU are available on remote machines
           FullKey - in the form of ROOTKEY\SubKey name
                ROOTKEY - [ HKLM | HKCU | HKCR | HKU | HKCC ]
                SubKey  - The full name of a registry key under the selected ROOTKEY
 
  /v       Queries for a specific registry key values.  If omitted, all values for the key are queried.
 
           Argument to this switch can be optional only when specified along with /f switch. This specifies to search in value names only.
 
  /ve      Queries for the default value or empty value name (Default).
 
  /s       Queries all subkeys and values recursively (like dir /s).
 
  /se      Specifies the separator (length of 1 character only) in data string for REG_MULTI_SZ. Defaults to "\0" as the separator.
 
  /f       Specifies the data or pattern to search for.  Use double quotes if a string contains spaces. Default is "*".
 
  /k       Specifies to search in key names only.
 
  /d       Specifies the search in data only.
 
  /c       Specifies that the search is case sensitive.  The default search is case insensitive.
 
  /e       Specifies to return only exact matches.  By default all the matches are returned.
 
  /t       Specifies registry value data type.
           Valid types are:   REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, REG_DWORD, REG_QWORD, REG_BINARY, REG_NONE
           Defaults to all types.
 
  /z       Verbose: Shows the numeric equivalent for the type of the value name.
 
Examples:
 
  REG QUERY HKLM\Software\Microsoft\ResKit /v Version
    Displays the value of the registry value Version
 
  REG QUERY \\ABC\HKLM\Software\Microsoft\ResKit\Nt\Setup /s
    Displays all subkeys and values under the registry key Setup  on remote machine ABC
 
  REG QUERY HKLM\Software\Microsoft\ResKit\Nt\Setup /se #
    Displays all the subkeys and values with "#" as the seperator  for all value names whose type is REG_MULTI_SZ.
 
  REG QUERY HKLM /f SYSTEM /t REG_SZ /c /e
    Displays Key, Value and Data with case sensitive and exact occurrences of "SYSTEM" under HKLM root for the data type REG_SZ
 
  REG QUERY HKCU /f 0F /d /t REG_BINARY
    Displays Key, Value and Data for the occurrences of "0F" in data  under HKCU root for the data type REG_BINARY
 
  REG QUERY HKLM\SOFTWARE /ve
    Displays Value and Data for the empty value (Default)  under HKLM\SOFTWARE

Monday, November 8, 2010

Chart of the Day: Raising CMD Script Errors

cmd

If I really need to explain this chart, then it means one of the following:

A) You have no idea what I'm talking about anyway

B) You don't care

C) You have no idea and don't care

D) Any of the above

Thursday, January 7, 2010

CLI vs GUI – Round, uhhhhh, 427,300,405 ?

So I took my semi-frequent stroll over to the UNIX guys on the other side of our office from where us civilized, well-fed Windows nerds reside.  I like them enough.  They’re good folks and enjoy a good joke.  But I had to chuckle when I noticed all their Solaris and AIX monitors had a GUI desktop with multiple Terminal consoles open and command text running amok.  I smiled and asked “so, why don’t you just boot into a pure CLI instead?”  I got no verbal answer, just a smirk or two.  So I continued on: “so…., you guys find it helpful to jump between the CLI windows by way of them floating around in a GUI?”  I got a couple of laughs, but man, I walked away feeling like I won the lottery.

Thursday, August 20, 2009

Creating Windows Event Log Entries with Scripting

KixTart: LOGEVENT

LOGEVENT (type, ID, message, target, source)

Examples:

$=LogEvent(4, 1, “This is just a user-defined event”, “”, “CustomEvent”)

$=LogEvent(1, 1, “Login script failed on client @wksta”, @LSERVER, “KixTart”)

Limitations:  You can only write to the Application log.
Advantages: You can invoke this without having elevated permissions.  You can submit events to remote computers (if permissions allow)

Windows Vista/7: EVENTCREATE

EVENTCREATE [/S system [/U username [/P [password]]]] /ID eventid
            [/L logname] [/SO srcname] /T type /D description

Examples:

EVENTCREATE /T ERROR /ID 100  /L APPLICATION /D "This is just a user-defined event"

EVENTCREATE /S Server123 /T ERROR /L APPLICATION /D “This is a custom event”

Limitations: It must be invoked with administrative permissions.  It requires the command shell, which is minimal overhead.
Advantages: Can write to all of the event logs (System, Application, etc.).  It can write to local and remote event logs (if permissions allow)

VBScript: LOGEVENT

object.LogEvent(intType, strMessage [,strTarget])

Examples:

Set objShell = CreateObject(“Wscript.Shell”)
cn = objShell.ExpandEnvironmentStrings(“%computername%”)
objShell.LogEvent 1, “This is a custom ERROR message”
objShell.LogEvent 1, “Error on computer “ & cn, “MyServer”

Limitations: It can only write to the Application log
Advantages: Compared to the other options available: none.

PowerShell: WriteEntry

$evtLog = New-Object –type System.Diagnostics.Eventlog –argumentlist Application
$evtLog.Source = “Custom Event”
$evtLog.WriteEntry(“This is a custom Error even”, “Error”)

$cn = [environment]::GetEnvironmentVariable(“computername”)
$evtLog = New-Object –type System.Diagnostics.Eventlog –argumentlist Application, MyServer
$evtLog.Source = $cn
$evtLog.WriteEntry(“Error occurred on $cn”, “Error”)

Wednesday, May 13, 2009

Playing With Fire

That's usually the first thing anyone says to someone when they're answering the question: "What is the 'registry'?"  They say "it's an evil box of destruction that will destroy your computer and all of mankind.  You're playing with fire!"  Ok, I think I actually heard someone say that once.  It was probably me.

Today's walk down destruction lane will focus on the registry.  And because I try to make everyone happy (and end up making nobody happy as a result) will pain the picture with not one, not two, not even three, but FOUR languages!  Amazing!  How the *$(^^*#$ does he do that?!  Pssstt.  Come closer... I have to whisper this.... it's called... Google.

I've been writing scripts for almost 20 years in a variety of languages, but I still look for the easy way out.  That's what scripting is all about: saving time and saving work.  Programmers look to make something awe-inspiring.  Scripters look to make things that free them up to drink more beer and make jokes about programmers.  Scripters also get to the bar earlier and therefore finish off the snacks before the worn-out programmers show up.  You know: while you're compiling, I'm doing something more fun.

Enough of that gibberish.  It'll melt your mind.  Here are four ways to query a registry key and pull all the sub-keys and values beneath it.  They aren't all purely recursive.  Two of them are, two of them aren't.  The two that are can be considered completely cheating, but who cares.  The VBScript and KiXtart examples are one-deep, not exhaustively recursive.  The CMD and PowerShell examples are.  Let's start with the ugly first, but please read the comments at the end as well?

VBScript:

Option Explicit

' Adapted from ActiveXperts registry script library...
' Click Here

Const strComputer = "."

Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_USERS = &H80000003
Const REG_SZ = 1
Const REG_EXPAND_SZ = 2
Const REG_BINARY = 3
Const REG_DWORD = 4
Const REG_MULTI_SZ = 7

Dim StdOut, oReg
Set StdOut = WScript.StdOut

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")

EnumSubkeys HKEY_LOCAL_MACHINE, "SYSTEM\CurrentControlSet\Services"

Sub EnumSubkeys(hive, parentkey)
Dim subkey, arrSubKeys
Wscript.Echo "PARENTKEY: " & parentkey
oReg.EnumKey hive, parentkey, arrSubKeys
For Each subkey In arrSubKeys
EnumValueTypes hive, parentkey & "\" & subkey
Next
End Sub

Sub EnumValueTypes(hive, strKeyPath)
Dim i, x, ValueName, arrValueNames, arrValueTypes, strValue, arrValues
Wscript.Echo "SUBKEY: " & strKeyPath
oReg.EnumValues hive, strKeyPath, arrValueNames, arrValueTypes
If VarType(arrValueNames) > 8192 Then
For i=0 To UBound(arrValueNames)
ValueName = arrValueNames(i)
Wscript.Echo vbTab & "Value Name.: " & ValueName
Select Case arrValueTypes(i)
Case REG_SZ
Wscript.Echo vbTab & "Data Type..: REG_SZ"
oReg.GetStringValue hive, strKeyPath, ValueName, strValue
Wscript.Echo vbTab & "Value......: " & strValue
Wscript.Echo
Case REG_EXPAND_SZ
Wscript.Echo vbTab & "Data Type..: REG_EXPAND_SZ"
oReg.GetExpandedStringValue hive, strKeyPath, ValueName, strValue
Wscript.Echo vbTab & "Value......: " & strValue
Wscript.Echo
Case REG_BINARY
Wscript.Echo vbTab & "Data Type..: REG_BINARY"
oReg.GetBinaryValue hive, strKeyPath, ValueName, strValue
If VarType(strValue) > 8192 Then
For x = 0 to UBound(strValue)
Wscript.Echo vbTab & "Value......: " & strValue(x)
Next
End If
Wscript.Echo
Case REG_DWORD
Wscript.Echo vbTab & "Data Type..: REG_DWORD"
oReg.GetDWordValue hive, strKeyPath, ValueName, strValue
Wscript.Echo vbTab & "Value......: " & strValue
Wscript.Echo
Case REG_MULTI_SZ
Wscript.Echo vbTab & "Data Type..: REG_MULTI_SZ"
oReg.GetMultiStringValue hive, strKeyPath, ValueName, arrValues
For each strValue in arrValues
Wscript.Echo vbTab & "Value......: " & strValue
Next
Wscript.Echo
End Select
Next
Else
Wscript.Echo vbTab & "Data Type..: " & VarType(arrValueNames)
End If
End Sub




KiXtart:





; Adapted from fEnumKey() by Howard A. Bullock
; Click Here

Break ON

$regkey = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services"
$=EnumSubkeys($regkey)

Function EnumSubkeys($parentkey)
Dim $index, $error, $x
$index = 0
Dim $keyname[$index]

If KeyExist($parentkey)
Do
$x = EnumKey($parentkey, $index)
$error = @error
If Not $error And $index > Ubound($keyname)
ReDim Preserve $keyname[$index]
EndIf
If Not $error
$keyname[$index] = $x
$index = $index + 1
$=EnumKeyValues("$parentkey\$x")
EndIf
Until $error
Else
$keyname[0] = ""
Exit 2
EndIf
EndFunction

Function EnumKeyValues($subkey)
Dim $i, $valuename, $v, $vname, $rval, $rtyp
$i = 0
Dim $vname[$i]
? "SUBKEY: $subkey"
Do
$v = EnumValue($subkey, $i)
$err = @error
If Not $err And $i > Ubound($vname)
ReDim Preserve $vname[$i]
EndIf
If Not $err
$vname[$i] = $v
$rval = ReadValue($subkey, $v)
$rtyp = ReadType($subkey, $v)
$i = $i + 1
? Chr(9)+"ValueName..: $v"
? Chr(9)+"Value......: $rval"
? Chr(9)+"Data Type..: $rtyp"
?
EndIf
Until $err
EndFunction




PowerShell:





dir hklm:system\currentcontrolset\services -recurse -ea silentlycontinue




CMD Shell:





reg query HKLM\SYSTEM\CurrentControlSet\Services /s 



Comments:

You might have noticed that the last two examples are just a teensy-weensy bit shorter than the first two.  Just a little.  That's not really a fair comparison.  Comparing the brevity of languages is a slippery slope.  Because they can be described as smoke-and-mirrors in some respects.  Each "language" (or "engine" if you will) comes with a particular (singular or community based) mindset regarding what belongs in the "core" versus what should be left to YOU to add-on.



PowerShell derives much of its potential from cmdlets, which are modular functions which collectively fill-out the PowerShell capability set.  You could do very similar things with KiXtart UDF's (User Defined Functions), which are identical in many respects.  The difference beneath that layer is that PowerShell derives from the .NET services layer, while KiXtart derives from an aggregate of COM and WMI interfaces.  The results almost identical in most respects, but there is only major difference overall: KiXtart is procedural, while PowerShell is object-oriented.  Does that mean that KiXtart is *always* procedural and PowerShell is *always* object oriented?  No.  Cars aren't always cars either.



So, basically, essentially, in other words, and so on, you could produce an almost identical functional expression with KiXtart that you see with PowerShell by simply building (or downloading) a UDF and it would (or could) be as brief and simple.  The REG.EXE command (CMD Shell example) is a compiled, single-purpose executable, rather than a scripting engine or environment.  I included it simply to show that PowerShell is but one way to screw up your registry with the fewest keystrokes.  (A dangerous combination if you drink beer AND a Red Bull in the same hour as you start playing with that.)



As I mentioned in an earlier post, there are trade-offs to each and every "tool" you use.  Some will be faster and easier at some things, but harder to lug around.  A good example of this is CMD shell, which is already pervasive, versus PowerShell, which is still in its infancy of pervasiveness.  Then there's KiXtart which is like a suitcase with a nuclear bomb in it.  Powerful, yet completely portable and fairly lightweight.  PowerShell on the other hand is not lightweight, and requires not only .NET Framework, but it's own installation, in order to crank it up and start using it.  But once it's roots are planted, it rocks.



Well, the goal of this article was to show some simple comparisons and discuss some of the differences between them.  I hope this helps!  Cheers!

Saturday, June 14, 2008

A Gradual Return to DOS

After months of using Windows Server 2008 and watching as many (most) of the Microsoft infrastructure arsenal began the migration to PowerShell, it seems that the net effect is that everything is returning to where it began: A GUI on top of a command shell.

Many people mistakenly think that it's always been that even through Windows NT, 2000, XP and into Vista. But that's dead wrong. NT4 was the turning point where the GUI (or GDI underpinnings) were the kernel master process and CMD was a child process hanging off of it like Remora on a Shark. This arrangement has remained in place, in fact become more tightly engaged with the NTOS kernel, that to see it turning around to PowerShell is really quite a surprise. I don't think it was the original intent when Jeffrey Snover and the gang started whiteboarding this thing. I think it was first envisioned to be a replacement for CMD.exe and many interviews I've seen seem to back that up.

Then came Exchange 2007 and the announcement it would be built "on top of" PowerShell. That got a little attention, but then came WS08 Core and the talk about getting PowerShell into that environment. Now with the additional announcements that System Center products (such as SCVMM, SCDPM and SCOM) would not only support PowerShell, but that it would be tightly integrated, were enough to stick a snake prod into the hind parts of EMC. Now Virtual Center is making a ton of press with scripting feature announcements, and this is all a good thing. Competition keeps it all working for us as customers. Every single product or service I've seen that lacked real competition ends up sucking horribly. I dare anyone to show me one product that really rocks which doesn't have some competition keeping it on it's toes. It's a part of nature.

I doubt that Windows 7 or Windows Server 7 will be built "on top of" PowerShell, but who of us really knows? With Steven Sinofsky in charge, it's going to be much quieter on the W7 front. If Sinofsky had his way, it would be more baren of "news" than anything Apple would dream of in the information restriction camp. I'm pretty sure though that W8 will have significant incorporation of PS features. I'm glad Linux and OSX are doing well, this keeps Microsoft drinking coffee and staying up late. We benefit from all three.