Labels

Saturday, March 27, 2010

More useful command-lines

This is the third edition of useful command lines, adding another 95 commands that I've found useful. Note that many of the command-line calls may require Microsoft utilities (such as dsquery, wmic, dnscmd).

Most of the commands are for the windows-based command interpreter, with a few PowerShell and ESX service console commands creeping in. They range from diagnostics, troubleshooting and simply automating recurring tasks.

Each command-line can be copied and pasted at the command prompt, if you use a batch file you'll need to reference variables with double-percent (%%).

See the previous two posts for more command-line operations:
http://waynes-world-it.blogspot.com/2008/09/useful-command-lines.html
http://waynes-world-it.blogspot.com/2009/09/more-useful-command-lines.html



Given an IP and mask, return the subet the IP belongs to
for /f "tokens=1-8 delims=.- " %i in ('echo 192.168.5.200 255.255.255.0') do set /a Octet1="%i & %m" >nul & set /a Octet2="%j & %n" >nul & set /a Octet3="%k & %o" >nul & set /a Octet4="%l & %p" >nul & Echo %i.%j.%k.%l,!Octet1!.!Octet2!.!Octet3!.!Octet4!,%m.%n.%o.%p

Disable the internal speaker beep
sc config beep start= demand & net stop beep

List the Volume Shadow Copy Sets
vssadmin list shadows

List the volume Shadow Copy storage associations and sizes
vssadmin list shadowstorage

Create an FSRM storage report to check duplicate files
Storrept Reports Add /Report:DuplicateFiles /Task:FSRM-DuplicateFiles /Scope:"E:\Data" /Name:"Duplicate Files" /Format:CSV /MailTo:user@somewhere.com

Create a scheduled task prior to creating a 2003 FSRM report 
schtasks /create /sc MONTHLY /D 1 /tn FSRM-DuplicateFiles /tr "storrept reports generate /scheduled /task:FSRM-DuplicateFiles" /st 19:00:00 /ru system

Find the number of mailboxes on the specified msExchHomeServerName
dsquery * -filter "(&(objectClass=User)(objectCategory=Person)(mailnickname=*)(msExchHomeServerName=*servername*))" -limit 0 | find /i /c "cn"

Join text copied from the command-line to a single line when pasting
Hold down the shift key when copying the text

Query the current control set, last known good and failed hives 
reg query HKLM\system\select

Make persistent changes to service control dependencies
sc \\%server% config snmp depend= EventLog/

Assign a drive letter to a recently created partition/volume
diskpart assign letter=e

Convert a group from type distribution to type security
dsmod group %groupDN% -secgrp Yes  

Query for global security or distribution groups
dsquery * -filter "(&(groupType:1.2.840.113556.1.4.803:=2))"

Query for global security groups
dsquery * -filter "(&(groupType:1.2.840.113556.1.4.803:=-2147483646))"

Given a list of group DNs, find if those groups are a member of other groups 
for /f "tokens=*" %i in (groups.txt) do @for /f "tokens=*" %m in ('"dsget group -memberof %i | find /i "cn" & if errorlevel 1 Echo Not a member of any groups"') do @echo %i,%m

Find the domain controller GUID of the specified DC 
dsquery * "CN=dcname,OU=Domain Controllers,DC=domainRoot" -scope base -attr objectguid

Find the domain GUID 
dsquery * "domainRoot" -scope base -attr objectGUID

Display the local WLBS Microsoft Network Load Balancing configuration
nlb display

Perform an LDAP ping against rootDSE to get the DC NETLOGON_SAM_LOGON_RESPONSE
adfind -rootDSE -f "(&(DnsDomain=domainFQDN)(Host=%computer%)(User=%computer%$)(DomainGuid=\30\FA\03\19\36\4F\47\1D\35\8F\C4\96\72\74\69\B3)(NtVer=\06\00\00\00))"  netLogon

Find the master browser for the subnet from NetBIOS browser
browstat getmaster \Device\NetBT_Tcpip_{3393FDD1-0D42-4DA4-8E53-36D9E00195F5} NETBIOS_DOMAIN_NAME

