Friday, March 6, 2009
(C:\WINDOWS\IsUninst.exe)Uninstall Softwares with Batch file where you don;t have the msi commands
Tuesday, March 3, 2009
FIND SQL Server Version with SQL Query
SELECT 'SQL Server '
+ CAST(SERVERPROPERTY('productversion') AS VARCHAR) + ' - '
+ CAST(SERVERPROPERTY('productlevel') AS VARCHAR) + ' ('
+ CAST(SERVERPROPERTY('edition') AS VARCHAR) + ')'
-------------------
Thanks,
http://sccm07.blogspot.com/
Thursday, February 26, 2009
SCCM Duplicate System Entries in the Console
SCCM Duplicate System Entries in the Console
If your SCCM console has duplicated System entries in the Console, and you want to find it right? Below is the Query for this issue.
select R.ResourceID,R.ResourceType,R.Name,R.SMSUniqueIdentifier,R.ResourceDomainORWorkgroup,R.Client from SMS_R_System as r full join SMS_R_System as s1 on s1.ResourceId = r.ResourceId full join SMS_R_System as s2 on s2.Name = s1.Name where s1.Name = s2.Name and s1.ResourceId != s2.ResourceId
Tuesday, February 24, 2009
SMS/SCCM Command-line Actions - alternate to right click tools ?
SMS/SCCM Command-line Actions
We can use WMIC tool to run on remote computers and get the client actions as we want
Some examples to trigger SMS/SCCM Client Actions from command line:
Disable Software-Distribution:
WMIC /namespace:\\root\ccm\policy\machine\requestedconfig path ccm_SoftwareDistributionClientConfig CREATE ComponentName="Disable SWDist",Enabled="false",LockSettings="TRUE",PolicySource="local",PolicyVersion="1.0" ,SiteSettingsKey="1" /NOINTERACTIVE
Re-Activate Software-Distribution:
WMIC /namespace:\\root\ccm\policy\machine\requestedconfig path ccm_SoftwareDistributionClientConfig WHERE ComponentName="Disable SWDist" delete /NOINTERACTIVE
Trigger Hardware Inventory:
WMIC /namespace:\\root\ccm path sms_client CALL TriggerSchedule "{00000000-0000-0000-0000-000000000001}" /NOINTERACTIVE
Trigger Software Inventory:
WMIC /namespace:\\root\ccm path sms_client CALL TriggerSchedule "{00000000-0000-0000-0000-000000000002}" /NOINTERACTIVE
Trigger DataDiscoverRecord (DDR) update:
WMIC /namespace:\\root\ccm path sms_client CALL TriggerSchedule "{00000000-0000-0000-0000-000000000003}" /NOINTERACTIVE
Force a FULL HW Inventory on next HW-Inv Schedule:
WMIC /namespace:\\root\ccm\invagt path inventoryActionStatus where InventoryActionID="{00000000-0000-0000-0000-000000000001}" DELETE /NOINTERACTIVE
Repair SMS/SCCM Agent on a remote client:
WMIC /node:%MACHINE% /namespace:\\root\ccm path sms_client CALL RepairClient
Repair a list (all clients listed in clients.txt) of remote SMS/SCCM Agents:
WMIC /node:@clients.txt /namespace:\\root\ccm path sms_client CALL RepairClient
-------------------
Thanks,
http://sccm07.blogspot.com/
VB Script Drive Space Check on list of System
Friday, February 20, 2009
WQL to SQL Query
WQL to SQL
Collections
.SiteID,
Collections.CollectionName,
Collection_Rules.QueryName,
Collection_Rules_SQL.WQL,
Collection_Rules_SQL.SQLFrom
Collections,Collection_Rules, Collection_Rules_SQLWhere
Collections
.CollectionID = Collection_Rules.CollectionIDAND
Collections.CollectionID = Collection_Rules_SQL.CollectionID-------------------Thanks,
http://sccm07.blogspot.com/
Monday, February 16, 2009
SCCM 2007 Right Click Tools latest version available, one can download from the below link
1. Most of the tools that were included in the original SMS Console Additions V1.4
2. The ability to see the computer details and security compliance web reports for a single client inside collections
3. A separate drill down for client logs as well as security update client logs.
4. The ability to check the status of an advertisement with a right click from that advertisement In order to get the client and the advertisement web reports to work you must perform the following.
5. Fixed the right click tools on the "collections" that didn't open a CMD window when running. Also fixed the echo so the results now show up in a command window
6. Will detect the version of the tool installed so re-installation of unnecessary files does not occur when new versions are released
7. Now has an entry in Add Remove Programs which enables un-installation of the program
8. No more hard coding of your site code to get scripts and reports to run correctly
- Detects and uninstalls any previous versions of the tool.
- Right click tool added to the software updates node, but it only works if there is a update list with patches deployed.
- Prefixed each tool with your SCCM site code for easier recognition
- Right click ability on each advertisement that will display three web reports
- Added a prompt to see the CCMsetup.log on the SCCM Client install
- Fixed the Client Action for User Policy Evaluation and Update
- Added all the client actions from the control panel including the Security Updates Scan and Security Updates Deployment Evaluation
- Added an extension to the client tools that will tell you what collection a user or system belongs to.
- Added a web report to show all the advertisements for a certain system.
- CCM and CCMSetup directories now work properly.
- Added the Software Updates Scan Cycle to the Collection root so it runs not just on one client but a whole collection. Requested by a member from the forum community.
- Added Support for Windows 2008 64bit.
- New Tool to Re-run advertisements from a drop down list.
- Added the ability to run client actions from the Query results.
- Fixed issue with script.bat
Thursday, February 12, 2009
SCCM How to make know to unknow
SCCM OSD Error code 80004005
In Build and Captured error "Task Sequence Manager could not resume SMS components. code 80004005 TSManager 2/12/2009 12:15:04 AM 1268 (0x04F4)"
Resolution 1:- Make sure in Task Sequese you have joining to Workgroup. Because sysprep can not be make under joining into domain
Resolution 2:- Check your Network desgin if it is build with Cisco then might be Fast Port opened need to stop this to fix it.. Yep I never find this information microsoft site (I ver bad in searching )but this is the solution What i found.
-------------------
Thanks,
http://sccm07.blogspot.com/
Monday, February 9, 2009
VBSCRIPT For a Copy a Folder
For a Copy a Folder
Dim wShell
strComputer = "."
Set objWMIService = GetObject _
("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
'errReturn = objWMIService.Create _
' ("cmd.exe /c md c:\ups", Null, Null, intProcessID)
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CopyFolder "file://172.20.128.51/sms_uk/Oct 2008\*.*" , "c:\pav\" , OverwriteExisting
Set wShell = CreateObject("WScript.Shell")
'wShell.Run "c:\ups\Election.html"
Const OverwriteExisting = TRUE
Friday, February 6, 2009
Patch Failed to scan and install Error 8024400E
-------------------
Thanks,
http://sccm07.blogspot.com/
Thursday, February 5, 2009
vb script To Clear SCCM / SMS CCM / Cache Folder
on error resume next
dim oUIResManager
dim oCache
dim oCacheElement
dim oCacheElements
set oUIResManager = createobject("UIResource.UIResourceMgr")
if oUIResManager is nothing then
' wscript.echo "Couldn't create Resource Manager - quitting"
wscript.quit
end if
set oCache=oUIResManager.GetCacheInfo()
if oCache is nothing then
set oUIResManager=nothing
' wscript.echo "Couldn't get cache info - quitting"
wscript.quit
end if
set oCacheElements=oCache.GetCacheElements
'wscript.echo "There are " & oCacheElements.Count & " cache elements"
'wscript.echo
' ***** Begin CLEAR CACHE *****
for each oCacheElement in oCacheElements
oCache.DeleteCacheElement(oCacheElement.CacheElementID)
next
' ***** End CLEAR CACHE *****
set oCacheElements=nothing
set oUIResManager=nothing
set oCache=nothing
-------------------
Thanks,
http://sccm07.blogspot.com/
Change Default Power Management settings on Laptop users
powercfg /change "Portable/Laptop" /standby-timeout-ac 30 /standby-timeout-dc 30 /hibernate-timeout-ac 45 /hibernate-timeout-dc 45
powercfg /setactive "Portable/Laptop"
Change Default Power Management settings
powercfg /change "Always On" /monitor-timeout-ac 30 /monitor-timeout-dc 30 /standby-timeout-ac 30
powercfg /setactive "Always On"
-------------------
Thanks,
http://sccm07.blogspot.com/
Wednesday, February 4, 2009
SCCM Query for SCCM Clients Model and Manufactures Name
Select DISTINCT Model0 from Computer_System_DATA
The above one will show all the Models
The below Query will show everything in the Database
Select
* from Computer_system_dataTuesday, February 3, 2009
Use a PSEXEC tool to deploy software on list of systems in text file
-------------------
Thanks,
http://sccm07.blogspot.com/
Saturday, January 31, 2009
How to Install Configuration Manager Clients Using Software Update Point Based Installation
Step:1
To configure an Active Directory Group Policy object to specify the software update point for client installation and software updates
-
Using an editor such as Windows Group Policy editor, open a new or existing Group Policy object.
-
In the Group Policy editor, navigate to Computer Configuration / Administrative Templates / Windows Components / Windows Update, and then open the properties of the setting Specify intranet Microsoft update service location.
-
Click Enabled.
-
In the Set the intranet update service for detecting updates: field, specify the name of the software update point server you want to use, and the port. These must match exactly with the server name format and the port being used by the software update point:
- If the Configuration Manager site system is configured to use a fully qualified domain name (FQDN), specify the server name using FQDN format.
- If the Configuration Manager site system is not configured to use a fully qualified domain name (FQDN), specify the server name using a short name format.
- If the site is in mixed mode and software updates is using the default Web site, the port number is likely to be 80 unless it has been changed.
- If the Configuration Manager site system is configured to use a fully qualified domain name (FQDN), specify the server name using FQDN format.
- Example: http://myactivewsusserver.mydomain.com:8530
or If your WSUS Setup configured on port 80 then the below URL will be placed
-
In the Set the intranet statistics server: field, specify the name of the intranet statistics server you want to use. There are no specific requirements for specifying this server. It does not have to be the same computer as the software update point server, and the format does not have to match if it is the same server.
-
Assign the Group Policy object to the computers on which you want to install the Configuration Manager client and receive software updates.
If the site is in mixed mode and software updates is using a custom Web site, the port number is likely to be 8530 unless it has been changed.
If your WSUS Setup configured on port 8530 then the below URL will be placed
Step:2
To publish the Configuration Manager 2007 client to the software update point
-
In the Configuration Manager console, navigate to System Center Configuration Manager / Site Database / Site Management / <site code> – <site name> / Site Settings / Client Installation Methods.
-
Right-click Software Update Point Client Installation, and click Properties.
-
To enable client installation, select the Enable Software Update Point Client Installation check box.
-
If the client software on the Configuration Manager 2007 site server is a later version than the client version stored on the software update point, the Upgrade Client Package Version dialog box will open. Click Yes to publish the most recent version of the client software to the software update point.
-
To finish configuring the software update point client installation, click OK.
Wednesday, January 28, 2009
SCCM Client failes with Software Updates: WUAHandler.log Error = 0x80070002
OnSearchComplete - Failed to end search job. Error = 0x80070002. WUAHandler 1/28/2009 3:00:15 PM 3380 (0x0D34)
Scan failed with error = 0x80070002. WUAHandler 1/28/2009 3:00:15 PM 3380 (0x0D34)
Tuesday, January 27, 2009
First command to start with Powershell is
First command to start with Powershell is
Get-Help
Power Shell Learning Commands
Power Shell Learning Commands:-
dir -RECURSE
`
Start-Transcript filename.txt
stop-Transcript
I will post to continue this article persistently
Thursday, January 22, 2009
SCCM 2007 / SMS 2003 SQL Package Related Query
-----------------------------------------------------------------------------------------------------------------------------------
SQL Query:-->
-----------------------------------------------------------------------------------------------------------------------------------
To know the package Name and ID
SELECT PackageID, Name
FROM dbo.v_Package
-----------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------
SQL Query:-->
If you want to filter with the package ID then modify the Query to
SELECT PackageID, Name
FROM dbo.v_Package
WHERE (PackageID = 'YourPKGID')
-----------------------------------------------------------------------------------------------------------------------------------
-------------------
Thanks,
http://sccm07.blogspot.com/
Failed to remove package from SMS / SCCM Retired/ Correpted distrubution point
Failed to remove package from a retired distrubution point
Select * from pkgservers where NALpath like '%\\retired DP path\DP$'
Select * from pkgstatus where pkgserver like '%\\retired DP path\DP$'
by runing above two commands verifiy that you have got the correct Correpted DP package ID or not. then if you find it you can safly run the below two commands to delete.
Next delete entries from any of the above tables to the invalid dp share.
Delete from pkgservers where NALpath like '%\\retired DP path\DP$'
Delete from pkgstatus where pkgserver like '%\\retired DP path\DP$'
Wednesday, January 21, 2009
SCCM OSD All Log Files
Log File Name | Description | ||
CCMSetup.log | Provides information about client-based operating system actions. | ||
CreateTSMedia.log | Provides information about task sequence media when it is created. This log is generated on the computer running the Configuration Manager 2007 administrator console. | ||
DriverCatalog.log | Provides information about device drivers that have been imported into the driver catalog. | ||
MP_ClientIDManager.log | Provides information about the Configuration Manager 2007 management point when it responds to Configuration Manager 2007 client ID requests from boot media or PXE. This log is generated on the Configuration Manager 2007 management point. | ||
MP_DriverManager.log | Provides information about the Configuration Manager 2007 management point when it responds to a request from the Auto Apply Driver task sequence action. This log is generated on the Configuration Manager 2007 management point. | ||
MP_Location.log | Provides information about the Configuration Manager 2007 management point when it responds to request state store or release state store requests from the state migration point. This log is generated on the Configuration Manager 2007 management point. | ||
Pxecontrol.log | Provides information about the PXE Control Manager. | ||
PXEMsi.log | Provides information about the PXE service point and is generated when the PXE service point site server has been created. | ||
PXESetup.log | Provides information about the PXE service point and is generated when the PXE service point site server has been created. | ||
Setupact.log Setupapi.log Setuperr.log | Provide information about Windows Sysprep and setup logs. | ||
SmpIsapi.log | Provides information about the state migration point Configuration Manager 2007 client request responses. | ||
Smpmgr.log | Provides information about the results of state migration point health checks and configuration changes. | ||
SmpMSI.log | Provides information about the state migration point and is generated when the state migration point site server has been created. | ||
Smsprov.log | Provides information about the SMS provider. | ||
Smspxe.log | Provides information about the Configuration Manager 2007 PXE service point. | ||
SMSSMPSetup.log | Provides information about the state migration point and is generated when the state migration point site server has been created. | ||
Smsts.log | General location for all operating system deployment and task sequence log events.Log file location:· If task sequence completes when running in the full operating system with a Configuration Manager 2007 client installed on the computer: <CCM Install Dir>\logs· If task sequence completes when running in the full operating system with no Configuration Manager 2007 client installed on the computer: %temp%\SMSTSLOG· If task sequence completes when running in WindowsPE: <largest fixed partition>\SMSTSLOG
| ||
TaskSequenceProvider.log | Provides information about task sequences when they are imported, exported, or edited. | ||
USMT Log loadstate.log | Provides information about the User State Migration Tool (USMT) regarding the restore of user state data. | ||
USMT Log scanstate.log | Provides information about the USMT regarding the capture of user state data. |
-------------------
Thanks,
http://sccm07.blogspot.com/
Tuesday, January 20, 2009
Remote Desktop Cut and Paste does not work
Issue:
When using RDP you may not be able to cut and paste information between your local and remote sessions.
Cause:
The rdpclip.exe processing may not be running on the remote system. Alternatively, the clipboard chain may be incomplete.
Workaround:
Restart the rdpclip.exe process on the remote system.
More Information:
The following article has a good article on Clipboard chaining;
http://blogs.msdn.com/ts/archive/2006/11/16/why-does-my-shared-clipboard-not-work-part-1.aspx
-------------------
Thanks,
http://sccm07.blogspot.com/
Analyzing Windows Kernel Dumps
This post contains information on steps I took to investigate a kernel mode dump with a repeatable 0x7F bugcheck caused on a workstation when printing a specific document to a generic LaserJet 4000 on a remote print server.
After analysing the kernel dump, the problem appeared to be occurring in the kernel-mode GDI win32k.sys driver, and using this information I was able to find a hotfix that did resolve the issue.
I don't pretend to understand a large portion of what was visible in the kanalyze results, but the information that I did glean was enough to point to the hotfix very quickly.
The following steps were taken to analyse the kernel dump created by the stop 0x7F error:
- Install debugging tools, The Kanalyze guide recommends version 6.5.3.8 32-bit (the most recent is dbg_x86_6.9.3.113.msi)
- Install Kanalyze 8.1. The default directory is c:\kktools\kanalyze8.1
- Copy c:\kktools\kanalyze8.1\x86\*.* to the '\Program Files\Debugging Tools for Windows' directory (including the plug-ins subdirectories)
- Run '\Program Files\Debugging Tools for Windows\kanalyze.exe
- Perform a new memory dump
- Type the location of the dump file (usually c:\windows\memory.dmp if a local dump)
- Leave the symbol and binaries path to the HTTP locations (requires Internet access)
- Select 'Show Detail' and then Next
- The crashdump analysis will begin, which can be relatively time consuming (~30 minutes for the small 87MB crashdump of my workstation).
- Perform a new memory dump
- Analysis Summary – The automatically generated summary, providing a best-guess of the potential cause of the crash. Note that in this crash, the AnalysisSummary.txt file shows that the best guess was rdbss.sys – the redirected drive buffering subsystem, used by the SMB mini-redirector.
- Analysis TriageInfo CrashStackInfo – Information on the kernel stack at the time of the crash. For this crash, this information seems more useful, as it shows the GDI bitblt and dithercolor functions being called, followed by a divide by zero trap in the kernel and the bugcheck. This gives quite a bit more information to go on when searching for cause and resolution
- Analysis TriageInfo CrashProcess – The process that caused the crash, in this case, winword.exe, providing information on the memory and processed (useful for other areas in the debug namespace)
- Analysis TriageInfo CrashThread – The thread that caused the crash, in this case, the kernel thread ID and start address space, useful for other areas in the debug namespace
- Analysis Deadlock – Current deadlocks – conflicts between threads trying to exclusively access code. Locks occur constantly, but a deadlock can occur when two or more threads have code locked and are waiting for the other(s) to continue. The deadlock in this scenario is presumed to be a result of the divide by zero kernel error, and not causative
- Root – Provides an interesting overview of the memory allocation of the system, including boot, HAL, non-paged/paged, kernel and usermode address spaces.
The following stack information from the crash dump was what pointed me in the hotfix direction, the bitblt and drvdither calls which resulted in a divide by zero error in the kernel:
+------------+ | | StackLimit = aa1f5000 +------------+ | : | +------------+ | | KernelStack = aa1f85d8 +------------+ /| | | | | : | | | | stack +------------+ growth | | InitialStack = aa1f9000 +------------+ ChildEBP Ret-Addr Called Procedure --------------------------------------------------------------------------- aa1f8984 80596813 nt!KeBugCheck + 14 aa1f89dc 8053d60f nt!Ki386CheckDivideByZeroTrap + 41 aa1f89dc bf903230 nt!KiTrap00 + 83 aa1f8a94 bf81af4d win32k!UMPDDrvDitherColor + 7d aa1f8b24 bf826e70 win32k!bGetRealizedBrush + 2bd aa1f8b3c bf82f869 win32k!pvGetEngRbrush + 1f aa1f8b98 bf805363 win32k!EngBitBlt + 283 aa1f8be8 bf80bd41 win32k!GrePatBltLockedDC + 1ea aa1f8d54 8053c9fa win32k!NtGdiFlushUserBatch + 689 aa1f8d70 aaea754a nt!KiFastCallEntry + ca aa1f8ddc 805411c2 rdbss!RxpWorkerThreadDispatcher + 18a aa1f8de8 00000000 nt!KiThreadStartup + 16
Notes:
- The analysis requires more than a minidump. Use sysdm.cpl Advanced Startup and Recovery Settings to write at least a 'Kernel memory dump', rather than a small / minidump.
- The console can be used to execute plug-in commands, or standard kernel debug commands (eg VIEWCMD or kd !ntsdexts.locks). Either click on the console button, or use the File Command Window menu option on the browser
References
Debugging Tools – v6.5.3.8:
http://msdl.microsoft.com/download/symbols/debuggers/dbg_x86_6.5.3.8.exe
Kernel Memory Space Analyzer Version 8.1
http://www.microsoft.com/Downloads/details.aspx?FamilyID=e84d3b35-63c3-445b-810d-9fed3fdeb13f&displaylang=en
First Step Guide to Kernel Memory Space Analyzer V8.1 (Kanalyze)
http://download.microsoft.com/download/8/3/5/835efd1b-d801-4aa5-84ab-c4809fb493f4/Kanalyze%20First%20Step%20Guide%20V8.1.ppt
BitBlt
http://msdn.microsoft.com/en-us/library/ms532278(VS.85).aspx
DrvDitherColor
http://msdn.microsoft.com/en-us/library/ms793395.aspx
Debugging Deadlocks (No Ready Threads)
http://msdn.microsoft.com/en-us/library/cc267852.aspx
Error message when you try to print after you install the GDI security update 925902: "Stop 0x0000007F"
http://support.microsoft.com/kb/935843
-------------------
Thanks,
http://sccm07.blogspot.com/
This was a basic overview of the ‘for’ command
This was a basic overview of the 'for' command
This is the first in a series of posts containing information on what I consider the building blocks to automate repetitive tasks at the Windows command-line. These components are the for, find, findstr, set, if and echo commands, control files used for data input, combined with errorlevels, command concatenation, nested loops and if/then/else constructs.
Described in this post is the 'for' command, the most important component in command-line automation. This command provides several methods of looping through a list, and running a command against each element in that list. Use the 'for /?' to get Microsoft help on this command.
Using the 'for' command with one of the syntaxes below provides many benefits, including:
- Repeatability – If you save the command you run, it can be re-run several or hundreds of times
- Change control and testing – It's easy to record what you are planning and simple to run the same commands in a test-lab environment. The output of commands can also be redirected to file, making accountability much easier. Using control files also provides a straightforward method of recording the targets of various actions, knowing that you have one master list, and do not risk accidentally missing an entry.
- Documentation – Implementation using a series of commands very easily translates to an as-built document – with the added benefit of providing a quicker DR process.
- Efficiency – Even though designing the command for the first run may not be as quick as using the GUI, every time after that will usually be much quicker, and previous commands can often be quickly adapted to new tasks.
You can use the 'for' command to:
Process a set of filenames or string literals
The filenames or literals can either be directly named in a space-separated set, or you can use wildcards to process more than one file. For example:
for %i in (*.txt) do echo %i
for %i in (test1.txt test2.txt) do echo %i
For example, I would use this syntax if I'm trying to:
Quickly execute something against a group of machines, eg ping each machine:
for %i in (server1 server2 server3 server4) do ping -n 1 %i
Process a series of data files that I have created from another process, eg this uses the regview utility to export the registry entries modified by *.pol files into *.txt:
for %i in (*.pol) do regview %i > %i.txt
Quickly execute the same command with a different variable, eg use the setprinter utility to view all levels of configuration for the specified printer (you could also use for /l in this example):
for %i in (0 1 2 3 4 5 6 7 8 9) do setprinter -show \\server\printer %i
Process a set of directories
The directory names can either be directly named in a space-separated set, or you can use wildcards to process more than one directory. For example:
for /d %i in (%windir%\*) do echo %i
for /d %i in (c:\temp c:\windows) do echo %i
I would use this syntax if I'm trying to do something with each top-level directory, for example:
Report or set ACLs:
for /d %i in (%rootDir%\*) do icacls %i /save %~ni.txt
Rename all the top-level directories to start with a new prefix:
for /d %i in (%rootDir%\*) do ren %i New-%~ni
Process the contents of a text file, line by line
The contents of a file – which I usually refer to as a control file – can be read line-by-line and your command would be run once for each line, substituting tokens from the control file. This provides unlimited capability – construct a control file through any means available and you can then process the entries one-by-one and run a command against that entry.
Note that in Vista at least, just a LF is enough to separate the lines, rather than the Windows standard CR+LF.
For example, assuming you have a control file with a list of servers or workstations, you could:
Lookup the IP address of each machine:
for /f %i in (test.txt) do nslookup %i
Ping each machine:
for /f %i in (test.txt) do ping %i
Remote dir of each machine:
for /f %i in (test.txt) do dir \\%i\c$
I use this constantly to run a command against multiple AD objects, machines, printers, or other network devices, whether the command queries or checks something, or makes a change to each device.
Process the results of a command, line by line
The results of almost any command can be used as the looping mechanism for a 'for /f' command, providing an in-memory control file. For example, you could:
Find the local hostname and then nslookup the computer (you could also use %computername% for this):
for /f %i in ('hostname') do nslookup %i
Query the local Active Directory for a list of DCs (server records) and lookup the IP of each DC:
for /f %i in ('dsquery server -o rdn') do nslookup %i
Recursively enumerate a path
It's possible to recursively enumerate files or directories from a specified starting location, passing each to the body of the for loop. This provides a rudimentary search and response facility, allowing you to traverse a tree looking for objects of a particular type – and then execute something for each found.
For example, you could search from the root of C: for *.txt files, and then report the filename and size (you would just use dir /s if all you wanted to do was echo)
for /r c:\ %i in (*.txt) do echo %i %~zi
Step through a sequence of numbers and execute for each
The 'for /l' option allows stepping through a sequence of numbers, passing the number as a parameter to the body of the 'for' loop.
I don't use this method very often, but it would be another method to the setprinter command above:
for /l %i in (1,1,9) do setprinter -show \\server\printer %i
Variable Expansion
When using 'for', 'for /f' and 'for /d' variable references can also be modified to return substrings or additional information. Note that when using 'for /f', most of these only make sense if you are processing lists of files or directories, but if you did have a control file with files/paths variable expansion does work as expected.
This substitution can be very useful, particularly when constructing parameters to pass to the command in the body of the 'for' loop. For Example:
If you had a number of control files that you wanted to process, outputting the results to a same-named log file:
for %i in (c:\temp\*.txt) do echo Do something with %i > %~ni.log
If the output of a previous command wrapped the results in quotes, but you need to append/prepend something else you can easily remove surrounding quotes:
for /f %i in ('echo "c:\windows"') do echo %~i\temp
Given a list of files, echo those that are zero bytes in size:
for %i in (c:\temp\*.txt) do @if %~zi == 0 @echo %i
Given a full path, split into drive, path and filename:
for %i in (c:\windows\temp\test.txt) do echo %~di %~pi %~nxi
Tokens, delimiters and skipping lines
The simple functionality of the 'for /f' command can be extended very easily with three options:
- Tokens – By default only the first token is returned in the variable specified. You can change this behaviour to return one or more tokens, eg tokens=2,3,5 or tokens=1-3 would populate %i, %j and %k with the respective tokens
- Delimiters – Instead of the normal space and tab delimiters, one or more alternate characters can be specified. For example, you can specify a comma as a delimiter to process as CSV file
- Skipping lines – the skip command can be used to skip one or more lines from the start of a control file, useful when trying to skip a header line, or bypass logo information in a command result.
These options can be used individually or as a combination, for example:
Skip the first line of the control file:
for /f "skip=1" %i in (test.txt) do echo %i
Skip the first line, and use comma's as the delimiter:
for /f "skip=1 delims=," %i in (test.txt) do echo %i
Skip the first two lines, use the second token, separated by comma and space:
for /f "skip=2 tokens=2 delims=, " %i in (test.txt) do echo %i
This was a basic overview of the 'for' command, future posts will build on this foundation with multiple commands, error levels, if/then/else statements and nested 'for' loops.
-------------------
Thanks,
http://sccm07.blogspot.com/
Finding duplicate DNS records
Internal DNS in many organisations is usually a little messy and if tasked with cleaning it, my first step would be to identify duplicate records in DNS - either an IP address that is recorded against multiple host names or a host name with multiple host (A) records. Assuming you have a file containing one record per line, this is fairly simple to report on.
The following examples use dnscmd.exe, which assumes Windows 2000/2003 DNS, but you could use any input, as long as it contains a name and an IP.
The two commands:
The first command uses dnscmd to enumerate the records from the root of the test.local zone and exclude aging (dynamic DNS) records. The last find command further filters the output by IP, which can be useful when targeting specific subnets/sites. You might also want to check aging dynamic records instead of static to see how well scavenging is working – if you do, just change the tokens to 1,5 instead of 1,4 (as the aging data is another token separating the name and IP).
The second command:
- Creates a new file called DuplicateIPs.txt in the current working directory
- Iterates through each line in the DNS record dump, extracting the first and fourth token (Name and IP)
- The commands in the first FOR loop check there is a value, then check the value hasn't already been processed in the duplicate list (otherwise you'd have duplicates of each duplicate) and then counts the duplicates and appends them to the file.
- The final command types the duplicate IP file created by the for loop iteration.
For example, supposing your DNS export contained the following records:
printer1 3600 A 192.168.10.100 printer2 3600 A 192.168.10.101 printer3 3600 A 192.168.10.100 printer4 3600 A 192.168.10.102 printer5 3600 A 192.168.10.103 printer6 3600 A 192.168.10.100 printer7 3600 A 192.168.10.102
After running the second command above, a file called DuplicateIPs.txt would be created and then typed to the prompt:
192.168.10.100,3: printer1 3600 A 192.168.10.100 printer3 3600 A 192.168.10.100 printer6 3600 A 192.168.10.100 192.168.10.102,2: printer4 3600 A 192.168.10.102 printer7 3600 A 192.168.10.102
The command below is modified to report duplicate names instead of IP addresses. This was done by using the first token (%i) instead of the second (%j), and modifying the findstr command to use a literal string search ending with a space rather than the regular expression EOL:
echo. > DuplicateIPs.txt & (for /f "tokens=1,4" %i in (DNSRecords.txt) do @if "%i" NEQ "" @find /i "%i" DuplicateIPs.txt >nul & if errorlevel 1 for /f "tokens=1" %m in ('"findstr /i /c:"%i " DNSRecords.txt | find /i /c "%i""') do @if %m GTR 1 (@echo %i,%m: & findstr /i /c:"%i " DNSRecords.txt & echo.) >> DuplicateIPs.txt) & type DuplicateIPs.txt
If you wanted a summary rather than the detail of each duplicate, you could also run the following command:
echo. > DuplicateIPSummary.txt & (for /f "tokens=1,4" %i in (DNSRecords.txt) do @if "%j" NEQ "" @find /i "%j" DuplicateIPSummary.txt >nul & if errorlevel 1 for /f "tokens=1" %m in ('"findstr /i "%j$" DNSRecords.txt | find /i /c "%j""') do @if %m GTR 1 (@echo %j,%m) >> DuplicateIPSummary.txt) & type DuplicateIPSummary.txt
In the example above, this would produce the following report:
192.168.10.100,3 192.168.10.102,2
I use this sort of command to generate reports on duplicates, in this case from DNS, but it could also be useful in DHCP, WINS, or any number of Active Directory objects/attributes. People (myself included) are often wary of automated processes that make changes, but this is an excellent example of how powerful read-only automated commands can be – you can take thousands of objects and produce a report in seconds to quickly identify inconsistencies in an environment.
Dnscmd Overview
http://technet.microsoft.com/en-us/library/cc778513.aspx
-------------------
Thanks,
http://sccm07.blogspot.com/