List the databases on an MSSQL 2005 server
sqlcmd -S %server% -d master -W -s "," -Q "SELECT NAME FROM sysdatabases Order By Name"

List the Service Control Manager security descriptor
sc sdshow SCMANAGER

Update the Service Control Manager SD on 2003 to allow non-admin access
sc sdset SCMANAGER D:(A;;CCLCRPRC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)

Update the DACL for a service to allow a user to query and interrogate the svc
subinacl /service \\%server%\SysmonLog /grant=domain\user=QSI

Find DFS roots from Active Directory
dsquery * "CN=Dfs-Configuration,CN=System,domainRoot" -filter "(objectClass=fTDfs)"

List the DFS trust domain SPC cache
dfsutil /spcinfo

Find the SQL Server version
sqlcmd -S %server% -d master -W -s "," -Q "SELECT  SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')"

Find the SQL Server 2000 affinity mask 
sqlcmd -S %server% -d master -W -s "," -Q "select c.value from master..sysconfigures c, master..spt_values v, master..syscurconfigs r where v.type = 'C' and v.number = c.config and v.number >= 0 and v.number = r.config and v.name ='affinity mask'"

Find the SQL Server 2005 affinity mask
sqlcmd -S %server% -d master -W -s "," -Q "SELECT Name, Value, Minimum, Maximum, Value_in_use, is_dynamic, is_advanced from SYS.Configurations Where Name = 'affinity mask'"

Find SQL Server 2005 configuration options
sqlcmd -S %server% -d master -W -s "," -Q "SELECT Name, Value, Minimum, Maximum, Value_in_use, is_dynamic, is_advanced from SYS.Configurations Order By Name"

Find SQL Server 2000 license information, Mode 0x0 per-seat, 0x2 per-proc
reg query "\\%server%\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\80\MSSQLLicenseInfo\MSSQL8.00

Find SQL Server 2000/2005 instances
reg query "\\%server%\hklm\software\microsoft\Microsoft SQL Server" /v InstalledInstances

Set environment variables for YYYYMMDD and YYYYMMDDHHMMSS
for /f "tokens=1-8 delims=/:. " %i in ('echo %date% %time%') do Set DateTime=%l%k%j&Set DateTimeLong=%l%k%j%m%n%o

Microsoft iSCSI, list sessions
iscsicli SessionList

Microsoft iSCSI, Report iSCSI and MPIO version information
iscsicli VersionInfo

Show disk usage by username (Windows Resource Kit)
diskuse c:\

Check whether external or forest trusts have SID filter qurantining enabled
nltest /domain_trusts /v

From a list of computers, run a command if the machine responds to a ping
for /f %i in (computers.txt) do @ping -n 1 %i >nul & if errorlevel 0 if not errorlevel 1 echo %i

Extract performance counters from a perfmon binary file and save as csv 
relog.exe -f csv Perfmon.blg -o perfmon.csv

Make a bootable CD using the specified boot sector file and source files
oscdimg /m /n /h -bc:\temp\bootsector.bin "c:\temp\source" install.iso

Find the Exchange storage groups known to AD
dsquery * "CN=Configuration,domainRoot" -filter "(&(objectClass=msExchStorageGroup))" -attr name msExchESEParamCircularLog msExchESEParamEventSource msExchESEParamLogFilePath msExchESEParamLogFileSize msExchESEParamSystemPath msExchESEParamZeroDatabaseDuringBackup msExchRecovery msExchESEParamEnableOnlineDefrag msExchESEParamEnableIndexChecking msExchESEParamBaseName msExchESEParamCommitDefault msExchESEParamDbExtensionSize msExchESEParamPageTempDBMin msExchESEParamPageFragment msExchESEParamCheckpointDepthMax

Check if an executable is large address aware (confirms support)
dumpbin /headers sqlservr.exe

Find all file/registry/thread/event details for a remote machine
psexec \\%server% -c handle.exe -a > c:\temp\handle.txt

Dump configuration with netsh that can be used to import
netsh interface ip dump > IPConfig.txt

Reapply settings saved with netsh export
netsh -f IPConfig.txt

List the SCSI devices for a group of machines
for /f %i in (computers.txt) do @for /f "tokens=1,2,*" %m in ('"devcon -m:\\%i listclass SCSIAdapter | find /i "VEN""') do @echo %i,%o

Adjust the priority of a process given its PID 
setprio /P %PID% /L 2

Find the paged and non-paged pool memory allocations
poolmon

Create a local tag file for paged and non-paged pool memory allocations
poolmon /c

Add a trigger to an existing scheduled task
jt.exe /sac "\\%server%\c$\windows\Tasks\taskname.job" /ctj StartTime=15:10 StartDate=02/02/2010 type=DAILY typearguments=1

Find AdminSDHolder / SDPROP groups in the directory
dsquery * -filter "(&(objectClass=Group)(objectCategory=Group)(adminCount=1))"   

Query for all objects that are protected (that are members of the groups above)
dsquery * -filter "(adminCount=1)"

Count how many user accounts are protected by the SDPROP process
dsquery * -filter "(&(objectClass=User)(objectCategory=Person)(adminCount=1))" | find /i /c "CN="

Find disk and partition relationships
wmic path Win32_LogicalDiskToPartition

LDAP string to search for mail-enabled user and contact objects
"(&(|((objectClass=Contact)(objectClass=User)))(objectCategory=Person)(mailnickname=*))"

Find SCPs (Service Connection Points) for objects other than print queues
dsquery * -filter "&((objectClass=ConnectionPoint)(!(objectClass=PrintQueue)))"  -limit 0

List VSS Shadowstorage associations
wmic /node:%server% path win32_shadowstorage

List VSS Max storage for disabled volumes
reg query HKLM\System\CurrentControlSet\Services\VSS\Volumes\Associations\{00b810fd-8ab6-11de-9d34-806e6f6e6963}\{00b810fd-8ab6-11de-9d34-806e6f6e6963}\MaxDiffSpace

Force a STOP error and generate a memory dump (Stop 0x2E) after enabling
Right Ctrl+ScrollLock+ScrollLock

Enable the option to generate a STOP error on demand
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\i8042prt\Parameters /v CrashOnCtrlScroll /t reg_dword /d 0x1

Logoff a remote terminal sessions session (after using query.exe)
logoff rdp-tcp#42 /v /server:%server%

List the DLL function exports of the specified DLL
dumpbin c:\temp\dllname.dll /exports

Terminate a disconnected terminal services session
rwinsta 0 /server:%server%

Find memory information from a list of machines
for /f %i in (computers.txt) do for /f "tokens=1-5" %m in ('"wmic /node:%i path Win32_PerfFormattedData_PerfOS_Memory get PoolNonpagedBytes,PoolPagedBytes,PoolPagedResidentBytes,FreeSystemPageTableEntries,AvailableMBytes | find /i /v "bytes""') do echo %i,%m,%n,%o,%p,%q

Set the percentage at which the paged pool working set is trimmed
reg add "\\%server%\HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Memory Management" /v PoolUsageMaximum /t reg_dword /d 60

Calculate a replication summary for the domain
repadmin /replsum /bysrc /bydest /sort:delta

Check a 2008 R2 schema forest prep has run successfully (rvevision=5)
dsquery * "CN=ActiveDirectoryUpdate,CN=ForestUpdates,CN=Configuration,domainRoot" -attr * -scope base

Check a 2008 R2 schema domain prep has run successfully (revision=5)
dsquery * "CN=ActiveDirectoryUpdate,CN=DomainUpdates,CN=System,domainRoot" -attr * -scope base

Find the infrastructure role holder for the DNS domain application partition
dsquery * "CN=Infrastructure,DC=DomainDNSZones,domainRoot" -attr fSMORoleOwner   

Find the application partitions from the forest root configuration NC
dsquery * "CN=Partitions,CN=Configuration,domainRoot" -filter "(&(objectClass=crossRef)(msDS-SDReferenceDomain=*))" -attr ncName dnsRoot

Monitor the page faults of an application (hard and soft)
pfmon.exe c:\temp\application.exe

Monitor the page faults of a process (hard and soft)
psmon /p %PID%

Reset the SystemPages memory management for available PTE's to server 2003 def.
reg add "\\%server%\HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management" /v SystemPages /t reg_dword /d 0x0x

Find Exchange mailbox limits for user accounts
csvde -f limits.csv -l samaccountname,cn,mDBStorageQuota,mDBOverQuotaLimit,mDBUseDefaults,mDBOverHardQuotaLimit,homeMDB -r "(&(objectClass=User)(objectCategory=Person)(mailnickname=*))"

Find computer accounts not server, XP or Vista
dsquery * domainroot -filter "(&(objectCategory=Computer)(objectClass=Computer)(&(!(operatingSystem=*prof*)(!(operatingSystem=*server*)(!(operatingSystem=*vista*))))))" -limit 0 -attr CN operatingSystem operatingSystemVersion

Find SPNs from the directory
dsquery * -filter "(servicePrincipalName=*)" -attr cn servicePrincipalName -limit 0

Query a list of groups and determine the group type (global/local/universal)
dsquery group -name *groupfilter* | dsget group -scope -secgrp -dn

Perform a NetBIOS name lookup
nblookup %NETBIOS_NAME%

Extract DNS scavenging events from the DNS eventlog
wmic /node:"%server%" path Win32_NTLogEvent WHERE "SourceName='DNS' AND LogFile='DNS Server' AND EventCode=2501"

Dump GPO information on priority and inherited links for an OU
cscript DumpSOMInfo.wsf "OUName" /ShowInheritedLinks

Copy a GPO 
cscript copygpo.wsf "Default Domain Policy" "Test Domain Policy" domain.com domain.com %SourceDC% %TargetDC%

Backup a number of GPOs from a control file input
for /f "tokens=*" %i in (gpos.txt) do cscript backupgpo.wsf "%i" c:\temp\gpo

Create a number of blank GPOs from a control file input         
for /f "tokens=*" %i in (c:\temp\gpo.txt) do cscript CreateGPO.wsf "%i" /domain:domain.com

Add GPO permissions for a number of GPOs
for /f "tokens=*" %i in (c:\temp\gpo.txt) do cscript SetGPOPermissions.wsf "%i" domain\user /permission:fulledit

List the available features for a 2008 R2 online installation 
dism /online /get-features

Allow remote desktop connections on a 2008 R2 server (requires reboot)
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t reg_dword /d 0x0

Allow remote desktop connections on a 2008 R2 server core  (requires reboot)
cscript C:\Windows\System32\Scregedit.wsf /ar 0

Set the boot timeout for a 2008 server
bcdedit /timeout 5

Modify startup and recovery settings prevent automatic restart on 2008 server 
reg add HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\CrashControl /v "AutoReboot" /t reg_dword /d 0x0

Modify the performance options to adjust for best performance
reg add HKU\.default\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects /v VisualFXSetting /t reg_dword /d 0x2

Disable hibernation on 2008 server
powercfg -hibernate off

Change the default user profile to adjust performance options for best perf
reg load c:\users\Default\ntuser.dat & reg add HKLM\a\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects /v VisualFXSetting /t reg_dword /d 0x2 & reg unload hkml\a

Enable boot logging on 2008 server
bcdedit /set {default} bootlog yes  

Disable Windows Error Reporting on 2008 server
serverWerOptin /disable

Adjust windows server 2008 event log sizes to 128MB
wevtutil sl Security /ms:135266304

Install Windows Server 2008 R2 optional components (features and roles)
cmd /c start /w ocsetup RSAT-NIS;SNMP;WMISnmpProvider;WindowsServerBackup;WindowsServerBackupCommandlet;NetFx3;MicrosoftWindowsPowerShellISE /quiet /norestart /log:c:\temp\install.log

Check Microsoft iSCSI initiator MaxRequestHoldTime 
reg query "\\%server%\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E97B-E325-11CE-BFC1-08002BE10318}\0002\Parameters" /v MaxRequestHoldTime



Wayne's World of IT (WWoIT), Copyright 2010 Wayne Martin. 


All Posts

printQueue AD objects for 2003 ClusterVirtualCenter Physical to VirtualVirtual 2003 MSCS Cluster in ESX VI3
Finding duplicate DNS recordsCommand-line automation – Echo and macrosCommand-line automation – set
Command-line automation - errorlevels and ifCommand-line automation - find and findstrBuilding blocks of command-line automation - FOR
Useful PowerShell command-line operationsMSCS 2003 Cluster Virtual Server ComponentsServer-side process for simple file access
OpsMgr 2007 performance script - VMware datastores...Enumerating URLs in Internet ExplorerNTLM Trusts between 2003 and NT4
2003 Servers with Hibernation enabledReading Shortcuts with PowerShell and VBSModifying DLL Resources
Automatically mapping printersSimple string encryption with PowerShellUseful NTFS and security command-line operations
Useful Windows Printer command-line operationsUseful Windows MSCS Cluster command-line operation...Useful VMware ESX and VC command-line operations
Useful general command-line operationsUseful DNS, DHCP and WINS command-line operationsUseful Active Directory command-line operations
Useful command-linesCreating secedit templates with PowerShellFixing Permissions with NTFS intra-volume moves
Converting filetime with vbs and PowerShellDifference between bat and cmdReplica Domain for Authentication
Troubleshooting Windows PrintingRenaming a user account in ADOpsMgr 2007 Reports - Sorting, Filtering, Charting...
WMIC XSL CSV output formattingEnumerating File Server ResourcesWMIC Custom Alias and Format
AD site discoveryPassing Parameters between OpsMgr and SSRSAnalyzing Windows Kernel Dumps
Process list with command-line argumentsOpsMgr 2007 Customized Reporting - SQL QueriesPreventing accidental NTFS data moves
FSRM and NTFS Quotas in 2003 R2PowerShell Deleting NTFS Alternate Data StreamsNTFS links - reparse, symbolic, hard, junction
IE Warnings when files are executedPowerShell Low-level keyboard hookCross-forest authentication and GP processing
Deleting Invalid SMS 2003 Distribution PointsCross-forest authentication and site synchronizati...Determining AD attribute replication
AD Security vs Distribution GroupsTroubleshooting cross-forest trust secure channels...RIS cross-domain access
Large SMS Web Reports return Error 500Troubleshooting SMS 2003 MP and SLPRemotely determine physical memory
VMware SDK with PowershellSpinning Excel Pie ChartPoke-Info PowerShell script
Reading web content with PowerShellAutomated Cluster File Security and PurgingManaging printers at the command-line
File System Filters and minifiltersOpsMgr 2007 SSRS Reports using SQL 2005 XMLAccess Based Enumeration in 2003 and MSCS
Find VM snapshots in ESX/VCComparing MSCS/VMware/DFS File & PrintModifying Exchange mailbox permissions
Nested 'for /f' catch-allPowerShell FindFirstFileW bypassing MAX_PATHRunning PowerSell Scripts from ASP.Net
Binary <-> Hex String files with PowershellOpsMgr 2007 Current Performance InstancesImpersonating a user without passwords
Running a process in the secure winlogon desktopShadow an XP Terminal Services sessionFind where a user is logged on from
Active Directory _msdcs DNS zonesUnlocking XP/2003 without passwords2003 Cluster-enabled scheduled tasks
Purging aged files from the filesystemFinding customised ADM templates in ADDomain local security groups for cross-forest secu...
Account Management eventlog auditingVMware cluster/Virtual Center StatisticsRunning scheduled tasks as a non-administrator
Audit Windows 2003 print server usageActive Directory DiagnosticsViewing NTFS information with nfi and diskedit
Performance Tuning for 2003 File ServersChecking ESX/VC VMs for snapshotsShowing non-persistent devices in device manager
Implementing an MSCS 2003 server clusterFinding users on a subnetWMI filter for subnet filtered Group Policy
Testing DNS records for scavengingRefreshing Computer Account AD Group MembershipTesting Network Ports from Windows
Using Recovery Console with RISPAE Boot.ini Switch for DEP or 4GB+ memoryUsing 32-bit COM objects on x64 platforms
Active Directory Organizational Unit (OU) DesignTroubleshooting computer accounts in an Active Dir...260+ character MAX_PATH limitations in filenames
Create or modify a security template for NTFS perm...Find where a user is connecting from through WMISDDL syntax in secedit security templates

About Me

I’ve worked in IT for over 20 years, and I know just about enough to realise that I don’t know very much.