Labels

Sunday, June 14, 2020

More useful command-lines #4


While PowerShell is usually the tool of choice these days, old habits die hard.  I still record
command-lines I find useful in the old-fashioned command prompt. 

This is the fourth edition of useful command lines, adding another 467 commands. Note that many of the command-line may require Microsoft utilities (such as dsquery, wmic, dnscmd), or resource kits, sysinternals or other third-party binaries.


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 (%%).


I hope this will help some of the other non-clickers out there.


See the previous three posts for more command-line operations:



Disable IPV6 on Windows Server 2008
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters" /v DisabledComponents /t reg_dword /d 0xFFFFFFFF

Verify a certificate chain
certutil -verify -urlfetch test.cer

Query the roles and features installed on a Windows Server 2008 installation
ServerManagerCmd -query

Create a performance monitor log to gather local counters
logman create counter SystemPerformance -cf c:\temp\counters.txt -b "29/04/2010 0:00:00" -e "29/04/2010 23:59:59" -r -rf 24:00:00 -cnf 24:00:00 -o c:\perflogs\%computername% -f bin -si 00:00:15

Check the access permissions on files/directories/registry keys (sysinternals)
accesschk.exe

GUI View virtual/physical memory maps of processes (sysinternals)
vmmap.exe

View Win32 and Kernel-mode Debug output (sysinternals)
dbgview.exe

Use 2008R2 logman to create a data collector set from a saved XML
logman import -xml c:\admin\Control\Performance.xml -n Performance

Use 2008R2 logman to start a performance data collector set
logman start Performance

Display license/activation details on a KMS client for the current license
cscript c:\windows\system32\slmgr.vbs /dlv

Find 2008 servers in the domain
dsquery * domainroot -filter "(&(objectCategory=Computer)(objectClass=Computer)(operatingSystem=Windows Server 2008*))" -limit 0

Set the KMS server used for activation
cscript slmgr.vbs /skms %kmsServer%

Trigger software activation
cscript slmgr.vbs /ato

Find the owners of all processes on a remote system
wmic /node:%server% PROCESS where "caption like '%'" getowner

Find contacts that are members of distribution groups
dsquery * -filter "(&(objectClass=Contact)(objectCategory=Person)(memberof=*))" -attr distinguishedname memberof -limit 0

Query a group of XenApp/terminal servers for TS logons
wmic /node:server01,server02,server03 path Win32_PerfFormattedData_TermService_TerminalServices Get ActiveSessions,InactiveSessions,TotalSessions

Enable user mode verbose logging
reg add "\\server01\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v UserenvDebugLevel /t reg_dword /d 0x30002

Enable Kerberos debugging
reg add HKLM\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters /v LogLevel /t reg_dword /d 1

Enable NTFRS debugging
reg add HKLM\SYSTEM\CurrentControlSet\Services\NtFrs\Parameters /v "Debug Log Severity" /t reg_dword /d 0x4

Enabled Group Policy Client Side Extension (CSE) debugging
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\GpExtensions\{827d319e-6eac-11d2-a4ea-00567f79f83a}" /v ExtensionDebugLevel /t reg_dword /d 0x2

Enabled Group Policy foldre redirection debugging
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Diagnostics" /v FdeployDebugLevel /d reg_dword /d 0x0000000F

Check whether a user's token size is too large
ntdsutil "group membership evaluation" "run domain user"

Use ntdsutil with escaped double-quotes when the SAMID has spaces
ntdsutil "group membership evaluation" "run domain \"User 01\"" quit quit

2008 server print backup recovery and maintenance, query printers
c:\Windows\System32\spool\tools\printbrm -q

Set the managed by attribute of an object on a particular DC
cscript SetManagedBy.vbs dc01 "CN=GroupName,CN=Users,DC=domain,DC=local" "CN=UserOrGroup,DC=domain,DC=local"

Set the ACE required for the tick-box allowing a manager of an object
dsacls.exe "CN=GroupName,CN=Users,DC=domain,DC=local" /G domain\user:WP;member

Test whether a Domain Controller is responding over LDAPS
adfind -b "dc=domain,dc=local" -h dc01 -ssl

Find AD/DNS registered KMS servers
nslookup -type=srv _VLMCS._tcp.domain.local

Query a number of Citrix/XenApp/Terminal servers for users
for %i in (server01 server02 server03) do @for /f %m in ('"quser /server:%i | find /i "ica" /c"') do @echo %i,%m

Query Citrix farm information
qfarm

Set 2003 page file information
cscript C:\WINDOWS\system32\pagefileconfig.vbs /change /s %server% /I 6144 /M 6144 /VO C:

Set 2008 page file information
wmic pagefileset create name="C:\\pagefile.sys" & wmic pagefileset set InitialSize=614,MaximumSize=6144

View the certificate stores available to the current user
reg query HKCU\Software\Microsoft\SystemCertificates

View the properties of an exported certificate
certutil /dump ExportedCert.pfx

Find the MTU size on a Windows 2003+ server
netsh interface ip show int

Read the registry to find network adapter configuration (MTU jumbo)
reg query \\server01\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318} /s | find /i "reg" | findstr /i /c:DriverDesc /c:ProviderName /c:"jumbo"

Use WMI to find the MTU of a network interface (2008 and later)
wmic /node:%server% path win32_networkadapterconfiguration get MACAddress,MTU,IPAddress

Report drive geometry using WMI
wmic path Win32_DiskDrive Get DeviceID,TotalSectors ,Size

Query Citrix session information
queryds /table:Conn_Sessions

Find the committed bytes in use percentage from a remote computer
wmic /node:%server% path Win32_PerfFormattedData_PerfOS_Memory get PercentCommittedBytesInUse

Find the Citrix XenApp metaframe load level for a Citrix server
wmic /node:%server% /namespace:\\root\Citrix path MetaFrame_Server_LoadLevel

Find the applications running on a Citrix server
wmic /node:server01 /namespace:\\root\Citrix path MetaFrame_ApplicationsRunningOnServer

Find Citrix server information
wmic /node:server01 /namespace:\\root\Citrix path MetaFrame_Server

From a list of computers, find the remote NIC bandwidth / speed
for /f  %i in (c:\temp\servers_20100601.txt) do wmic /node:%i path Win32_PerfRawData_Tcpip_NetworkInterface Where "Name!='MS TCP Loopback interface'" Get Name,CurrentBandwidth > %i_bandwidth.txt

Find Exchange Servers from Active Directory
dsquery * "CN=Configuration,DC=domain,DC=local" -filter "(&(objectClass=msExchExchangeServer)(objectCategory=msExchExchangeServer))"

Transfer single-master FSMO roles to the connected DC
ntdsutil roles Connections "Connect to server dc01" quit "Transfer %role%"

Query for the NetBIOS 1B domain master browser and PDC record
nblookup /x 1b DOMAIN

Query for the DNS PDC SRV Service Record
nslookup -type=srv _ldap._tcp.pdc._msdcs.domain.local

Check the role for a domain member
wmic /node:dc01 path win32_computersystem get DomainRole  (0 Standalone WS, 1 Member WS, 2 Standalone Server, 3 Member Server, 4 Backup Domain Controller, 5 Primary Domain Controller)

Load performance counters from the specified DLL
lodctr %file%

Find a list of computers sorted by creation date
dsquery * "OU=Workstations,OU=Resources,DC=domain,DC=local" -limit 0 -filter "(&(objectClass=Computer)(objectCategory=Computer))" -attr whenChanged CN | sort

Find the display specifier used when creating new users through the GUI
dsquery * "CN=user-Display,CN=409,CN=DisplaySpecifiers,CN=Configuration,DC=domain,DC=local" -attr createDialog

Delete a computer record from SCCM through the WMI provider
wmic /namespace:\\root\sms\site_sc1 /node:"server01" path  SMS_R_System WHERE Name='server02' DELETE

Recompile service control manager logs to fix missing SCM event log entries
psexec \\server01 /s mofcomp %windir%\system32\wbem\scm.mof

Export feature/role information using 2008 server manager (shows defaults)
servermanagercmd -query c:\temp\roles.xml

Find trust account metadata for a trusted domain
repadmin /showmeta "CN=DOMTRUST$,CN=Users,DC=domain,DC=local"

Set read-only permissions to the current folder with non-progagated inheritance
icacls . /grant Users:(NP)(R)  - in this example adding (NP) is not strictly necessary, just ommitting (OI)(CI) assumes this folder only (NP).  The SDDL export of two commands reports the same (with NP and without)

Query system devices and drivers
wmic /node:server01 path win32_systemdriver

Find machines from a specific manufacturer
wmic /node:server01 path win32_computersystem where "Manufacturer like '%Dell%'" get Manufacturer,Model,Name

Run a remote sysinternals utility with psexec specifying accepteula twice
psexec -accepteula \\server01 c:\temp\handle.exe "-accepteula"

Use delayed expansion (cmd /v:on) to parse reg.exe output and produce CSV
for /f "tokens=1,* delims=_" %i in ('dir /b *.txt') do @set test="%~nj"& (@for /f "skip=2 tokens=3" %m in ('"find /i "reg_" %i_%j | findstr /c:AutoReboot /c:CrashDumpEnabled /c:DumpFile /c:LogEvent /c:MinidumpDir /c:Overwrite /c:SendAlert | sort"') do @set test=!test!,"%m")& @echo !test!

Enable the option to generate a STOP error on demand for a USB 2008 server
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\kbdhid\Parameters /v CrashOnCtrlScroll /t reg_dword /d 0x1

Generate a STOP error with a sysinternals test faulty app
NotMyFault.exe /crash

Gather file system cache and other memory information from a group of servers
for /f %i in ('dsquery computer -desc *file* -name server* -o rdn') do @for /f "skip=1 tokens=1-8" %m in ('"wmic /node:%i path Win32_PerfFormattedData_PerfOS_Memory get CacheBytes,CacheBytesPeak,SystemCacheResidentBytes,AvailableMBytes,PoolPagedBytes,PoolNonpagedBytes,FreeSystemPageTableEntries,PercentCommittedBytesInUse"') do @echo %i,%m,%n,%o,%p,%q,%r,%s,%t

Analyse Windows memory allocation (sysinternals). Metafile for FS cache
RAMMap and VMMap

Install IIS7 and management tools on 2008
servermanagercmd -install Web-WebServer Web-Mgmt-Tools

Install File services and FSRM on 2008
servermanagercmd -install File-Services FS-FileServer FS-Resource-Manager

Find the cluster size of a disk volume
wmic /node:%server% path win32_volume Get DriveLetter,BlockSize,Label

Find mail enabled users and contacts from an AD and export to CSV
csvde -f c:\temp\mailEnabled_20100816.csv -l samaccountname,cn,givenName,sn,displayname,mail,proxyAddresses,mailnickname,legacyExchangeDN,lastLogonTimestamp -r "(&(|((objectClass=Contact)(objectClass=User)))(objectCategory=Person)(mailnickname=*))"

Find Exchange private mailbox stores from AD
dsquery * "CN=Configuration,DC=domain,DC=local" -filter "(&(objectClass=msExchPrivateMDB)(objectCategory=msExchPrivateMDB))"

Modify security descriptor for access to the application event log
HKLM\System\CurrentControlSet\Services\Eventlog\Application\CustomSD,1,%AppLogSD%,2

Query alternate recipients for Exchange forwarding addresses
dsquery * -filter "(&(objectClass=*)(altRecipient=*))" -attr cn altrecipient

Use IPMI to query the event log of a Dell server BMC
ipmiutil sel -N 192.168.1.10 -U root -P calvin -F lan2

Query a dnsNode object in AD for a reverse lookup zone
dsquery * "DC=10,DC=192.168.1.in-addr.arpa,CN=MicrosoftDNS,DC=DomainDnsZones,DC=domain,DC=local" -attr *

List Print Drivers on a 2008 R2 server
cscript C:\Windows\System32\Printing_Admin_Scripts\en-US\prndrvr.vbs -l

Install an x64 2008 R2 version 3 printer driver
cscript C:\Windows\System32\Printing_Admin_Scripts\en-US\prndrvr.vbs -a -v 3 -e "Windows x64" -m "RICOH Aficio 3245C PCL 6" -i c:\src\Drivers\Ricoh3245C\r40479en\disk1\OEMSETUP.INF -h c:\src\Drivers\Ricoh3245C\r40479en\disk1

Install an x86 XP version 3 printer driver to a 2008 R2 server
cscript C:\Windows\System32\Printing_Admin_Scripts\en-US\prndrvr.vbs -a -v 3 -e "Windows NT x86" -m "RICOH Aficio 3245C PCL 6" -i c:\src\Drivers\Ricoh3245C\r40485en\disk1\OEMSETUP.INF -h c:\src\Drivers\Ricoh3245C\r40485en\disk1

Create a TCP/IP port using RAW over TCP 9100
cscript prnport.vbs -a -s server01 -r IP_192.168.1.10 -h 192.168.1.20 -o raw -n 9100

Create a printer, using the specified printer and port on a 2008 R2 server
cscript prnmngr.vbs -a -p DJW391 -m "RICOH Aficio 3245C PCL 6" -r IP_192.168.1.10

Share and publish a printer on a 2008 R2 server
cscript prncnfg.vbs -t -p DJW391 -h DJW391 +shared +published

Query IIS virtual directories using WMI
wmic /node:server01 /namespace:\\root\MicrosoftIISv2 path IIsWebVirtualDir

Enumerate 2008 R2 event logs
wevtutil.exe el

Get the configuration of a 2008 R2 event log
wevtutil.exe gl Microsoft-Windows-PrintService/Operational

Enable print information job logging with 10MB log file
wevtutil.exe sl Microsoft-Windows-PrintService/Operational /e /ms:10485760

Set AD acls for full control of computer objects, inherited to sub-objects
dsacls "OU=Workstations,OU=Resources,DC=domain,DC=local" /I:S /G DOMAIN\group01:GA;;computer

Set AD acls for creating/deleting computer objects, inherited to this and sub
dsacls "OU=Workstations,OU=Resources,DC=domain,DC=local" /I:T /G DOMAIN\group01:CCDC;computer

Check whether an executable is x86, WAMD64, W32i64 etc (2003 support.cab)
filever.exe %filename%

LDAP filter to return mail-enabled users that are members of a particular group
dsquery * -filter "(&(objectClass=User)(objectCategory=Person)(mailnickName=*)(memberOf=CN=group01,OU=Groups,DC=domain,DC=local))"

Find dynamic distribution lists in the directory and the LDAP filter used
dsquery * -filter "(objectClass=msExchDynamicDistributionList)" -attr distinguishedName msExchDynamicDLFilter

Find groups a user is a member of using extended match operator for the chain
dsquery * -filter "(&(objectClass=Group)(member:1.2.840.113556.1.4.1941:=CN=user01,DC=domain,DC=local))" -scope subtree

Find foreign security principals and group membership, resolving the name
dsquery * CN=ForeignSecurityPrincipals,DC=domain,DC=local -filter "(&(objectClass=foreignSecurityPrincipal)(memberOf=*))" -attr msDS-PrincipalName memberof

Find constructed token groups for the specified user
dsquery * "CN=user01,DC=domain,DC=local" -attr tokenGroupsGlobalAndUniversal -s dc01 -scope base

Find constructed last modified for the specified object
dsquery * "CN=user01,DC=domain,DC=local" -attr modifyTimeStamp -s dc01

Find the constructed canonincal name for the specified user object
dsquery * -filter (samaccountname=user01) -attr canonicalName -s dc01

Find software that's installed using WMI
wmic path win32_product

Find file/directory information using WMI
wmic path win32_directory where "Name = 'c:\\temp'"

Join a computer to a domain
netdom join %computername% /domain:test.com /userd:administrator /passwordd:password /reb

Find a list of servers from AD and then query them for disk space
for /f %i in ('dsquery computer -name server* -o rdn') do @wmic /node:%i path Win32_LogicalDisk Get Name,Size,FreeSpace,VolumeName /format:csv | find /i /v "a:,," | find /i /v "d:,," | find /i "dv"

Find uptime of a computer and lanman workstation statistics
net stats workstation

Find uptime of a computer and lanmanserver statistics
net stats srv

Find size and free space of logical disks of a remote machine
wmic /node:"server01" path Win32_LogicalDisk WHERE "Size > 0" GET SystemName,Name,Size,FreeSpace,VolumeName /format:csv

ODBC data source administrator on 2008 R2
odbcad32.exe

Create a 64-bit DSN on 2008 R2
odbcconf.exe /Lv c:\admin\logs\SQLNativeClientInstall.log /A {CONFIGSYSDSN "SQL Server Native client 10.0" "DSN=VMware VirtualCenter|Description=Test instance of vCenter|Server=sqlserver01\instance01|Database=VirtualCenter"}

Create a 32-bit DSN on 2008 R2
c:\windows\syswow64\odbcconf.exe /Lv c:\admin\logs\SQLNativeClientInstall.log /A {CONFIGSYSDSN "SQL Server Native client 10.0" "DSN=VMUM|Description=Update Manager Test Instance|Server=sqlserver01\instance01|Database=VMUM"}

Check the NTP announceflags of each DC to find reliable time servers
for /f %i in ('"nltest /dclist: | find /i "[ds]""') do reg query \\%i\hklm\system\currentcontrolset\services\w32time\config /v announceflags

Set the logon as a service right on a remote computer
ntrights -m \\%computer% -u %domain%\%user% +r SeServiceLogonRight

Set a remote service to run as a doman user account (remove interact)
sc \\%computer% config %service% obj= "%domain%\%username%" password= "password" type= own

Find the server holding the PDC single-master operations role
dsquery server -hasfsmo pdc

Add and install a Plug and Play driver package (enough for 2008 to change vga)
pnputil -i -a "c:\program files\common files\vmware\Drivers\wddm_video\vm3d.inf"

Find vCenter alerts
dumpel -s server01 -l application -d 1 -m "Categor01"

Find the latest .Net framework version from a list of computers
for /f %i in (c:\temp\servers_20101020.txt) do @ping -n 1 %i >nul & if errorlevel 0 if not errorlevel 1 @for /f "tokens=*" %m in ('"reg query "\\%i\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP" 2>nul |find /i "hkey" > c:\temp\dotnet.txt & tail -1 c:\temp\dotnet.txt"') do @for /f "tokens=3" %q in ('"reg query "\\%i\%m" /v version 2>nul| find /i "reg_sz" & if errorlevel 1 echo 1 2 NotFound"') do @echo %i,%m,%q

Query Citrix or terminal server session information
qwinsta /server:%computer%

Reset a remote Citrix or terminal server session
rwinsta %sessionname% /server:%computer%

Reset a local Citrix or terminal server session
reset %sessionname%

Find host header bindings from the IIS metabase
findstr /i "^.*:[0-9]*:.*$" \\%server%\c$\windows\system32\inetsrv\metabase.xml

Export events, changing the date from EN-US to EN-AU
for /f "tokens=1-3,* delims=/ " %i in ('"dumpel -s \\server01 -l application -e 3041 -m "MSSQL$DB01" -d 50"') do @echo %j/%i/%k %l

Use IPMI to read sensors on a Dell R900 server
ipmiutil sensor -N 192.168.1.10 -U root -P calvin -F lan2

Find the sector and cluster size for an NTFS volume
fsutil fsinfo ntfsinfo h:\

Enumerate SRV records from the specified location in a DNS zone
dnscmd dc01 /enumrecords domain.local._tcp.dc._msdcs.domain.local. /type SRV

Export an AD-integrated zone to file
dnscmd server01 /ZoneExport domain.local domain.local.dns

Find driver file information for the specified devices
devcon drivernodes *RDP_MOU* & devcon driverfiles *RDP_MOU*

Create a custom Active Directory partition for DNS records
DnsCmd dc01 /CreateDirectoryPartition manualDNS_msdcs.domain.local

Add an additional DC for partition replication
DnsCmd dc01 /EnlistDirectoryPartition  manualDNS_msdcs.domain.local

Convert a file-based primary to an AD integrated primary in a custom partition
dnscmd /ZoneResetType _msdcs.domain.local /DsPrimary /OverWrite_Ds /DirectoryPartition manualDNS_msdcs.domain.local

Enumerate the partitions in an Active Directory
DnsCmd /EnumDirectoryPartitions

Find CAs published in AD
dsquery * "cn=enrollment services,cn=public key services,cn=services,cn=configuration,dc=domain,dc=local

Find user accounts with SID history
adsquery * -filter "(&(objectClass=User)(objectCategory=Person)(sidhistory=*))" -attr name sidhistory

Check the local _msdcs records on a Domain Controller
\\%computer%\c$\windows\system32\config\netlogon.dns

Find secure channel information about trusted domains/forests
wmic /namespace:\\root\MicrosoftActiveDirectory path Microsoft_DomainTrustStatus

Find services that are set to automatically start but are currently stopped
wmic /node:server01 path win32_service  where "State='Stopped' AND StartMode='Auto'"

Find trusts of type forest
dsquery * "CN=System,DC=domain,dc=local" -filter "(&(objectClass=trustedDomain)(trustAttributes:1.2.840.113556.1.4.803:=8))" -attr stPartner flatName trustAttributes

Add an Active Directory service record for GC lookups
dnscmd dc01 /recordadd _msdcs.domain.local.  _ldap._tcp.site01._sites.gc._msdcs.domain.local. SRV 0 100 3268 dc01.domain.local.

Modify the default intra-site change notification for replication
repadmin /notifyopt dc1 dc2 "DC=domain,DC=local" /first:10

Find the options for a site link (1 for change notifications)
dsquery * "CN=SiteLink01,CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration,DC=domain,DC=local"  -attr Options

Modify a site link to use change notifications
admod -b "CN=SiteLink01,CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration,DC=domain,DC=local" options::1

Delete one or more user profiles
delprof /p /c:\\%computer%

Write an ISO image to CD/DVD
isowriter -r e: -e "file.iso"

Find mail-enabled public folders that aren't hidden from the GAL
dsquery * -filter "(&(objectClass=publicFolder)(mailnickName=*))" -attr cn mail msExchHideFromAddressLists -limit 0 | find /i "false"

Query servers from an SMS/SCCM database
wmic /namespace:\\root\sms\site_a01 /node:"server01" path SMS_R_System WHERE "ADSiteName = 'S01' and OperatingSystemNameandVersion like '%server%'" get name,adsitename,IPAddresses,MACAddresses /format:CSV

Find serial numbers from physical servers
wmic /node:@physical.txt path Win32_SystemEnclosure get SerialNumber /format:csv

Find the number of mail-enabled active users who have a home drive on a server
for /f "tokens=*" %i in ('dsquery * -filter "(&(objectClass=User)(objectCategory=Person)(mailnickname=*)(!userAccountControl:1.2.840.113556.1.4.803:=2)(homeDirectory=*%server%*))" -limit 0 ^| find /i /c "cn="') do @echo %i

Find the canonical name (constructed attribute) of a list of users
dsquery * -filter "(&(objectClass=User)(objectCategory=Person)(homeDirectory=*arisrv*))" -attr canonicalName

Query and decode password last set for user accounts, output in csv without DN
adfind -b "DC=domain,DC=local" -f "(&(objectClass=User)(objectCategory=Person)(homeDirectory=*server01*))" canonicalName pwdlastset -tdc -csv -excl -nodn

Find an account and decode all attributes (pwdlastset, useraccountcontrol etc)
adfind -s base -b "CN=user01,OU=Accounts,DC=domain,DC=local" -h dc01 -alldc

Find the canonical name of a filtered list of OUs
dsquery * -filter "(&(objectClass=organizationalUnit)(name=*server*))" -attr canonicalName

Purge Kerberos tickets for the currently running user
klist purge

From a list of computers, report whether they respond to a ping or not
for /f %i in (c:\temp\Servers.csv) do for /f "tokens=3 delims=: " %m in ('ping -n 1 %i ^| find /i "reply from" ^& if errorlevel 1 echo 1:2:NoReply') do echo %i,%m

Query 2008 or later for the OS architecture (x86 or x64)
wmic /node:server01 path Win32_OperatingSystem Get OSArchitecture

Query 2003 or earlier for the OS architecture (x86 or x64)
wmic /node:server01 path Win32_OperatingSystem Get Caption

Delete the policy restriction to run perfmon.msc
reg delete HKEY_CURRENT_USER\Software\Policies\Microsoft\MMC\{C96401CF-0E17-11D3-885B-00C04F72C717}

Update the WINS DHCP Option Value
netsh dhcp server \\server01 scope 192.168.10.0 set optionvalue 044 IPADDRESS 192.168.10.10 192.168.20.10

List Components installed on a 2008 R2 core installation
ocsetup ServerManager-PSH-Cmdlets, Import-Module Servermanager; Get-WindowsFeature

Rename a computer
netdom renamecomputer oldserver01 /newname newserver01 /reboot

Show current firewall rules
netsh advfirewall firewall show rule name=all

Enable DNS logging
dnscmd /config /loglevel 0xffffffff

Disable EDNS0 probes
dnscmd /Config /EnableEDnsProbes 0

Update the master for a secondary DNS zone
dnscmd /zoneresetmasters zone.local 192.168.10.10 192.168.10.11

Disable TCP window size auto-tuning on 2008 servers
netsh interface tcp set global autotuning=disabled

Show global TCP settings on 2008 servers
netsh interface tcp show global

Allow storage of credentials (requirse reboot)
reg add hklm\system\currentcontrolset\control\lsa /v disabledomaincreds /d 0x0 /t reg_dword

Tell Exchange to filter messages sent through authenticated connections (SCL)
reg add HKEY_LOCAL_MACHINE\Software\Microsoft\Exchange\ContentFilter /v CheckAuthSessions /d 0x1 /t reg_dword

Check if Access Based Enumeration (ABE) is enabled on a DFS namspace
dfsutil property abe \\domain.local\shared

Find groups of type distribution
dsquery * -filter "(&(objectClass=Group)(objectCategory=Group)(!groupType:1.2.840.113556.1.4.803:=2147483648))"

Set variables for the current date
for /f "tokens=2-9 delims=/:. " %i in ('echo %date% %time%') do Set DateTime=%k%j%i&Set DateTimeLong=%k%j%i%l%m%n

Find people that have logged on today
for /f "tokens=2-9 delims=/:. " %i in ('echo %date% %time%') do Set Today=%k/%j/%i& adfind -default -f "(&(objectClass=User)(objectCategory=Person))" -csv -noDN -alldc Name lastlogontimestamp | find /i "%today%"

Set the secure list of IPs allowed to transfer a DNS zone
dnscmd dc01 /zoneresetsecondaries domain.local /SecureList 192.168.10.10 192.168.10.11

Use portqry to perform a NetBIOS adapter status request (retrieves MAC)
portqry -n server01 -e 137 -p udp

Find the Exchange schema version
dsquery * CN=ms-Exch-Schema-Version-Pt,cn=schema,cn=configuration,dc=domain,dc=local -scope base -attr rangeUpper

Find the NTDS.DIT file size on Domain Controllers in the local domain
for /f %i in ('dsquery server -o rdn') do @for /f "tokens=1-5" %m in ('"dir \\%i\c$\windows\ntds\ntds.dit | find /i "dit""') do @echo %i,%m,%n %o,"%p",%q

Find Active Directory schema attributes with the specified display Name
dsquery * "CN=Schema,CN=Configuration,DC=domain,DC=local" -filter (lDAPDisplayName=info)

Find groups with the info/comment set
dsquery * -filter "(&(objectClass=Group)(objectCategory=Group)(info=*))" -attr Name Info

Refresh 2008 R2 network configuration after policy changes (eg SearchList)
psexec \\server01 gpupdate

Check the disk timeout value for SCSI Request block storport I/O requests
reg query \\%server%\HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Disk /v TimeOutValue

Find a DC in the closest site available by site cost    nltest /dsgetdc:domain.
ocal /TRY_NEXT_CLOSEST_SITE                  

Query the SPF record for a DNS zone from the specified DNS server
nslookup -type=txt server.mail.com 192.168.10.10

Enabled Event log tracing for Windows for nltest.exe processes using DCLocator
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\DCLocator\Tracing\nltest.exe"

Start an ETW session for the DCLocator GUID
"C:\WinDDK\7600.16385.1\Tools\tracing\amd64\tracelog.exe" -start "nltest" -guid #cfaa5446-c6c4-4f5c-866f-31c9b55b962d -f c:\temp\nltesttrace1.evt -flag 0x0a024332 -level 0x4

Stop an ETW session
tracelog -stop nltest

Parse ETW data and generate a HTML report
tracerpt nltesttrace.etl -o -report

Use LogParser to parse an ETW DCLocator report
"C:\Program Files (x86)\Log Parser 2.2\LogParser.exe" -i etw -o csv "select * from \temp\nltesttrace.etl"

Query the status of an NBL load balanced cluster
nlb query & cluster.domain.local:clusterhost2

Extract Windows Server 2008 R2 events by source
dumpel -l application -d 1 -m Microsoft-Windows-Defrag

Redirect output to the clipboard (2003 or later binary)
echo test | clip

Find users who will need to reset their password at next logon
dsquery * -filter "(&(objectClass=User)(objectCategory=Person)(pwdLastSet=0))"

Decode Exchange 2003 permissions through msExchMailboxSecurityDescriptor
adfind -b "CN=user01,DC=domain,DC=local" -alldc -sddc+ -resolvesids

Refresh certificates from NTDS store on 2008 Domain Controllers
adfind -h dc01 -sc rsc

Find Exchange servers from Active Directory
dsquery * "CN=Servers,CN=First Administrative Group,CN=Administrative Groups,CN=ORG,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domain,DC=local" -scope onelevel

Browse directly to a different mailbox with OWA
https://vip.domain.local/owa/user01@domain.local

Find the Operating System from a list of computers
wmic /node:@c:\temp\exchange.txt path win32_operatingsystem get CSName,Name

Export a certificate as Base64 encoded
certutil -split -store my server01.domain.local & certutil -encode Blob0_0.crt server01.domain.local.txt

Create a self-signed root authority on a server (prompts for password)
makecert -r -pe -n "CN=Test Root Authority" -ss my -sr LocalMachine -a sha1 -sky signature TestCA.cer -sv TestCA.pvk

Add a self-signed root to the trusted root CA store
certutil -addstore root TestCA.cer

Create a server authentication cert using the self-signed root for local DC
makecert -pe -n "CN=dc01.test.local" -ss my -sr LocalMachine -a sha1 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -in "Test Root Authority" -is MY -ir LocalMachine -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 dc01.test.local.cer

Create a server authentication cert using the self-signed root for a second DC
makecert -pe -n "CN=dc02.Test.local" -ss my -sr LocalMachine -a sha1 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -in "Test Root Authority" -is MY -ir LocalMachine -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 dc02.Test.local.cer

Export the dc02 cert with private key for transfer to another computer
certutil.exe -privatekey -exportpfx "dc02.test.local" dc02.test.local.pfx

On dc02, install the root trusted cert and the server cert
certutil -addstore root TestCA.cer & certutil -importPFX dc02.test.local.pfx

Delete certificates from the personal store on the local computer
certutil -delstore my dc02.test.local & certutil -delstore my TestVCA

Shows DHCP reserved IPs from a DHCP scope
netsh dhcp server \\server01 scope 192.168.10.0 show reservedip

Find users that are listed in the managedBy field of one or more groups
dsquery * -filter "(&(objectClass=User)(objectCategory=Person)(managedObjects=*))" -attr name managedobjects

Find Collections from SMS using WMIC
wmic /namespace:\\root\sms\site_org path sms_collection where "Name like '%OSD%'"

Deny a user the right to view another user in AD
dsacls "CN=user01,DC=domain,DC=local" /d domain\user02:GR;;

Find groups and decode the group type
adfind -b "dc=domain,dc=local" -f "(&(objectClass=Group)(mailnickname=*))" -h dc01 name groupType -alldc -csv

Find the token size and groups a user is a member of
tokensz /compute_tokensize /dump_groups

From a resource server, find the token size and group membership (SIDHistory)
tokensz /compute_tokensize /user:user01 /domain:domain /password:Password1 /dump_groups

Using OWA for Exchange 2003, view/recover deleted items in any folder
http://exchange01/exchange/user@domain.local/?cmd=showdeleted

Find group and their group type (security, distribution, universal etc)
adfind -b "dc=domain,dc=local" -f "(&(objectClass=Group)(objectCategory=Group))" -h dc01 name groupType -alldc -csv > c:\temp\quest\SecurityGroupTypes_20110826.csv

Find groups of type security in the directory
adfind -b "dc=domain,dc=local" -f "(&(objectClass=Group)(objectCategory=Group)(name=@*)(groupType:1.2.840.113556.1.4.803:=-2147483648))" grouptype -alldc

Find tables in the specified SQL database
sqlcmd -S server01\QMMINSTANCE -d MMEXProject -W -s "," -Q "SELECT * from sys.tables"

Query a Quest QMM 8,7 database for collections and members
sqlcmd -S server01\QMMINSTANCE -d MMEXProject -W -s "," -Q "SELECT COL.CollectionName,srv.Name,MO.DisplayName from MEMBERSOFCOLLECTION MO inner join collections COL on COL.ID = MO.CollectionID inner join server srv on srv.ID = MO.ServerID Where MO.CollectionID != 0"

Find accounts in the directory created today
for /f "tokens=1-8 delims=/:. " %i in ('echo %date% %time%') do Set Today=%l%k%j000000 & adfind -b dc=domain,dc=local -f "(&(objectClass=User)(objectCategory=Person)(whenCreated>=%today%.0Z))" -csv

View a DFS namespace on 2008 R2
dfscmd /view \\domain.local\shared /full

Find the Outlook mail control panel CPL file
reg query "HKEY_CURRENT_USER\Control Panel\MMCPL"

Mount a shadow copy volume through the filesystem (vssadmin list shadows)
mklink /d c:\shadowcopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy242\ (the trailing back-slash is important)

From a list of computers, find the srvcomment
for /f %i in (servers.txt) do @for /f "tokens=1,2,*" %m in ('"reg query \\%i\hklm\system\currentcontrolset\services\lanmanserver\parameters /v srvcomment 2>nul| find /i "srvcom" & if errorlevel 1 echo 1 2 {None}"') do @echo %i,%o

From a list of computers, find the AD computer account description
for /f %i in (servers.txt) do adfind -b "dc=domain,dc=local" -f "(&(objectClass=Computer)(objectCategory=Computer)(name=%i))" -csv -nocsvheader -nodn Name,description

Find an immediate but not very accurate way to count of files on a volume
fsutil fsinfo ntfsinfo C: & echo Divide Mft Valid Data Length / Bytes Per FileRecord Segment

Export a mailbox from 2003 Exchange that's greater than 2GB
cscript ExMBspanPst.vbs user01

Install Active Directory Administration tools for 2008 R2
servermanagercmd -install RSAT-ADDS

Robocopy in restartable mode (this slows down copy 10-20x)
robocopy . c:\dest /z

Mailbox-enable an AD user account in Exchange 2003
exchmbx -b "%userDN%,OU=domain,DC=local" -cr Exchange01:sg1:db1

Add to an SMS/SCCM collection
cscript c:\data\scripts\sms\AddDirectMembership.wsf server01 /c:"Collection01" /s:server01

Find a list of files and their size and date modified
for /f "tokens=*" %i in ('dir /s /a-d /b *.*') do echo "%i","%~zi","%~ti">> C:\Admin\Logs\DirList.txt

Parse a number of robocopy log files, showing the filename and total size/files
for %i in (\\server\c$\logs\robocopy*.log) do for /f "tokens=*" %m in ('"tail "%i" | findstr /i /c:" files :" /c:" bytes :""') do echo %i   %m

From a list of users, return which groups they have managedBy set for
adfind -b "DC=domain,DC=local" -f "(&(objectClass=User)(objectCategory=Person)(managedObjects=*))" managedObjects -list

Save ACLs in SDDL format
icacls g: /save ACLs.txt /t /c

Find msExchMasterAccountSid and decode to readable SID
adfind -b dc=domain,dc=local -f "(&(objectCategory=user)(msExchUserAccountControl=0)(msExchMasterAccountSid=*))" msExchMasterAccountSid distinguishedName -alldc -csv -nodn

View the DFS referral cache on the DFS client
dfsutil cache referral

Check Windows Server 2008 hardware installation/device/driver log files
C:\WINDOWS\INF\setupapi.dev.log

Remove the 'Authentication' tab from ncpa.cpl properties (kb950725)
sc \\%server% stop dot3svc

Check which .Net framework edition an assembly has been compiled for
c:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\x64\ildasm.exe

Use back-quoted for loops including special characters with ^ as escape for |
for %i in (*.xml) do for /f "tokens=* usebackq skip=1" %m in (`find /i "Install the telnet client on a Windows 2008 R2 server
servermanagercmd -install Telnet-Client

Enumerate DFS targets
wmic /node:server01 path win32_dfstarget get ServerName,LinkName,ShareName

View DFS referrals for XP/2003 clients
dfsutil /PKTINFO

Find DNS scavenging events from a 2008 R2 server
wmic /node:"server01" path Win32_NTLogEvent WHERE "SourceName='Microsoft-Windows-DNS-Server-Service' AND LogFile='DNS Server' AND EventCode=2501"

Check whether AD Bridge All Site Links is enabled or not (0x2)
dsquery * "CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration,dc=domain,dc=local" -attr options -scope base

Check whether Domain Controllers are responding on LDAPS
for /f %i in ('dsquery server -o rdn') do adfind -h %i:636 -default -s base

Display a tree-like structure using the canonical name of OUs
dsquery * -filter "(&(objectClass=OrganizationalUnit)(objectCategory=OrganizationalUnit))" -attr canonicalName | sort

Quickly count the number of files on a drive
c:\util\ndff.exe c:

Query information from the Dell WMI namespace (doesn't show disk status though)
wmic /node:%server% /namespace:\\root\cimv2\dell path dell_cmdevice

Check the firewall status for the domain profile from a number of servers
for /f %i in (Servers_20120117.txt) do @for /f "tokens=3" %m in ('"reg query \\%i\hklm\System\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy\DomainProfile /v EnableFirewall | find /i "enablefire" & if errorlevel 1 echo 1,2,NotFound"') do @echo %i,%m

Report directory usage of a directory and subdirectories
du -c -v c:\temp

Dump loaded DLLs and versoin information
listdlls  -v

Find TCP network connections on a remote machine using SNMP
snmputil walk localhost public .1.3.6.1.2.1.6.13.1.1

Query events from a 2008 event log
wevtutil qe System /q:"*[System[Provider[@Name='EventLog']]]" /e:events > events.xml

Create an eventlog entry
eventcreate /T ERROR /ID 1000 /L APPLICATION /D "Test"

Find proxy addresses filtered by SMTP type from a user account
adfind -b %i name mail displayName proxyaddresses -list -nocsvheader -mvfilter proxyaddresses=smtp

Query the SCP used by Autodiscover in Exchange 2007
dsquery * "CN=domain.local,CN=Microsoft Exchange Autodiscover,CN=Services,CN=Configuration,DC=domain,DC=local" -attr *

Parse IIS logs for OWA connections
findstr "SEARCH.\/exchange/.*\/Inbox" ex120130.log

Query SCCM sites and site servers
wmic /namespace:\\root\sms\site_S01 /node:server01 path SMS_Site

Query SCCM folders
wmic /namespace:\\root\sms\site_S01 /node:"server01" path  SMS_ObjectContainerNode

Query the IPMI WMI classes for Baseboard Management Controller (BMC) info
wmic /node:server01 /namespace:\\root\hardware path NumericSensor

Query the IPMI WMI classes for recent SEL events
wmic /node:server01 /namespace:\\root\hardware path LogRecord Where "MessageTimestamp > '20120110144951.000000+600'" Get MessageTimestamp,Description

Run Dell omreport to check disk status information from remote servers
for /f %i in (c:\temp\servers.txt) do psexec \\%i "C:\Program Files (x86)\Dell\SysMgt\oma\bin\omreport.exe" storage pdisk controller=0 > %i_physicaldisk.txt

Query IPMI for drive information (sometimes can tell disk failure)
wmic /node:server01 /namespace:\\root\hardware path Sensor Where "Name like 'Drive%'" Get Name,Description,CurrentState

Query a number of workstations for cross-forest logons
for /f %i in (c:\temp\servers.txt) do @dumpel -s %i -l application -m Userenv -e 1109 >> WorkstationCrossForestLogons.txt

Delete shadow copies (allows deleting backup shadows)
diskshadow delete shadows ID {shadowID}

Delete Internet Explorer policy restrictions prevending showing option tabs
reg delete "hku\S-1-5-21-3554533865-731492840-16770200-2139\software\policies\microsoft\internet explorer\control panel"

Find the Exchange 2007 AutoDiscover binding URL
dsquery * "CN=server01,CN=Autodiscover,CN=Protocols,CN=server01,CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=ORG,CN=Microsoft Exchange,CN=Services,CN=Configuration,dc=domain,dc=local" -attr *

Find the owner of an AD object
dsacls "CN={9596758E-5ADC-4639-A3A4-812835D92F6F},CN=Policies,CN=System,dc=domain,dc=local" /A

Find the default security descriptor applied to OU objects
adfind -b "CN=Organizational-Unit,CN=Schema,CN=Configuration,dc=domain,dc=local" defaultSecurityDescriptor

Automatic analysis of a memory dump created from a bugcheck/stop error
C:\Program Files\Debugging Tools for Windows (x64)\dumpchk.exe SRV*c:\websymbols*http://msdl.microsoft.com/download/symbols memory.dmp

Use SCCM Remote Control (requires rc.exe and rdpencom.dll)
rc 1 server01 \\sccm01

IIS logs on 2008 R2 IIS7 servers
\\%server%\c$\inetpub\logs\logfiles\W3SVC1\u_ex120317.log

Query IIS logs for OWA activity
logparser "SELECT cs-username, Count(*) AS OWAHits from c:\temp\u_ex120317.log WHERE cs-uri-stem LIKE '%OWA%' AND cs-username IS NOT NULL GROUP BY cs-username ORDER BY OWAHits Desc" -rtp:-1

Use LogParser to read event logs
"c:\Program Files\Log Parser 2.2\logparser" -i:evt "Select * from \\server01\system Where EventID = 1"

Use LogPartser to parse IIS logs for OWA statistics
logparser "SELECT cs-username, Count(*) AS OWAHits from \\server01\C$\INETPUB\LOGS\LOGFILES\W3SVC1\u_ex12031*.log WHERE cs-uri-stem LIKE '/owa/%' AND cs-username IS NOT NULL GROUP BY cs-username ORDER BY OWAHits Desc" -rtp:-1

Export local security policy with rights merged with domain policy
secedit /export /cfg security_domain.txt /mergedpolicy /areas user_rights

Export local security policy, including local and domain policy settings
secedit /export /cfg security.txt /areas user_rights

List all DFSR replication groups
dfsradmin rg list /attr:all

List all DFSR replication group memberships
dfsradmin Membership list /rgname:domain\share\dfs01 /attr:all

List all DFSR replication connections
dfsradmin conn list /rgname:domain\share\dfs01

Forcefully take ownership of files
takeown /f *.* /A /R

Query FEP forefront endpoint protection infection status
wmic /namespace:\\root\Microsoft\SecurityClient path AntimalwareInfectionStatus

Query the local anti-virus product
wmic /namespace:\\root\SecurityCenter path AntiVirusProduct

Query the local firewall product
wmic /namespace:\\root\SecurityCenter path FirewallProduct

Query an SCCM client for console user information
wmic /namespace:\\root\cimv2\sms path sms_systemconsoleuser

Query an SCCM client for top console user
wmic /namespace:\\root\cimv2\sms path sms_systemconsoleusage

Query profile last login information
wmic /node:server01 path Win32_NetworkLoginProfile get Name,LastLogon

Show the SDDL string for an ACL (redirect to console)
icacls \\server\share\directory /save con

Export ETL files to CSV
tracerpt MPTrace-04162012-125657.bin -o test.csv -of csv

Find the primary SMTP address and samaccountname from all mail-enabled users
adfind -b DC=domain,DC=local -f "(&(objectclass=User)(objectCategory=Person)(mailnickname=*))" samaccountname proxyaddresses -csv -nodn -mvfilter proxyaddresses=SMTP -mvfiltercs  > mailPrimary_20120310.txt

Use the SQL stored procedure to return column name and data type information
Sp_help TableName

Install the PowerShell Active Directory module on a 2008 R2 server
servermanagercmd -install RSAT-AD-PowerShell

Query the MX records for the specified domain
nslookup -type=mx domain.com 192.168.10.10

Query the managedObjects (managedBy back) to show managed groups
dsquery * "CN=user01,DC=domain,DC=local" -attr managedObjects

ADLDS LDAP debugging (logged to event viewer)
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ADAM_Test\Diagnostics /v "15 Field Engineering" /d 0x5 /t reg_dword & reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ADAM_Test\Parameters" /v "Expensive Search Results Threshold" /d 0x1 /t reg_dword

Produce a sorted lits of OUs
adfind -b dc=domain,dc=local -f "(&(objectClass=OrganizationalUnit)(objectCategory=OrganizationalUnit))" canonicalName description -csv -nocsvheader -nodn | sort > OU_ORG_20120614.csv

View all settings from a single window
md c:\temp\GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}

Anonymous bind to AD to query an object (operations error?)
adfind -b DC=domain,DC=local -h dc01 -f "(&(objectClass=User)(objectCategory=Person)(samaccountname=user01))" -u  -simple

Check whether SID filter (SID History) will be allowed across forest trusts
Netdom trust domain.local /domain domain.local /EnableSIDHistory

Query SCCM site information from Active Directory
dsquery * "CN=System Management,CN=System,DC=domain,DC=local" -filter (objectClass=mSSMSSite) -attr mSSMSSiteCode mSSMSAssignmentSiteCode mSSMSRoamingBoundaries

Query SCCM management point information from Active Directory
dsquery * "CN=System Management,CN=System,DC=domain,DC=local" -filter (objectClass=mSSMSManagementPoint) -attr mSSMSSiteCode mSSMSMPName

Query SCCM Service Locator Points (stored as SCPs) from Active Directory
dsquery * "CN=System Management,CN=System,DC=domain,DC=local" -filter (objectClass=mSSMSServerLocatorPoint) -attr mSSMSSiteCode mSSMSMPName

Find disabled user accounts without msExchMasterAccountSid set
adfind -b dc=domain,dc=local -f "(&(objectClass=User)(objectCategory=Person)(msExchUserAccountControl=2)(!(msExchMasterAccountSid=*)))" msExchMasterAccountSid distinguishedName -alldc -csv -nodn

Find enabled user accounts that have msExchMasterAccountSid set
adfind -b dc=domain,dc=local -f "(&(objectClass=User)(objectCategory=Person)(msExchUserAccountControl=0)(msExchMasterAccountSid=*))" msExchMasterAccountSid distinguishedName -alldc -csv -nodn

Restore the default domain controllers and default domain policy
dcgpofix /target:both

Query token groups for a resource forest access
ntdsutil "group membership evaluation" "set account dc dc01" "set resource dc rdc01" "run domain user01"

Query token suze for a resource forest access request (run on resource server)
tokensz /compute_tokensize /user:usetest /domain:dom /password:Passw0rd /dump_groups

Query group membership for the current access token
whoami /groups

Query SCCM packages and export to a CSV file
wmic /namespace:\\root\sms\site_org /node:"sccm01" path SMS_package get * /format:csv > sms_packages.csv

Use netdom to query the local FSMO role holders
netdom query fsmo

Query IIS logs to find Exchange OWA connections
echo SELECT cs-username, Date INTO STDOUT FROM \\server01\c$\inetpub\logs\LogFiles\W3SVC1\*,\\server02\c$\inetpub\logs\LogFiles\W3SVC1\* WHERE (cs-username IS NOT NULL) AND (sc-status = 200) AND (cs-uri-stem = '/owa/') AND (c-ip like '10.6%') GROUP BY Date, cs-username > c:\temp\WebAccess.sql & "c:\Program Files\Log Parser 2.2\LogParser.exe" file:c:\temp\WebAccess.sql -i:IISW3C -o:CSV > OWA_ExternalAccess_20120828.csv

Reset the EV client
cd "C:\Program Files\Microsoft Office\Office14" & "c:\Program Files\Enterprise Vault\EVClient\ResetEVClient.exe

Query SCCM Asset Intelligence user last logon information
sqlcmd -S sql01\sccm -d sccm -W -s "," -Q "SET NOCOUNT ON;Select distinct v_R_System.Netbios_Name0 AS 'Computer', v_R_System.AD_Site_Name0 AS 'AD Site', v_GS_SYSTEM_CONSOLE_USER.SystemConsoleUser0 AS 'Console User',v_GS_SYSTEM_CONSOLE_USER.NumberOfConsoleLogons0 AS 'Console Logons',v_GS_SYSTEM_CONSOLE_USER.TotalUserConsoleMinutes0 AS 'Total Minutes on Console',v_GS_SYSTEM_CONSOLE_USER.LastConsoleUse0 AS 'Last Console Use' from v_R_System INNER JOIN v_GS_SYSTEM_CONSOLE_USER ON v_GS_SYSTEM_CONSOLE_USER.ResourceID = v_R_System.ResourceID" > c:\temp\SCCM_AI_ConsoleUsers_20121030.txt

Find the FIM 2010 Service/Portal database server and name
reg query \\fimservice\hklm\System\CurrentControlSet\Services\FIMService | find /i "database"

Find the FIM 2010 Synchronisation Service database informtaion
reg query \\fimsync\hklm\System\CurrentControlSet\Services\FIMSynchronizationService\Parameters

Find the database recovery model for SQL databases on the specified server
sqlcmd -S sql01\db01 -d master -W -s "," -Q "SELECT name AS [Database Name], recovery_model_desc AS [Recovery Model] FROM sys.databases"

Performance Collector and viewer for ETW/ETL files
PerfView.exe

Clear DNS server cache
dnscmd dc01 /clearcache

Reset a locked user account
dsmod user -disabled no "CN=user1,OU=Users,DC=domain,dc=local"

Find DNS unconditional forwarders for a DNS server
dnscmd /info

Find full access and send-as mailbox rights for Exchange 2003
adfind -b "CN=user1,OU=Users,DC=domain,dc=local" msExchMailboxSecurityDescriptor ntsecuritydescriptor -alldc -sddc++ -resolvesids -mvfilter msExchMailboxSecurityDescriptor="FULL MBX";ntsecuritydescriptor="Send As"

Grant the AD right to poll for directory changes
dsacls "DC=domain,dc=local" /G "domain\group:CA;Replicating Directory Changes"

Find PCNS targets in Active Directory
dsquery * "CN=System,DC=domain,DC=local" -filter "(objectclass=mS-MIIS-PCNS-Target)" -attr *

Regular expression for numbers with spaces or brackets
'^[\d() -]+$'

Dump PCNS successfull password change logs
dumpel -s fimsync -l application -e 6902 -d 2 -m FIMSynchronizationService > c:\temp\PCNS_SuccessfulChanges.txt

Access terminal services shared drives
\\tsclient\c\temp

Query the logical names from a file backup set
RESTORE FILELISTONLY FROM disk='e:\temp\DB1.BAK'

Restore a SQL database, moving the files to new locations
RESTORE DATABASE "DB1" FROM DISK='e:\temp\DB1.BAK' WITH MOVE 'DB1' TO 'e:\MSSSQL\Data\db1.mdf', MOVE 'DB1_log' TO 'f:\MSSSQL\Log\DB1_log.ldf'; GO

Create a scheduled task that runs every day between 6am-6pm
SCHTASKS /Create /S fimservice /RU domain\user /RP Password /SC DAILY /MO 1 /TN "Repeated task" /TR ".\task.bat" /ST 06:00 /DU 12:00

Audit mailbox folder permissions (works on Ex2007 to mailbox servers)
PFDAVAdmin.exe

Custom pfdavadmin filter to only export calendar permissions
(&(0x3001001E=Calendar))

Parse IIS logs on Exchange 2007 for OWA access
"c:\Program Files\Log Parser 2.2\LogParser.exe" file:c:\temp\WebAccess.sql -i:IISW3C -o:CSV > OWA_InternalAccess_20120828.csv (sql: SELECT cs-username, Date INTO STDOUT FROM \\server01\c$\inetpub\logs\LogFiles\W3SVC1\*,\\server02\c$\inetpub\logs\LogFiles\W3SVC1\* WHERE (cs-username IS NOT NULL) AND (sc-status = 200) AND  (cs-uri-stem = '/owa/') AND  (c-ip like '10.6%')  GROUP BY Date, cs-username)

View FIM trace logs
svcTraceViewer.exe (win 7 sdk)

Boot disk to reset the local administrator password
cd080802.zip

Start Outlook with RPC diagnostics
"C:\Program Files\Microsoft Office\Office14\outlook.exe" /rpcdiag

Reset the protected flag on an AD ACL
dsacls "CN=user01,DC=domain,DC=local" /P:N

Find the Exchange autodiscover SRV record from DNS
nslookup -type=srv _autodiscover._tcp.domain.local

Verify a certificate's validity and CRL check
certutil -v -f -urlfetch -verify certificate.cer

Display the certificate URL cache entries
certutil /urlcache

Delete all certificate URL cache entries
certutil /urlcache * delete

Start the GUI to access the stored usernames (manage passwords) applet
control userpasswords2 (then click on 'manage passwords')

Add a stored credential for a SQL instance to use with trused windows auth
cmdkey /add:sql01.domain.com:49709 /user:domain\user01 /pass

Enable Internet Explorer add-on management (if disabled by policy)
reg add "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Internet Explorer\Restrictions" /v NoExtensionManagement /d 0x0

tracert with increased buffer size and higher timeout
c:\util\ftrace.exe -l 2048 -d -w 5000 host.domain

tracert with increased buffer size and lower timeout with 10 pings per hop
c:\util\ftrace.exe -l 2048 -d -w 500 -i 10 host.domain

Use outlook.exe to remove connected calendars and hidden messages (migration)
outlook.exe /resetnavpane

Find the domain/forest functinoal levels
adfind -sc modes

Find the major revision of the forest
dsquery * CN=ActiveDirectoryUpdate,CN=ForestUpdates,CN=Configuration,dc=domain,dc=local -attr revision

Find the ADDS Domain Controller capabilities from the directory
for /f "tokens=*" %i in ('dsquery server') do @adfind -b "CN=NTDS Settings,%~i" msDS-Behavior-Version -s base -csv -alldc -nocsvheader

Unlock a user account
dsmod user "CN=user01,DC=domain,DC=local" -disabled no

Check FIM performance counters and re-enable
lodctr.exe /q:FIMSynchronizationService && lodctr.exe /e:FIMSynchronizationService

Find the CLR version used by all processes running on the local computer
clrver -all

List the assemblies in the Global Assembly Cache on the local computer
gacutil -l

Query for global security groups
dsquery * -filter "(&(objectClass=Group)(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=-2147483646))" -limit 0

Query for local security groups
dsquery * -filter "(&(objectClass=Group)(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=-2147483644))" -limit 0

Query for universal security groups
dsquery * -filter "(&(objectClass=Group)(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=-2147483640))" -limit 0

Query Exchange 2010 EAS informatino from AD objects
dsquery * "CN=ExchangeActiveSyncDevices,CN=user01,OU=Users,DC=domain,DC=local" -filter (objectClass=msExchActiveSyncDevice) -attr msExchDeviceUserAgent msExchFirstSyncTime msExchDeviceModel msExchDeviceFriendlyName

VSS administration on 2003 (VSS 7.2 SDK)
vshadow.exe

Resynchronise performance counters with WMI
WINMGMT.EXE /RESYNCPERF

Query for an AD object using Ambiguous Name Resolution (ANR)
set dsquery * -filter (anr=martin)

Find attributes in the Partial Attribute Set replicated to Global Catalog DCs
adfind -b "CN=Schema,CN=Configuration,DC=domain,DC=local" -f "(&(objectclass=attributeSchema)(isMemberOfPartialAttributeSet=TRUE))" -csv > gc_pas.txt

Check the telephone number attribute for index information (searchFlags)
adfind -b "CN=Telephone-Number,CN=Schema,CN=Configuration,DC=domain,DC=local" -alldc

Open a specific folder with OWA (still requires full access to the mailbox)
https://owa.domain.local:443/owa/default.aspx?cmd=contents&module=calendar

Query AD with LDAP server controls
adfind -b CN=group1,OU=Groups,DC=domain,DC=local whenchanged -h 192.168.10.10 -alldc -srvctls 1.2.840.113556.1.4.417;1.2.840.113556.1.4.529;1.2.840.113556.1.4.2065  (LDAP_SERVER_SHOW_DELETED_OID, LDAP_SERVER_EXTENDED_DN_OID, LDAP_SERVER_SHOW_DEACTIVATED_LINK_OID)

Install the system.web.security.singlesignon.dll class on 2008 R2 for claims
servermanagercmd -install ADFS-Claims

Show cached/stored credentials GUI
rundll32.exe keymgr.dll, KRShowKeyMgr

Start a system command prompt interacting with the specified RDP session
psexec \\server01 /s /i 2 /d cmd

Parse Exchange IIS logs to find ActiveSync connections
 "c:\Program Files\Log Parser 2.2\LogParser.exe" "SELECT cs-username, Count(*) AS EASHits from \\cas01\c$\inetpub\logs\LogFiles\W3SVC1\u_ex130919.log,\\cas02\c$\inetpub\logs\LogFiles\W3SVC1\u_ex130919.log WHERE cs-uri-stem LIKE '%Microsoft-Server-ActiveSync%' AND cs-username IS NOT NULL GROUP BY cs-username ORDER BY EASHits Desc" -i:IISW3C -o:CSV > c:\temp\2010_EAS2_20130919.csv

Parse Exchange IIS logs to find ActiveSync connections per device
 "c:\Program Files\Log Parser 2.2\LogParser.exe" "SELECT cs-username AS UserID, cs(User-Agent) AS DeviceType, count (*) FROM \\cas01\c$\inetpub\logs\LogFiles\W3SVC1\u_ex130919.log,\\cas02\c$\inetpub\logs\LogFiles\W3SVC1\u_ex130919.log WHERE cs-uri-stem LIKE '%Microsoft-Server-ActiveSync%' AND cs-username IS NOT NULL GROUP BY UserID, DeviceType ORDER BY UserID" -i:IISW3C -o:CSV > c:\temp\2010_EAS2ByDevice_20130919.csv

Show the replication metadata for the specified AD object
repadmin /showobjmeta dc01 "CN=group1,OU=Groups,DC=lands,DC=domain,DC=local"

Show pending file rename operations
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager" /v PendingFileRenameOperations

Use the LDAP in chain matching rule to recursively find members of a group
dsquery * -filter "(memberOf:1.2.840.113556.1.4.1941:=CN=group1,OU=Groups,DC=lands,DC=domain,DC=local)" -s dc01

Open the 'choose profile' dialog box
start outlook /profiles

Use mfcmapi to view the message class and details of items
mfcmapi | Session | Logon and Display Store Table

Exchange 2010 exfolders (pfdavadmin replacement)
"\\cas01\c$\Program Files\Microsoft\Exchange Server\V14\Bin\ExFolders.exe"

Query for Exchange 2010 user mailboxes
adfind -b "OU=Shared Mailboxes,DC=domain,DC=local" -s onelevel -f "(&(objectClass=User)(objectCategory=Person)(msExchVersion=44220983382016))" samaccountname useraccountcontrol msexchmasteraccountsid -alldc -csv > SharedMailboxes_20131205.csv

Query lastlogon from every Domain Controller
repadmin /showattr * "CN=user01,OU=Users,DC=domain,DC=local" /attrs:lastLogon

Set the unconditional DNS forwarders for a server
dnscmd dns01 /ResetForwarders 192.168.10.1 192.168.10.2

Query NTFS journal USN (buggy)
usnjournalproject.exe

Query the fine-grained password policy settings from AD
dsquery * "CN=Password Settings Container,CN=System,DC=domain,DC=local"

Download symbols for windbg debugging
symchk /r c:\windows\system32\*.dll SRV*c:\windows\temp\symbols*http://msdl.microsoft.com/download/symbols

Find Outlook Auto Mapping attributes for links/backlinks
dsquery * -filter "(&(objectclass=user)(objectcategory=person)(|(msexchdelegatelistbl=*)(msexchdelegatelistlink=*))(extensionattribute5=DSITIA-Science))" -attr displayname msexchdelegatelistbl msexchdelegatelistlink

Access a shadow copy using a previous versions token pathname extension
dir \\server01\data\@GMT-2014.06.29-23.00.07\dir1

Extract an ISO file with 7ZIP
"C:\Program Files\7-Zip\7z.exe" x -y -oC:\temp\ISOFiles c:\downloads\cd1.iso

Modify the current power configuration to disable standby for AC power
powercfg -x -standby-timeout-ac 0

Query tombstoned AD objects
adfind -b dc=domain,dc=local -showdel -f isdeleted=TRUE > deletedObjects_20141014.txt

Query the current credential providers (gina/winlogon notification replacement)
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication" /s

Show a list of supported scenarios for netsh ETL tracing
netsh trace show scenarios

Query SCOM Audit Collection Services (ACS) database for 2008 creation events
select top 10 * from adtserver.dvall5 where EventId = 4720

Purge kerberos tickets from the system login ID
klist -li 0x3e7 purge

Disable hybrid sleep in the balanced power plan
powercfg -SETACVALUEINDEX 381b4222-f694-41f0-9685-ff5bb260df2e 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 0

Disable sleep in the balanced power plan
powercfg -SETACVALUEINDEX 381b4222-f694-41f0-9685-ff5bb260df2e 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0

Disable hibernate in the balanced power plan
powercfg -SETACVALUEINDEX 381b4222-f694-41f0-9685-ff5bb260df2e 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0

Disable NLA in an .RDP file for remote desktop/terminal services
enablecredsspsupport:i:0

Rename an AD object
dsmove "CN=user1,OU=Users,DC=domain,DC=local" -newname user2 -s dc01

Query an entire SQL database and all tables for the specified string
c:\util\QuerySQLDatabase.sql

Access a SharePoint server using a non-standard port using UNC
\\teamsite@5001\folder1\folder2\folder3

Perform a network capture on a Server 2012 server
Netsh Trace start capture = yes (followed by: Netsh Trace stop)

Show the domain-wide password policy
net accounts /domain

Check if pending reboot required prevents software installation (eg SQL 2008)
reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired

Find the SharePoint content databases and server
stsadm -o enumcontentdbs -url http://localhost

Query virtual directories on an IIS 7.x server (web or FTP)
appcmd list vdir & appcmd list site

Add an alternate computer name to AD
netdom COMPUTERNAME servernew /add serverold.domain.local

List the audit policy categories available
auditpol /list /category /v

List the audit policy subcategories available for the specifid category
auditpol /list /subcategory:"Object Access"

Modify the LM compatibility level to NTLMv2 only for RDP 8.1 (no reboot req.)
reg add HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA /v LMCompatibilityLevel /d 0x3 /t reg_dword

Show process permissions and token information
accesschk -p explorer.exe -f

Query the volume shadow copies available
volrest \\server01\Test1_20151007

List the certificate enrolment policy templates
certutil -template

Add a firewall rule to allow TCP:8080 inbound
netsh advfirewall firewall add rule name="Allow Tomcat In" dir=in protocol=TCP localport=8080 action=allow

Run a manual sync with ADConnect
"C:\Program Files\Microsoft Azure AD Sync\Bin\DirectorySyncClientCmd.exe"

MIISClient console for ADConnect
"C:\Program Files\Microsoft Azure AD Sync\UIShell\miisclient.exe"

Enable logging dropped local firewall connections
netsh advfirewall set domainprofile logging droppedconnections enable

Create a virtual RAM disk (not accessible through VIclient)
imdisk -a -s 536870912 -m R: -o rem -p "/fs:ntfs /q /y"

Create a virtual floppy disk backed by file (flp can be mounted through vi)
imdisk -a -s 1440K -f c:\temp\test1.flp -m R: -o fd -o shared -p "/fs:fat /q /y"

Return AD search index information on a query
adfind -b dc=domain,dc=local -f "(&(objectClass=User)(objectCategory=Person)(extensionattribute2=test))" samaccountname -stats+only

Extract cabinet files from patches (MSP)
msix patch.msp /out .

Find the supported SASL mechanisms of a directory
adfind -rootdse -s dc01

LDAP client tracing
reg add HKLM\System\CurrentControlSet\Services\ldap\tracing\Microsoft.IdentityServer.ServiceHost.exe & logman create trace ldap -p {099614a5-5dd7-4788-8bc9-e29f43db28fc} 0x1FFFDFF3 -o .\ldap.etl & logman start ldap & pause &   logman stop ldap & tracerpt.exe ldap.etl -o ldap2.csv -of CSV

Evalute SID count and token size for a user
dsmgmt "group membership evaluation" "run lands user01" quit quit

Run AdminSDHolder / SDProp process on PDC emulator
admod -sc runpag -h dc01.domain.local

Change the owner of a database to a SQL login
ALTER AUTHORIZATION ON DATABASE::Orchestrator TO [sa];

Enable RDP remotely
reg add "\\pc\HKEY_LOCAL_MACHINE\software\policies\microsoft\Windows NT\Terminal Services" /v fDenyTSConnections /d 0x0 /t reg_dword & sc \\pc stop termservice & sc \\pc start termservice

Find attributes marked as confidential
dsquery * CN=Schema,CN=Configuration,DC=domain,DC=local -filter "(searchFlags:1.2.840.113556.1.4.803:=128)

Query LAPS password and expiration
dsquery * -filter "(&(objectClass=Computer)(objectCategory=Computer)(ms-mcs-admpwd=*))" -s dc01 -attr name ms-mcs-admpwd ms-Mcs-AdmPwdExpirationTime

Query global and universal groups an account is a memberof
adfind -b "CN=user01,OU=Users,DC=domain,DC=local" -s base  TokenGroupsGlobalAndUniversal

Query for expiring user accounts
adfind -b "OU=Users,DC=domain,DC=local" -f "(&(objectClass=User)(objectCategory=Person)(!(|(accountExpires=9223372036854775807)(accountExpires=0))))" samaccountName accountexpires -alldc -csv > ExpiringAccounts_20170410.csv

Show current SQL server processes and blocks/locks
EXEC sp_who2

Start a process as the 'Network Service' account on an RDP session
psexec \\pc /i 3 /u "nt authority\network service" cmd.exe

Decrypt a bitlocked encrypted volume
manage-bde -off c:

Find the per-service SID for a service
sc showsid dnscache

Apply permissions to a per-service SID
icacls file.txt /grant *S-1-5-80-1458370022-919992539-2723553652-3559830572-560683627:(D,WDAC)

Export a task to XML
schtasks /query /xml /tn "daily delta sync" > "c:\temp\Daily.xml"

Create a task from XML
schtasks /create /xml "c:\temp\Daily.xml" /ru domain\svc_account /rp * /tn "Daily Delta Sync"

Upgrade from standard to datacentre 2008 R2 using KMS datacentre key
dism /online /set-edition:ServerDatacenter /productkey:74YFP-3QFB3-KQT8W-PMXWJ-7M648 /AcceptEula

Find the .Net Framework 3.5 version installed
reg query "\\server01\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5

Find the .Net 2.0 CLR version (used by .Net 3.5)
filever \\server01\c$\Windows\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll

check the HTTP listener session status
netsh http show servicestate view="session"

Enable http.sys verbose ETW tracing
logman start httptrace -p Microsoft-Windows-HttpService 0xFFFF -o c:\temp\httptrace.etl -ets

Kill a TCP connection
wkillcx.exe 192.168.10.10:5725

Modify the default TTL you seen when pinging a machine (default 128)
netsh int ipv4 set glob defaultcurhoplimit=63

Wait for a crashdump for the specified process and write a full dump
Procdump.exe -t -ma -o Microsoft.ResourceManagement.Service.exe C:\CrashDumps

Enable SCHANNEL informational logging
reg add \\server01\HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL /v EventLogging /d 0x7  /t reg_dword

Show the current firewall profile
netsh advfirewall show currentprofile

Show Win 10 Azure device registration status
dsregcmd.exe /status

Disable NetBIOS over TCP/IP
wmic nicconfig get caption,index,TcpipNetbiosOptions & wmic nicconfig where index=7 call SetTcpipNetbios 2

Query stored credentials
vaultcmd /listcreds:"Windows Credentials" /all

Find registry hives loaded
reg query \\server01\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist

Query ETL providers
logman query providers

Find the certificate a host is using for https
nmap.exe -n -Pn -p443 outlook.office.com --script ssl-cert

Query DNS Conditional fowarders
reg query "\\dc01\hklm\software\microsoft\windows nt\currentversion\DNS Server\Zones\domain.local"

Temporarily disable policy and allow basic auth for WinRM
reg add "HKLM\Software\Policies\Microsoft\Windows\WinRM\client" /v AllowBasic /d 0x1 /t reg_dword & winrm set winrm/config/service/auth '@{Basic="true"}'

Find the public key token of a DLL
"c:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\sn" -T c:\temp\MicrosoftServices.IdentityManagement.WorkflowActivityLibrary.dll

Grant permissions to the private keys of a certificate using RK tools
WinHttpCertCfg.exe -g -c LOCAL_MACHINE\My -s "Server Data Encryption" -a "domain\svc_service"

Start an elevated command prompt as another user
runas /user:domain\user01 "powershell.exe -command \"start-process -verb runas cmd\""

Find tokenGroups to show SIDs of groups a person is a member of
adfind -b "CN=user01,OU=Users,DC=domain,DC=local" -s base tokengroups

Find the SDDL for the specified event log on a remote computer
wevtutil gl /r:dc01 security

Update the SDDL for the specified event log on a remote computer
psexec \\dc01 wevtutil sl Security /ca:O:BAG:SYD:(A;;CCLCSDRCWDWO;;;SY)(A;;CCLC;;;BA)(A;;CC;;;ER)(A;;CC;;;NS)

Show the ephemeral dynamic RPC port range currently configured
netsh int ipv4 show dynamicport tcp

Show the Windows Firewall filters matching run-time IDs in event logs
Netsh.exe WFP Show State

Query BitLocker recovery information confidential attribute from AD
dsquery * -filter "(&(objectClass=msFVE-RecoveryInformation))"

Check the schema to see if an attribute is confidential (searhcFlags=0x128)
adfind -b "CN=ms-FVE-RecoveryPassword,CN=Schema,CN=Configuration,DC=domain,DC=local" -alldc searchflags

Redirect the output of a command to the clipboard
dsquery user -samid user01 | clip

sysinternals TCP network connectivity check
psping fimservice:5725

Query the triggers for a service (ie stop when not domain joined)
sc qtriggerinfo w32time

View SharePoint log files, and Outlook trace files
ulsviewer.exe

List the certificate templates from a CA
certutil -CATemplates -config "CA1.domain.local\Internal Issuing CA 1 SHA256"

View the alternate data streams in a file
streams

Query the DNS block list
dnscmd dc1.domain.local /info /globalqueryblocklist

Export security policy on a 2016 Core DC
secedit /export /cfg c:\windows\temp\security.inf /log c:\windows\temp\sec.log

Query accounts configured with unconstrained delegation
dsquery * -filter "(&(objectCategory=Person)(objectClass=User)(userAccountControl:1.2.840.113556.1.4.803:=524288))"

Query for people who don't have domain users as primary group
adfind -b "OU=Users,DC=domain,DC=local" -f "(&(objectClass=User)(objectCategory=Person)(!primarygroupID=513))" samaccountname -csv

Revert Windows 10 to the old Alt+Tab experience
reg add HKEY_USERS\S-1-5-21-123660284-1234560955-123430997-1234\Software\Microsoft\Windows\CurrentVersion\Explorer /v AltTabSettings /t reg_dword /d 0x1

Set the number of explorer thumbnails to 1 so they're stacked with 2+ instances
reg add HKEY_USERS\S-1-5-21-123660284-1234560955-123430997-1234\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Taskband /v NumThumbnails /t reg_dword /d 0x1

Wayne's World of IT (WWoIT). 


Read more!

Exchange PowerShell Commands #2

Well it's 2020, and instead of flying around in a hovercar I'm *still* doing IT. Trying to get back in the swing of things – and following on from the last post seven year ago (!?), here's an additional 64 Exchange commands circa Exchange 2013/2016.

Each command can be copied and pasted into a PowerShell command line running with an Exchange PSSession, although at the time I made notes on a couple of them about running locally on the server due to cmdlet or type casting limitations.



Remove an existing Exchange 2010 move request (to allow subsequent moves)
Remove-MoveRequest -id user01

Initiate an Exchange 2010 intra-org move request
new-moverequest -id user01 -TargetDatabase db02

Output semi-colon delimited list of email addresses for a mailbox
[string]::Join(';',$mailbox.emailaddresses)

Convert a mailbox to a standard user mailbox
get-mailbox user01 | set-mailbox -type regular -whatif

Modify permissions to allow modifying apply policy attributes of user objects
Add-ADPermission -Identity "OU=Resources,DC=domain,DC=local" -InheritanceType Descendents -InheritedObjectType user -AccessRights ReadProperty, WriteProperty -Properties msExchPoliciesIncluded, msExchPoliciesExcluded -User "domain\group1" -domaincontroller dc01

Disable an Exchange 2007 mailbox - leaving the user account in AD
Disable-Mailbox -id user01

Reapply the mandantory properties on a mailbox (changing from linked to normal)
set-mailbox -id $account -applymandatoryproperties  #Clearing AEA and master account SID resets the isLinked property of the mailbox, but RecipientTypeDetails / RecipientDisplayType is not automatically updated.  Re-applying mandatory properties corrects this issue and sets the mailbox back to being a user mailbox instead of a linked mailbox

Find Exchange 2010 DAG status
Get-DatabaseAvailabilityGroup -status | fl *

Find Exchange 2010 DAG replication status
$servers = Get-MailboxServer; foreach ($server in $servers) { Get-MailboxDatabaseCopyStatus -server $server.name}

Find the mailbox activation preference for an Exchange 2010 mailbox database
(Get-MailboxDatabase -id MBXDB1).ActivationPreference

Report the last 1000 commands executed
Get-history -count 1000

Reseed the content index catalog for the database copy
Update-MailboxDatabaseCopy "DB\SERVER" -CatalogOnly

Get the mailbox database copy status
Get-MailboxServer | Get-MailboxDatabaseCopyStatus -ExtendedErrorInfo | sort-object ContentIndexState | fl Name,ContentIndexState,ContentIndexErrorMessage

Convert a user mailbox to a linked mailbox without disabling
Set-User -id user01 -LinkedMasterAccount domainb\user01 -LinkedDomainController dc01.domainb.com -LinkedCredential $domainbcred # may need get-mailbox -id user01 | set-mailbox -type regular; get-mailbox -id user01 | set-mailbox -ApplyMandatoryProperties

Find the current owner of Exchange 2010 mailbox databases
dsquery * "CN=Databases,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=Dept,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domain,DC=local" -filter (objectclass=msExchMDB) -attr Name msExchOwningServer -s dc2

Mount an Exchange 2010  public folder database
Get-PublicFolderDatabase -id 'Public Folder Database 1' | mount-database

Find an Exchange 2010 Primary Active Manager for the specified DAG
Get-DatabaseAvailabilityGroup -Status | fl PrimaryActiveManager

Configure the Exchange 2010 postamaster address
Get-TransportConfig | fl -ExternalPostmasterAddress; Set-TransportConfig -ExternalPostmasterAddress postmaster@domain.com

Enumerate outlook profiles to find connected mailboxes and calendars
EnumOutlookProfiles.ps1

Find if an Exchange 2010 mailbox is enabled for ActiveSync
get-casmailbox -id user1

Set Exchange 2010 calendar processing to anyone can book and autoaccept
Set-CalendarProcessing -Identity room01 -AutomateProcessing AutoAccept -AllBookInPolicy $true

Get Exchange 2010 mailbox calendar configuration
Get-MailboxCalendarConfiguration -id room01 | fl *

Force an update of the offline address book
Update-OfflineAddressBook -id 'Default Offline Address List'

Exchange query for Global Security groups
get-group -filter "GroupType -eq $([Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::SecurityEnabled.value__ + [Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::Global.value__)"; #get-group -filter {GroupType -eq '-2147483646'}

Exchange query for Domain Local Security groups
get-group -filter "GroupType -eq $([Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::SecurityEnabled.value__ + [Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::DomainLocal.value__)"; #get-group -filter {GroupType -eq '-2147483644'}

Exchange query for Universal Security groups
get-group -filter "GroupType -eq $([Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::SecurityEnabled.value__ + [Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::Universal.value__)"; #get-group -filter {GroupType -eq '-2147483640'}

Set Out Of Office on a mailbox
Set-MailboxAutoReplyConfiguration 'user1' -AutoReplyState enabled -ExternalAudience all -InternalMessage "Internal not Here" -ExternalMessage "External not here"

Get a role group from the root of the forest
Get-RoleGroup -id Exchange-Lvl1Support -DomainController dc1.forest.root

Get a role group and the roles and role assignments
$rg = Get-RoleGroup -id Exchange-Lvl1Support -DomainController dc1.forest.root; $rg.roles; $rg.roleassignments

Get a management scope to show the recipient root and filter
Get-ManagementScope -id MS-Exchange_Distribution-Groups | fl *

Get the management role assignments for the specified assignee
Get-ManagementRoleAssignment | where {$_.RoleAssigneeName -like '*Exchange-Lvl1Support*'} | ft -wrap -auto

Get the management role assignment to confirm the CustomRecipientWriteScope
Get-ManagementRoleAssignment -id Distribution-GroupCreation | fl *

Expand the e-mail addresses of a mailbox to one per line
get-mailbox -id user1 | select -expand emailaddresses

Find Distribution List expansion
$expandDL = foreach ($server in Get-TransportServer) {Get-MessageTrackingLog -EventID EXPAND -resultsize unlimited -server $server | select "Timestamp","ServerHostname","EventId",{$_.RelatedRecipientAddress},{$_.Sender},"MessageSubject"}

Convert a mailbox from linked to resource
$ADsPath = "LDAP://CN=user1,OU=Shared Mailboxes,DC=domain,DC=local"; $user = [ADSI]$ADsPath ; $user.putex(1,"msExchMasterAccountSid",$null); $user.setinfo(); get-mailbox -id user1 | set-mailbox -ApplyMandatoryProperties; get-mailbox -id user1 | set-mailbox -type shared

Find mailboxes on a specific version of exchange (2010)
$mailboxes = get-mailbox -filter {ExchangeVersion -eq 44220983382016} -resultsize unlimited

Find the Exchange 2010 SP1+ Address Book RPC port
reg query \\cas1\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\MSExchangeAB\ParametersSystem /v RpcTcpPort

Find the Exchange 2010 RPC port
reg query \\cas1\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\MSExchangeRPC\ParametersSystem /v "TCP/IP Port"

Mail-enable an existing AD contact
Enable-MailContact -id "CN=User 01,OU=Contacts,DC=domain,DC=local" -ExternalEmailAddress user@somewhere.com

Modify the MRS mailbox replication for move requests
notepad "\\cas1\c$\Program Files\Microsoft\Exchange Server\V14\Bin\MSExchangeMailboxReplication.exe.config" (MaxActiveMoves* and MaxTotalMovesPerMRS)

Find Exchange 2010 recoverable deleted items
Get-MailboxFolderStatistics -Identity "user@domain.com" -FolderScope RecoverableItems | ft -wrap -auto

Export mailbox to PST in EX2010 (requires Exchange Trusted Subsystem ACLs)
New-MailboxExportRequest -Mailbox user@domaincom -FilePath \\cas1\d$\martinwa.pst

Check the move history of a mailbox
get-mailboxstatistics -id "CN=user1,DC=domain,DC=local" -includemovehist | fl Identity,MoveHistory

Check Exchange 2010 logon statistics to see who is logging on to a mailbox
get-mailbox -id user1 | get-logonstatistics | ft UserName,ServerName,LogonTime,LastAccessTime,Windows2000Account -wrap -auto

Set mailbox delivery restrictions to only allow accepting messages from (ndr)
Set-Mailbox -Identity user1 -AcceptMessagesOnlyFrom @{add="user2"} -whatif

Use Exchange 2010 cmdlets to change the CN/DisplayName of a security group
get-adgroup -id oldsamid | set-adgroup -SamAccountName newsamid -whatif

Find safe and blocked senders configured through Outlook for each mailbox
$mailboxes | Get-MailboxJunkEmailConfiguration | export-csv -path c:\temp\JunkEmailConfiguration_20140625.csv

Delete all the items from an Exchange 2010 mailbox
Search-Mailbox -id user@domain.com -DeleteContent -confirm:$false -force

restore specific folders from a disconnect mailbox data to a recovery mailbox
New-MailboxRestoreRequest -BatchName Recovery -Name Test.User -SourceDatabase 'MBXDB5' -SourceStoreMailbox "2e94ffc9-9dad-42b1-92ec-5767d11051e4" -excludedumpster -includeFolders "Contacts/Misc", "Contacts/MISC/SHOPPING", "Contacts/MISC/Work Related" -TargetMailbox "recovery1" -AllowLegacyDNMismatch -whatif

Find Exchange 2010 RBAC management role entries for the specified role
Get-ManagementRole  -id RecipientCreationUserMailboxes | select -expand roleentries;  $entries = (Get-ManagementRole  -id RecipientCreationMailUser).RoleEntries; $entries | %{$_.split()[1]}

Find Exchange 2010 RBAC management scope OU and filter for the specified scope
Get-ManagementScope -id Managed-Users_UserMailboxes  | fl Identity,RecipientFilter,RecipientRoot

Search Exchange 2010 Admin Audit log for changes made by Exchange
Search-AdminAuditLog | ft -wrap -auto

export Exchange 2010 Admin Audit Log for new-mailbox requests and callers
$newUsers = Search-AdminAuditLog -cmdlets New-Mailbox,New-MailUser; $newUsers | select RunDate,ObjectModified,CmdletName,Caller,OriginatingServer | export-csv -path c:\temp\ExchangeUsers_20141020.csv -encoding ascii

Get Exchange mail queues on the specified server
get-queue -Server mail02

Get Exchange mail queue information
get-queue -Identity MAIL02\281950 | fl DeliveryType,NextHopDomain,Status,MessageCount,LastError

Find disconnected mailboxes (run on console of exchange server, not session)
get-mailboxdatabase | Get-MailboxStatistics | where {$_.displayName -eq 'User 01' -and $_.DisconnectDate -ne $null}

Report AD permissions through Exchange cmdlets
Get-ADPermission -id "OU=Distribution Lists,OU=Resources,DC=domain,DC=local" |ft Identity,User,InheritedObjectType,ExtendedRights,Properties,ChildObjectTypes,AccessRights -wrap -auto

Add an address to an exchange 2010 object
Set-MailUser -id "user1" -EmailAddresses (((Get-MailUser -id "user1").EmailAddresses)+="smtp:usernew@domain.com") -whatif

Remove an address from an exchange 2010 object
$recipient = "user1"; $remove = "smtp:usernew@domain.com"; Set-MailUser -id $recipient -EmailAddresses ((Get-MailUser -id $recipient).EmailAddresses | where {$_ -ne $remove}) -whatif

Remove an address from an exchange 2010 object with AD cmdlets
$recipient = "user1"; $remove = "smtp:usernew@domain.com"; Set-ADUser -id $recipient -replace @{proxyAddresses=([system.object[]](Get-ADUser -id $recipient -prop proxyAddresses | Update-List -Property proxyAddresses -Remove $remove).proxyaddresses)} -whatif

Find Outlook Auto Mapping attributes for links/backlinks
get-adobject -LDAPFilter "(&(objectclass=user)(objectcategory=person)(|(msexchdelegatelistbl=*)(msexchdelegatelistlink=*)))" -prop displayname,msexchdelegatelistbl,msexchdelegatelistlink | select displayname,msexchdelegatelistbl,msexchdelegatelistlink | ft -wrap -auto

Exchange cmdlet to query the UPN suffix list
Get-UserPrincipalNamesSuffix

Find people that have upgrated to iOS 7.0 on EAS connected devices
get-adobject -ldapfilter "(&(objectClass=msExchActiveSyncDevice)(objectCategory=msExchActiveSyncDevice)(msExchDeviceOS=ios*7.0*))" -prop msExchDeviceOS,canonicalName -server dc1

Apply a throttling policy association to a standard user or MEU
Set-ThrottlingPolicyAssociation -Identity svc_mw -ThrottlingPolicy Office365MigrationWiz

Wayne's World of IT (WWoIT). 


Read more!

Tuesday, April 2, 2013

Exchange PowerShell Commands

It's been a long time between drinks...

However, I have still been quietly squirreling away useful command lines, with the following 166 commands used for Exchange 2007/2010 information gathering, automating configuration management, troubleshooting and many bits in between.

Each command can be copied and pasted into a PowerShell command line running the Exchange snap-in loaded with the default prefix, although you may need to adjust input such as distinguished names, server names, mailbox names etc.

Let me know if you find them useful.



Get mailboxes that have a space in the displayName
get-mailbox -filter "(displayname -like '* *')" | ft identity,database -wrap -auto

Find Exchange transport rules
Get-TransportRule | ft Name,Priority,{$_.Conditions | select Name,{$_.Words}},{$_.Actions | select Name,Rank,SclValue},Comments -wrap -auto 

Find Exchange 2007 mailbox servers in the local organisation
get-mailboxserver

Get mailbox statistics for mailbox servers with the specified name
get-mailboxserver | where {$_.Name -like 'server*'} | Get-MailboxStatistics | Sort-Object TotalItemSize -Descending | select-object -prop DisplayName,LastLogonTime,StorageLimitStatus,TotalItemSize,TotalDeletedItemSize,@{N="Size (MB)";E={$_.TotalItemSize.Value.ToMB()}},@{N="Deleted Item Size (MB)";E={$_.TotalDeletedItemSize.Value.ToMB()}},ItemCount,ServerName,StorageGroupName,DatabaseName.LegacyDN | export-csv -path c:\temp\MailboxStatistics.csv

Get mailbox database size limit/quota settings on malibox stores
get-mailboxdatabase | select-object -prop Name,ServerName,StorageGroup,ProhibitSendReceiveQuota,ProhibitSendQuota,IssueWarningQuota | ft -wrap -autosize

Find the number of mail-enabled contacts in the organisation
get-mailcontact -ResultSize 'unlimited' | measure

Export the IP addressed allowed to relay through the specified connector
$rc = Get-ReceiveConnector -id 'server01\connector01'; $rc.RemoteIPRanges | export-csv -path c:\temp\rc1.csv

Exchange 2007 global transport size limits
get-transportconfig | ft -prop MaxReceiveSize,MaxSendSize -wrap -autosize   

Exchange 2007 transport server sizelimits
get-transportserver | ft -prop Name,OriginatingServer,InternalDsnMaxMessageAttachSize,ExternalDsnMaxMessageAttachSize -wrap -autosize

Exchange 2007 send connector size limits
get-sendconnector | ft -prop Identity,AddressSpaces,MaxMessageSize -wrap -autosize

Exchange 2007 receive connector size limits
get-receiveconnector | ft -prop Identity,AddressSpaces,MaxMessageSize -wrap -autosize

Exchange 2007 mailbox limits other than unlimited
get-mailbox |where {$_.MaxSendSize -ne 'unlimited' -or $_.MaxReceiveSize -ne 'unlimited'} | ft -prop Identity,MaxSendSize,MaxReceiveSize -wrap -autosize

Get the storage group copy status (CCR/LCR/SCR) for mailbox stores 
get-mailboxserver | where {$_.Name -like 'server*'} | Get-StorageGroupCopyStatus  | ft -wrap -autosize

Get storage groups and their SCR stand-by machine
Get-StorageGroup  | ft -prop Name,Server,StandbyMachines -wrap -autosize

Get the storage group copy status (SCR) for the first target on all SGs
Get-StorageGroup | %{Get-StorageGroupCopyStatus -id $_.Identity -StandbyMachine $_.StandbyMachines[0].NodeName} | sort -prop LastReplayedLogTime | select -prop Identity,SummaryCopyStatus,ServiceDown,CopyQueueLength,ReplayQueueLength,LatestAvailableLogTime,LastCopyNotificationedLogTime,LastCopiedLogTime,LastInspectedLogTime,LastReplayedLogTime,LatestFullBackupTime | export-csv -path c:\temp\SCR_Status.csv

Get the storage group copy status (SCR) for the specified server/target
Get-StorageGroupCopyStatus -Server server01 -standbymachine server01 | ft -wrap -autosize

Find the backup status and whether VSS was used for the backup
Get-StorageGroup | %{Get-StorageGroupCopyStatus -id $_.Identity -StandbyMachine $_.StandbyMachines[0].NodeName} | sort -prop LatestFullBackupTime | select -prop Identity,SummaryCopyStatus,ServiceDown,LatestFullBackupTime,SnapshotBackup  | export-csv -path c:\temp\MailboxBackup_Status.csv

Change an Exchange 2007 mailbox type to equipment (or room)
Set-Mailbox MailboxName -Type Equipment

Add full access mailbox permissoins for an Exchange 2007 mailbox
Add-MailboxPermission -Id MailboxName -User:'DOMAIN\group' -AccessRights:FullAccess

Add send as rights to the AD security of a mail-enabled user
Add-ADPermission -Id MailboxName -User:'DOMAIN\group' -ExtendedRights:Send-As

Find mailboxes that are not standard user mailboxes (Room, Equipment)
get-mailbox | where {$_.RecipientTypeDetails -ne 'UserMailbox'} | fl -prop Name,RecipientTypeDetails

Remove mailbox permissions for the specified user
Remove-MailboxPermission MailboxUser -User DOMAIN\User -AccessRight FullAccess    

Find exchange mailbox statistics including per-user mailbox and DB limits 
. C:\data\scripts\PowerShell\Exchange\FindMailboxSizes.ps1 | out-file -file c:\temp\MailboxStats.txt -encoding ascii

Find the AutomateProcessing setting for a resource mailbox
Get-MailboxCalendarSettings  -id mailboxID

Modify a resource mailbox to automatically accept in-policy requests
Set-MailboxCalendarSettings -id mailboxID -AllBookInPolicy:$true 

Find the mailbox type of one or more mailboxes
get-mailbox -id mailboxes* | fl -prop IsResource,RecipientType,RecipientTypeDetails,ResourceType

Find the debug event logging levels set on an Exchange 2007 server
Get-EventLoglevel -server ExchangeServer01

Set the equipment mailbox to auto-accept and allow anyone to automatically book
Set-MailboxCalendarSettings -Identity "mailbox01" -AutomateProcessing AutoAccept -AllBookInPolicy $true

Turn on high logging for the booking attendant
Set-EventLogLevel "server01\MSExchangeMailboxAssistants\Resource Booking Attendant" -Level High

Find all resource mailboxes of type equipment
get-mailbox |where {$_.resourcetype -eq 'Equipment'}

Read Exchange 2007 event logs for the MSExchangeMailboxAssistants (resources)
get-eventlog -logname application -computer server01 -source msexchangemailboxassistants

Check Exchange Message Tracking Logs based on message ID
Get-MessageTrackingLog -MessageId 'FBE264977E286848971C4C15BDD7F5FE439245C5EF@mx.company.com.au' -Start "05/07/2011 00:00:00" -End "07/07/2011 06:00:00" -server server01

Check Exchange Message Tracking Logs based on mail subject
Get-MessageTrackingLog -MessageSubject "RE: Subject" -Start "06/07/2011 00:00:00" -End "07/07/2011 00:00:00" -server server01

Find Exchange server version, edition and roles
Get-ExchangeServer | sort | select-object -prop Name,Role,Edition,ServerRole,Site,ExchangeVersion,AdminDisplayVersion | export-csv -path c:\temp\ExchangeServers.csv

Find the mailbox sizes in Exchange 2007 looking at the filesystem
Get-MailboxDatabase | foreach-object {add-member -inputobject $_ -membertype noteproperty -name mailboxdbsizeinGB -value ([math]::Round(([int64](get-wmiobject cim_datafile -computername $_.server -filter ('name=''' + $_.edbfilepath.pathname.replace("\","\\") + '''')).filesize / 1GB),2)) -passthru} | Sort-Object mailboxdbsizeinGB -Descending | format-table identity,mailboxdbsizeinGB 

Update the allowed IP addresses for an Exchange 2007 receive connector
$connector = Get-ReceiveConnector -id 'server01\connector01'; $connector.RemoteIPRanges += "192.168.20.10-196.168.20.20"; Set-ReceiveConnector 'server01\connector01' -RemoteIPRanges $connector.RemoteIPRanges

Move a mailbox to a new database
Move-Mailbox -id user01 -targetdatabase 'server01\sg01\db01' 

View the original warning quota message
Get-SystemMessage -original | where {$_.Identity -like 'en\warn*'}

Add a new warning quota message
New-SystemMessage -QuotaMessageType WarningMailbox -Language EN -Text "Please reduce your mailbox size! Delete any items you don't need from your mailbox and empty your Deleted Items folder."

Hide a mailbox from the GAL
get-mailbox -id user01 | set-mailbox -HiddenFromAddressListsEnabled:$true

Remove SID History from a user
get-aduser -id 'user01' -prop sIDHistory | foreach {set-aduser $_ -remove @{sIDHistory=$_.sIDHistory.value}}

Remove SID history from one or more groups
Import-Module ActiveDirectory; $groups = get-content -path groups_sAMAccountName.txt; foreach ($group in $groups) {get-adgroup -id $group -prop sIDHistory | foreach {set-adgroup $_ -remove @{sIDHistory=$_.sIDHistory.value}}}

Remove multiple attributes from an AD account
$user = get-aduser -id 'user01' -prop HomeDrive,HomeDirectory,ProfilePath; set-aduser $user -HomeDrive $null -HomeDirectory $null -ProfilePath $null

Enumerate public folders
Get-PublicFolder -server server01 -Recurse | ft -wrap -autosize

Restore a deleted user account using AD recycle bin
$deletedaccount = get-adobject -filter 'samaccountname -eq "user01"' -IncludeDeletedObjects -properties *; $deletedaccount | restore-adobject

Reconnect a mailbox to an AD user account 
$user = Get-MailboxStatistics -server server01 | where {$_.displayName -eq 'User01, Test' -and $_.DisconnectDate -ne $null}; Connect-Mailbox -Identity $user.Identity -Database $user.database -User DOMAIN\user01

Group and list the mailboxes on each mailbox store 
get-mailboxdatabase -server server01 | get-mailbox | Group-Object -prop database | ft -wrap -autosize

Create new mail contacts from CSV input in Exchange 2007
$dataSet = Import-Csv -path contacts.csv; foreach ($contact in $dataset)  {  New-MailContact -ExternalEmailAddress $contact.targetaddress -Name $contact.cn -DisplayName $contact.displayName -FirstName $contact.givenName -LastName $contact.sn -OrganizationalUnit domain.local/Contacts -PrimarySmtpAddress $contact.mail}

Set the primary mail AD attribute of a newly created Exchange 2007 contact
$contacts = get-mailcontact -OrganizationalUnit 'domain.local/Contacts' | where {$_.Name -like 'test*'} ; foreach ($contact in $contacts) {  set-mailcontact -id $contact.identity -WindowsEmailAddress $contact.PrimarySmtpAddress;  $contact.HiddenFromAddressListsEnabled = $true; }

Create a new basic authenticated send connector in Exchange 2007
$pass = Read-Host "Password?" -assecurestring; $credential = new-object System.Management.Automation.PSCredential("domain\username",$pass); $cred = get-credential -Credential $credential; New-SendConnector -Name "send01" -AddressSpaces * -AuthenticationCredential $cred -SmartHostAuthMechanism BasicAuth -DNSRoutingEnabled:$false -SmartHosts smtp.local

Find users who have been delegated send on behalf of rights to a mailbox
$delegates = Get-Mailbox 'room01' | select-object GrantSendOnBehalfTo; $delegates.GrantSendOnBehalfTo.toarray()

Find NDR 5.1.4 duplicate mail addresses from Exchange application event logs 
get-eventlog -logname 'Application' -computer server01 -after "28/10/2011 8:00:00" | where {$_.eventID -eq 3029}

Replace the primary SMTP email address 
Get-Mailbox -id 'user01' | Set-mailbox -EmailAddressPolicyEnabled $false; Get-Mailbox -id 'user01' | Update-List -Property EmailAddresses -Add "SMTP:user01@domain.local" | Set-Mailbox; Get-Mailbox -id 'user01' | Set-mailbox -EmailAddressPolicyEnabled $true

Add a new secondary SMTP address 
Get-Mailbox -id 'user01' | Update-List -Property EmailAddresses -Add "smtp:user01@domain.local" | Set-Mailbox

Check Exchange 2007 queues
Get-Queue -server server01 | ft -wrap -autosize

Find the public delegates for a mailbox and then reset to a new list
Get-Mailbox -id user01 | select -expand GrantSendOnBehalfTo; Get-Mailbox -id user01 | Set-Mailbox -grantSendOnBehalfto User02,User03,User04

Export Exchange client connection statistics (online/cached mode, client ver) 
$dateshort = [DateTime]::Now.ToString("yyyyMMddhhmmss"); get-mailboxserver | get-logonstatistics | select * | export-csv -path ("c:\temp\ExchangeLogonStats_" + $dateshort  + ".csv"); write-host ("c:\temp\ExchangeLogonStats_" + $dateshort  + ".csv")

Get a mailbox from the domain sAMAccountName 
get-mailbox -id 'domain\username' | fl *

Change the sAMAccountName of a mailbox-enabled user account
get-mailbox -id 'domain\user001' | set-mailbox -samaccountname user01

Change the Name/CN/DN of a mailbox-enabled user account
get-mailbox -id 'domain\user' | set-mailbox -DisplayName "User, Test" -Name "User, Test"

Change the alias of a mailbox object
get-mailbox -id 'domain\user' | set-mailbox -alias user01

Check if a mailbox exists
if (get-mailbox -id user01 -ErrorAction SilentlyContinue) {write-host "test"}

Find the oldest and newest dates of mailbox folders
get-mailboxfolderstatistics -id user01 -FolderScope Inbox -IncludeOldestAndNewestItems

Find Exchange logs for messages that failed to deliver
Get-MessageTrackingLog  -Start "21/12/2011 6:00:00" -server server01 | where {$_.eventId -eq 'Fail'} | ft * -wrap -autosize

Find messages where delivery failed 
Get-MessageTrackingLog -EventId FAIL -Start "20/12/2011 6:00:00" -server server01 | ft TimeStamp,Source,EventID,Recipients,Sender,RecipientStatus -wrap -autosize 

See which mailboxes a user has direct permissions to access
get-mailbox -OrganizationalUnit 'domain.local/Mailboxes/Shared' | get-mailboxpermission | where {$_.user -like 'domain\user01'}

Find mailboxes that have a specified ACE set
get-mailbox -OrganizationalUnit 'domain.local/Mailboxes/Shared' | get-adpermission | where {$_.AccessRights -contains 'WriteProperty' -and $_.Properties -like 'Personal-Information'} | ft -wrap -autosize

Find active sync utilisation for mailboxes
Get-Mailbox -ResultSize:Unlimited |ForEach {Get-ActiveSyncDeviceStatistics -Mailbox:$_.Identity} |ft identity,devicemodel,LastSuccessSync,LastPolicyUpdateTime,DeviceType,DeviceID,DeviceUserAgent,LastPingHeartbeat,DeviceFriendlyName,DeviceOS,DeviceIMEI,DevicePhoneNumber

Find SMTP mail delivery failures
foreach ($server in Get-TransportServer) {Get-MessageTrackingLog -EventId FAIL -Start "01/01/2012 6:00:00" -server $server.name | where {$_.recipients -like '*@*' -and $_.recipients -notlike '*@local.com' -and $_.recipients -notlike 'IMCEAEX*'} | ft EventId,Source,Sender,Recipients -wrap -autosize}

Find the owner of one or more mailboxes
get-mailbox -id user01 | get-adpermission -owner | ft -wrap -autosize

Get the Exchange 2007 organisation config
Get-OrganizationConfig

Find the Exchange 2007 accepted domains (authoritative and relay)
Get-AcceptedDomain

Find logs for distribution list expansion
foreach ($server in Get-TransportServer) {Get-MessageTrackingLog  -EventId EXPAND -Start "29/02/2012 17:28:00" -server $server.name | ft Timestamp,Sender,RelatedRecipientAddress,Recipients,RecipientStatus -wrap -autosize}

Find logs for e-mail from a specific address
foreach ($server in Get-TransportServer) {Get-MessageTrackingLog  -Sender "user01@external.com"  -Start "29/02/2012 17:28:00" -server $server.name | ft Timestamp,Recipients,RecipientStatus,Sender -wrap -autosize}

Find logs for failed messages
foreach ($server in Get-TransportServer) {Get-MessageTrackingLog  -EventId FAIL -Start "29/02/2012 17:28:00" -server $server.name | ft Timestamp,Recipients,RecipientStatus,Sender -wrap -autosize}

Find logs for messages from the last minute
foreach ($server in Get-TransportServer) {Get-MessageTrackingLog -start (Get-Date).AddMinutes(-1)  -server $server.name | ft Timestamp,Sender,RelatedRecipientAddress,Recipients,RecipientStatus -wrap -autosize}

Find mail attributes for a public folder
get-mailpublicfolder -id "\Folder01\SubFolder01" | fl *

Find Exchange 2007 Web Services
Get-WebServicesVirtualDirectory | fl *

Find Exchange Message Tracking messages from a particular client IP
foreach ($server in Get-TransportServer) {Get-MessageTrackingLog -resultsize unlimited -start (Get-Date).AddMinutes(-15) -server $server.name | where {$_.ClientIp -eq '192.168.1.10'} | ft * -wrap -autosize}   

Report explicit OU security for OUs in the domain
$ous = dsquery ou "dc=domain,dc=local" -limit 0; $permissions = foreach ($ou in $ous) {Get-ADPermission -id $ou.replace('"','') | where {$_.IsInherited -eq $False -and $_.User -like 'DOMAIN\*'}}; $permissions | select Identity,User,Deny,{$_.ChildObjectTypes},{$_.AccessRights},{$_.Properties},{$_.InheritedObjectType} | export-csv -path c:\temp\OU_Permission_20120309.csv

Find OWA Internal/External URL configuration
Get-OwaVirtualDirectory | where {$_.name -eq 'owa (Default Web Site)'} | ft Server,Name,InternalUrl,ExternalUrl -wrap -autosize 

Find transport server message tracking configuraiton 
Get-TransportServer | fl Name,messagetra*

List the available event logs from a remote server
Get-EventLog -computer server01 -list

List the Exchange 2007 diagnostic logging configuration
Get-EventLogLevel -server server01 | ft -wrap -autosize

Enable connectivity logging for Exchange 2007 Edge/Hub transport servers
get-TransportServer -id server01 | set-transportserver -ConnectivityLogEnabled:$true

View messages in the queue
get-queue -server server01 | get-message -IncludeRecipientInfo | fl *

Find recipients with a filter based on department
get-recipient -filter '((Department -eq "DEPT") -and (Alias -ne $null))'

Find users that do not have the specified primary SMTP address domain
get-recipient -filter '(ObjectClass -eq "User")' -resultsize:unlimited | where {$_.PrimarySmtpAddress -notlike "*@domain.local"} | ft Identity,PrimarySmtpAddress -wrap -autosize

Export to CSV users that don't have the specified primary SMTP domain
get-recipient -filter '(ObjectClass -eq "User")' -resultsize:unlimited | where {$_.PrimarySmtpAddress -notlike "*@domain.local"} | select Identity,PrimarySmtpAddress,Department | export-csv -path c:\temp\PrimarySMTP.csv

Expand a nested distribution group, counting all mail recipients
. C:\data\scripts\PowerShell\Exchange\ExpandDL.ps1 "CN=DL01,OU=Groups,dc=domain,dc=local"       

Find the user and SID on mailbox permissions (useful when sidhistory is used)
get-mailboxpermission -id user01 | ft User,{$_.user.securityidentifier} -wrap -auto

Find mailbox enabled users with a first/last name using ActiveDirectory
$users = get-aduser -filter {givenName -like '*' -and sn -like '*' -and mailnickname -like '*'}

Find user mailbox recipients that have a first and last name set
$mailboxes = get-recipient -resultsize unlimited -filter "(firstName -like '*' -and lastname -like '*' -and Alias -like '*' -and RecipientType -eq 'UserMailbox')"; foreach ($mailbox in $mailboxes) {  $firstName = $mailbox.firstname.replace(" ", "");   $lastName = $mailbox.lastname.replace(" ", "");   $primary = $mailbox.EmailAddresses | where {$_.IsPrimaryAddress -eq $true -and $_.PrefixString -eq "SMTP"} ;   $mailSplit =  $primary.SmtpAddress.split(".@");   if ($firstName -ne $mailSplit[0] -or $lastName -ne $mailSplit[1]) {    Write-Host $primary.SmtpAddress;   }}

Find mail recipients that don't have a first or last name (shared mailboxes)
$mailboxes = get-recipient -resultsize unlimited -filter {firstName -eq $null -and lastname -eq $null -and Alias -like '*' -and RecipientType -eq 'UserMailbox'}

Find mailboxes with the specified domain name
get-mailbox -filter {emailaddresses -like '*@domain.local'}

Find mailboxes with the specified domain name as their primary address
get-mailbox -filter {emailaddresses -like '*@domain.local'} | get-mailbox | where {$_.primarysmtpaddress -like '*@domain.local'}

Find distribution lists that can be emailed externally
$dls = get-distributiongroup -resultsize unlimited -filter {Alias -ne $null -and RequireAllSendersAreAuthenticated -eq $true}

Update the accept from for a DL with a list of users
$users = "User01, Test", "User02, Test"; foreach ($user in $users) {$user = get-mailbox -id $user; if ($user) {Get-DistributionGroup -id "DL01" | Update-List -Property AcceptMessagesOnlyFrom -Add $user.distinguishedName | Set-DistributionGroup }}

Update a distribution list to allow sending only from another DL
set-distributiongroup -id dl01 -AcceptMessagesOnlyFromDLMembers dl02

Find the user accounts for mailbox recipients with first and last name 
$mail = get-user -filter {(FirstName -ne $null -and LastName -ne $null)} -RecipientTypeDetails UserMailbox,LinkedMailbox -resultsize unlimited -OrganizationalUnit "OU=Mailboxes,dc=domain,dc=local" | select FirstName,LastName,windowsemailaddress

Find users that don't conform to first.last@ email addresses
$mail = get-user -filter {(FirstName -ne $null -and LastName -ne $null)} -RecipientTypeDetails UserMailbox,LinkedMailbox -resultsize unlimited -OrganizationalUnit "OU=Mailboxes,dc=domain,dc=local" | select FirstName,LastName,windowsemailaddress

Create a new transport rule setting SCL based on subject or body text
$condition = Get-TransportRulePredicate SubjectOrBodyContains; $condition.words = "SCL=9"; $action = Get-TransportRuleAction SetSCL; $action.sclvalue = 9; New-TransportRule -name "Filter01" -Condition $condition  -Action $action

Find mailboxes configured to forward and report details
$outputFile = "c:\temp\EmailForward_" + ([DateTime]::Now.ToString("yyyyMMddhhmmss")) + ".csv"; get-mailbox -filter {forwardingaddress -ne $null} | sort -prop whenChanged -descending | select whenChanged,SamAccountName,Identity,DeliverToMailboxAndForward,ForwardingAddress, @{N='ForwarderPrimarySMTPAddress';E={$recipient = get-recipient -id $_.ForwardingAddress; if ($recipient.recipienttype -eq 'MailContact') {write-output $recipient.externalemailaddress.tostring().replace("SMTP:","")} else {write-output $recipient.primarysmtpaddress}}},@{N='RecipientType';E={$recipient = get-recipient -id $_.ForwardingAddress; write-output $recipient.recipienttype.tostring()}} | export-csv -path $outputFile; write-host $outputFile

Turn on send connector verbose logging
get-sendconnector -id 'SendConnect01' | set-sendconnector -ProtocolLogginglevel verbose

Find NDR 5.4.6 routing loops in the last day from all transport servers
foreach ($server in Get-TransportServer) {Get-MessageTrackingLog -resultsize unlimited -EventId FAIL -Start (Get-Date).AddDays(-1) -server $server.name | where {$_.RecipientStatus -like '*5.4.6*'} | ft Timestamp,Recipients,RecipientStatus,Sender -wrap -autosize}

Find email addresses that aren't using first.last
foreach ($user in $mail) { if (!($user.windowsemailaddress.tostring().tolower().contains($user.firstname.tolower().replace(' ', '') + '.' + $user.lastName.tolower().replace(' ', '') + '@'))) { write-host $user.windowsemailaddress} }

Export a mailbox to PST
export-mailbox -id user01 -PSTFolderPath c:\temp\user01.pst

Find the Exchange 2003 global restrictions in AD for envelope recipients
Get-ADObject -id "CN=Message Delivery,CN=Global Settings,CN=ORG,CN=Microsoft Exchange,CN=Services,CN=Configuration,dc=domain,dc=local" -prop msExchRecipLimit

Find the Exchange 2007/2010 global restrictions in AD for envelope recipients
Get-ADObject -id "CN=Transport Settings,CN=ORG,CN=Microsoft Exchange,CN=Services,CN=Configuration,dc=domain,dc=local" -prop msExchRecipLimit

Find the Exchange 2007 transport settings for max enveople recipients
Get-TransportConfig | fl MaxRecipientEnvelopeLimit

Update managedBy for a distribution group
get-distributiongroup -id DL01 | Set-DistributionGroup -ManagedBy "CN=user01,OU=Mailboxes,dc=domain,dc=local"

Get the offline address book update schedule 
$oab = Get-OfflineAddressBook; $oab.schedule | ft -wrap -auto

Find the offline address book server, PF database and web distribution point
Get-OfflineAddressBook | fl Server,PublicFolderDatabase,VirtualDirectories

Find the Offline Address Book virtual directory
Get-OabVirtualDirectory | ft -wrap -auto

Find the custom resource schema configuration for custom resource properties
Get-ResourceConfig

Gather public folder statistics
$pfstats = Get-PublicFolderStatistics -server server01

Start the Exchange Management Shell from a standard powershell instance
add-pssnapin  Microsoft.Exchange.Management.PowerShell.Admin; . "C:\Program Files\Microsoft\Exchange Server\bin\Exchange.ps1"

Send an SMTP e-mail with PowerShell 2.0 or later
send-mailmessage -from $sendfrom -to $sendto -subject $subject -body $body -BodyAsHtml -smtpServer $smtpserver

Add an availability address space to access local public folder schedule+ FB
Add-AvailabilityAddressSpace -ForestName remote.address.space -AccessMethod PublicFolder

Query free/busy schedule+ public folder replica information
get-publicfolder -Identity "\NON_IPM_SUBTREE\SCHEDULE+ FREE BUSY"  -Recurse | ft Name,OriginatingServer,Replicas -wrap -auto

Query free/busy schedule+ public folder information on Exchange 2007/2010
get-publicfolder -Identity "\NON_IPM_SUBTREE\SCHEDULE+ FREE BUSY"  -Recurse | Get-PublicFolderItemStatistics | ft PublicFolderName,Subject -wrap -auto

Show the e-mail addresses for the specified user in list format
((Get-Mailbox user01).EmailAddresses)

Add a secondary e-mail address in Exchange 2010 to a mailbox user
Set-Mailbox user01 -EmailAddresses (((Get-Mailbox user01).EmailAddresses)+="smtp:user01@test.com")

Add a secondary e-mail address in Exchange 2010 to a MEU
Set-MailUser testuser01 -EmailAddresses (((Get-MaiLUser testuser01).EmailAddresses)+="smtp:testuser01@new.domain.com") -whatif

Update the targetAddress attribute for an ADSI object
$user = [adsi]"LDAP://CN=testuser01,OU=Migrated,DC=domain,DC=local"; $user.put("targetAddress","smtp:testuser01.User@new.domain.com")

List the client-side public folder permissions for all public folders
$pfperms = Get-PublicFolder -recurse | Get-PublicFolderClientPermission

Get the report from a Exchange 2010 new-moverequest operation
$MoveReport = (Get-MailboxStatistics -Identity user01 -IncludeMoveReport).MoveHistory

Add to the managedBy property of a distribution list
set-distributiongroup -id $group -managedby (((get-distributiongroup -id $group).managedby) += $user.identity.distinguishedName)

Find the current management roles that have distribution in the name
Get-ManagementRoleAssignment | where {$_.name -like '*recipient*'} -warningaction silentlycontinue | ft -wrap -auto

Find CAS array information for an Exchange 2010 installation
get-clientaccessarray

Find delegate access to a mailbox with Exchange 2010 SP1
adfind -b "DC=domain,DC=local" -f "(&(objectClass=User)(objectCategory=Person)(msExchDelegateListLink=*))" -h dc01.domain.local samaccountname msExchDelegateListLink

Find delegate access to a mailbox with Exchange 2010 SP1 through backlink
adfind -b "DC=domain,DC=local" -f "(&(objectClass=User)(objectCategory=Person)(MsExchDelegateListBL=*))" -h dc01.domain.local samaccountname MsExchDelegateListBL

Convert legacy global distribution groups to universal
Get-Group -ResultSize Unlimited -RecipientTypeDetails NonUniversalGroup -OrganizationalUnit "OU=Distribution Lists,OU=Resources,DC=domain,DC=local" | Where-Object {$_.GroupType -match 'global'} | Set-Group -Universal

Mail-enable legacy global DLs that have been converted to universal
Get-Group -ResultSize Unlimited -RecipientTypeDetails UniversalDistributionGroup -OrganizationalUnit "OU=Distribution Lists,OU=Resources,DC=domain,DC=local"  | enable-distributiongroup

Change group scope for non-universal groups to universal
Get-DistributionGroup -ResultSize Unlimited -RecipientTypeDetails MailNonUniversalGroup | Set-Group -Universal

Upgrade Exchange 2010 legacy groups
Get-DistributionGroup -ResultSize Unlimited | Set-DistributionGroup -ForceUpgrade

Extract all properties of one or more users and save to CSV
get-aduser -ldapfilter "(&(objectClass=User)(objectCategory=Person)(samaccountname=*.exchtest*))" -prop * | export-csv -path c:\temp\TestUsers.csv

Create a new display name with surname in UPPER and first in Title case
$newName = $user.LastName.toUpper() + ' ' + (Get-Culture).textinfo.totitlecase($user.FirstName)

Start a remote powershell session to an exchange 2010 namespace
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://cas01.domain.local/PowerShell/ -Authentication Kerberos;   Import-PSSession $Session

Start a remote powershell session to an exchange 2010 namespace using prefix
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://cas01.domain.local/PowerShell/ -Authentication Kerberos;   Import-PSSession $Session -prefix ResForest

Bitwise OR to whether whether grouptype is distribution or security
if (14 -bor 2147483648 -eq 14) {write-output "Distribution} else {write-output "Security"}

Find mailbox folder permissions in Exchange 2010
$mailbox = get-mailbox -id user01; get-mailboxfolderpermission -id ($mailbox.primarysmtpaddress.tostring() + ":\Calendar")

Find the Exchange 2010 autodiscover URL (then stored in SCP)
Get-ClientAccessServer | fl *autodisc*      

Find Exchange 2010 RBAC management roles
Get-ManagementRole -id 'Distribution Groups' | fl *

Find Exchange 2010 RBAC management role assignments
Get-ManagementRoleAssignment |where {$_.role -eq 'Distribution Groups'} | ft -wrap -auto

Select the value of a property as an array of strings rather noteproperty
$members = get-adgroup "CN=group,DC=domain,DC=local" -server $dc | get-adgroupmember -server $dc | %{write-output $_.SamAccountName.ToString()}

Convert a group from security to distribution
get-adgroup -id migtestdl3 | set-adgroup -GroupCategory 0

Find recipient info from multiple forests and group by primary SMTP domain
$recipients = get-recipient -domaincontroller dc01.domain.local -OrganizationalUnit "OU=People,DC=domain,DC=local" -filter {(firstName -ne $null -and LastName -ne $null) -and (RecipientType -eq 'UserMailbox')} -resultsize unlimited ; $recipients += get-recipient  -domaincontroller targetdc.target.domain -OrganizationalUnit "OU=People,DC=target,DC=domain" -filter {(firstName -ne $null -and LastName -ne $null) -and (RecipientType -eq 'UserMailbox')} -resultsize unlimited ; $recipients | select @{N='EmailDomain';e={$_.primarysmtpAddress.tostring().split("@")[1]}} | group-object -prop EmailDomain | sort -prop Count | ft -wrap -auto

Find mailboxes from multiple forest and info on e-mail domain and islinked
$mailboxes = get-recipient -domaincontroller dc01.domain.local -OrganizationalUnit "OU=People,DC=domain,DC=local" -filter {(firstName -ne $null -and LastName -ne $null) -and (RecipientType -eq 'UserMailbox')} -resultsize unlimited  | get-mailbox -domaincontroller dc01.domain.local; $mailboxes += get-recipient  -domaincontroller dc01.taret.domain -OrganizationalUnit "OU=People,DC=target,DC=domain" -filter {(firstName -ne $null -and LastName -ne $null) -and (RecipientType -eq 'UserMailbox')} -resultsize unlimited | get-mailbox -domaincontroller dc01.target.domain; $mailboxes | select OriginatingServer,@{N='EmailDomain';e={$_.primarysmtpAddress.tostring().split("@")[1]}},IsLinked | group-object -prop OriginatingServer,EmailDomain,IsLinked | sort -prop Count | ft Count,Name -wrap -auto  

Find mailboxes with an ActiveSync device partnership
get-casmailbox -resultsize unlimited  | where {$_.HasActiveSyncDevicePartnership -eq 'true'}

Find the preferred domain controllers for the current Exchange 2010 session
Get-ADServerSettings | fl *

Set domain controller configuration for an exchange server
Set-ExchangeServer -StaticConfigDomainController dc01 StaticDomainControllers dc01,dc02 -StaticExcludedDomainControllers dc03 -StaticGlobalCatalogs gc01

Link an Exchange 2010 mailbox to a cross-forest security principal
get-mailbox user01 | set-mailbox -LinkedMasterAccount domain\user01 -linkeddomaincontroller dc01.domain.local

Get Exchange 2010 IMAP settings
Get-IMAPSettings -Server cas01

Disable policy and update the primary SMTP address of a 2010 mailbox 
get-mailbox -id "CN=user01,OU=People,DC=domain,DC=local" | set-mailbox -EmailAddressPolicyEnabled $false -PrimarySmtpAddress user01@domain.local

Find the server generating the Offline Address Book
Get-OfflineAddressBook | ft server,guid,AddressLists -wrap -auto (files stored in C:\Program Files\Microsoft\Exchange Server\V14\ExchangeOAB\)

Prepare an Exchange 2010 cross-forest move (create MEU and merge contact)
.\Prepare-MoveRequest.ps1 -Identity $username -RemoteForestCredential $cred -RemoteForestDomainController dc01.domain.local -LinkedMailUser -MailboxDeliveryDomain domain.local -TargetMailUserOU "OU=Resource Forest Accounts,DC=domain,DC=local" -UseLocalObject

Initiate an Exchange  2010 cross-forest move request
New-MoveRequest -Identity $username -RemoteLegacy -RemoteGlobalCatalog dc01.domain.local -TargetDatabase 'DB01' -RemoteCredential $cred -TargetDeliveryDomain 'domain.local' ?Verbose

Get an Exchange 2010 move request report
$moverequest = Get-MoveRequestStatistics -id user01 -IncludeReport; $moverequest.report

Get all the mailbox users in an OU and set a user property
get-mailbox -org "OU=Resource Forest Accounts,DC=domain,DC=local" | set-user -company 'Company01'

Check Exchange 2010 CAS RPC Client Access stats for online mode
$matches = select-string -pattern "2013-03" -simple -path "\\cas01\c$\Program Files\Microsoft\Exchange Server\V14\Logging\RPC Client Access\RCA_201303*"; $results = foreach ($match in $matches) {$line = $match.line;   write-output $line }; $results | out-file -file c:\temp\rpcusage.txt -encoding ascii; $rpc = import-csv -path c:\temp\rpcusage.txt -header date-time,session-id,seq-number,client-name,organization-info,client-software,client-software-version,client-mode,client-ip,server-ip,protocol,application-id,operation,rpc-status,processing-time,operation-specific,failures; $classic = $rpc | where {$_.'client-mode' -eq 'Classic' -and $_.'client-software' -eq 'outlook.exe'}; $classic | select client-name | group-object -prop client-name | ft -wrap -auto Count,Name

Find Exchange 2007/2010 mailbox statistics in MB (not with remote powershell)
get-mailbox -id user* | get-mailbox | get-mailboxstatistics | select DisplayName,ItemCount,@{n='SizeMB';e={$_.TotalItemSize.value.tomb()}} | ft -wrap -autosize

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


Read more!

Sunday, August 15, 2010

vSphere Storage vMotion traffic

This post provides information on storage vMotion in VMware vSphere 4 with ESXi 4.0 U2 hosts. While using storage vMotion to move data between unconnected storage, I conducted some simple testing to identify the networks and ports used for vMotion.

I’ve never seen an explanation of how storage vMotion works, and while it seems kind of obvious in retrospect, I thought some people might find this interesting.


Summary

  1. The scope of a storage vMotion operation is datacenter wide, not limited to clusters or which host can see which storage.
  2. In the testing conducted, storage vMotion relies upon the management network to transfer the disk data between the two ESXi hosts
  3. If this method was used to import a large number of VMs from foreign storage then the limitation would typically be the 1GB vmnic used for the management network.
  4. To allow the migration between datastores not visible by a single host, the VM would also be migrated between hosts.

Scenario

Two hosts managed by single vCenter instance, vc01:
  1. esx01 part of the CLUS1 cluster
  2. esx02 not in a cluster
  3. esx01, connected only to the iSCSI SAN 1
  4. esx02, connected only to the iSCSI SAN 2

Management network on vmk0 using two GbE interfaces on both hosts. Vmk0 on the management network with load balancing based on the virtual port ID.

Test

The test conducted was using storage vmotion to move a virtual machine through VirtualCenter on vc01 from a datastore visible only to esx02 to a datastore visible only to esx01.
  1. The source datastore was LUN02 (visible only to esx02) and the destination datastore was LUN01 (visible only to esx01).
  2. vMotion was used to automatically migrate the VM from esx02 to esx01 (as the VM had moved storage)

Traffic and network usage observed

  1. On esx02 unsupported console, vmk0 source 192.168.0.12.60504 (esx02), destination 192.168.0.11.902 (esx01).
  2. Command: /bin/tcpdump-uw -I vmk0 -nn

esx02
  1. MbRx 190Mb/sec on software iSCSI NIC – Reading the disk information from iSCSI SAN 2 for the VM
  2. MbTx 136Mb/sec – Transmit the information across the management network to esx01.
  3. Command: resxtop --server esx02 (‘n’ for network information)

esx01
  1. MbRx 120Mb/sec – receiving the disk data from esx02 across the management network
  2. MbTx 200Mb/sec on software iSCSI NIC – writing the data to the SAN across the iSCSI network
  3. Command: resxtop --server esx01 (‘n’ for network information)

The following diagram shows the traffic flow of storage vMotion on an iSCSI network:


Read more!

Saturday, August 14, 2010

Resizing a VM's Windows system OS with Set-HardDisk

With vSphere PowerCLI Update 1 there is now an automated method of increasing the system disk of a virtual machine. This essentially performs the same thing as I’ve been doing manually for a while now - the disk is resized and mounted to a ‘helper vm’ and diskpart extends the disk, the helper VM is then shutdown and the risk removed, and when the resized VM starts up the OS prompts for a final reboot after detecting the disk change.

Note that both the target and helper VM must be powered off, and credentials must be passed or the helpervm argument is ignored. The guest credentials are used on the Windows helper VM to authenticate using the VMtools mechanism to invoke a command inside a VM.


$guetsusername = "domain\username"
$guestpass = Read-Host "Guest password (administrator of the server)?" -assecurestring
$hostusername = "root"
$hostpass = Read-Host "Host Password (VI SDK access to the ESX host)?" -assecurestring
$hostcredential = new-object System.Management.Automation.PSCredential($hostusername, $hostpass)
$guestcredential = new-object System.Management.Automation.PSCredential($guetsusername, $guestpass)
$sizeGB = 30
$sizeKB = $sizeGB *1024*1024
$harddisk = Get-HardDisk -vm vm01
Set-HardDisk -HardDisk $harddisk[0] -capacityKB $sizeKB -hostcredential $hostcredential -guestcredential $guestcredential -helpervm $vm



An error occurred when trying to use domain credentials to pass to the vCenter SDK – host credentials are required, not credentials to vCenter (which seems odd).

Set-HardDisk -HardDisk $harddisk[0] -capacityKB 31457280 -hostcredential $hostcredential -guestcredential $guestcredential -helpervm helpervm
Set-HardDisk : 4/02/2010 1:25:04 PM    Set-HardDisk    919835D1-AD13-41DF-ABDE-D630E96FE722    While performing operation 'Connect to host service 'https://esx01/sdk' at port 902' the following error occured: 'Insufficient permissions in host operating system'
At line:1 char:13
+ Set-HardDisk  <<<< -HardDisk $harddisk[0] -capacityKB 31457280 -hostcredential $hostcredential -guestcredential $guestcredential -helpervm helpervm




Another error occurred when trying to resize a VM, the script used failed.  Note that I tried this manually and it also failed (must have been something particular to that VM).  It was interesting to see that from this it looks like the cmdlet uses the invoke-vmscript to run a remote script through the VMtools interface that calls the diskpart commands.
Set-HardDisk : 4/02/2010 11:22:11 AM    Set-HardDisk    919835D1-AD13-41DF-ABDE-D630E96FE722    Execution of the  script in guest OS on VM 'helpervm' failed: '
Microsoft DiskPart version 5.2.3790.3959
Copyright (C) 1999-2001 Microsoft Corporation.
On computer: HELPERVM
Disk 1 is now the selected disk.
Volume 2 is the selected volume.
The volume you have selected may not be extended.
Please select another volume and try again.
'
At line:1 char:13
+ Set-HardDisk  <<<< -HardDisk $harddisk[0] -capacityKB 31457280 -hostcredential $hostcredential -guestcredential $guestcredential -helpervm $vm



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


Read more!

Sunday, May 9, 2010

Keeping Citrix sessions alive with sendkeys

I use the following script as a way of keeping my Citrix session alive to thwart security guys and their over-aggressive timeouts.

Normally I don't like to use sendkeys, but this seemed like the perfect way to trick ica into thinking keys were being pressed...

PowerShell and VBScript versions below.



#
# Find the wfica.exe process and poke keystrokes at it, preventing a Citrix session from timing out
# Be careful what you have open and what keystrokes you poke

[System.Object[]]$processes = get-process | where {$_.ProcessName -eq "wfica32.exe"}
if ($processes.count -ge 1) { $process = $processes[0] }

if ($process -is [System.Diagnostics.Process])
{
  $processes | format-list -property *

  for (;;)
  {
    [void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")

    [Microsoft.VisualBasic.Interaction]::AppActivate($process.Id)
    start-sleep -seconds 1

    [void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
    [System.Windows.Forms.SendKeys]::SendWait("1")
    start-sleep -seconds 240
  }

}





Set objWshShell = CreateObject("Wscript.Shell")

strProcessName = "wfica32.exe"

intProcessID = 0
Call FindProcessID(strProcessName, intProcessID)

if (intProcessID > 0) Then
 wscript.echo "Found process ID: " & intProcessID

 Do 
  objWshShell.AppActivate(intProcessID)
  WScript.Sleep 1000
  objWshShell.SendKeys "1"
  WScript.Sleep 240000
 Loop

End If


Function FindProcessID(ByRef strProcessName, ByRef intProcessID)

 strQuery = "Select * from Win32_Process Where Name = '" & strProcessName & "'" ' WQL query string looking for the specified process

 Set objNameSpace = GetObject("winmgmts://./root/cimv2")    ' The cimv2 namespace of the local machine

 FindProcessID = vbFalse
 Set objProcessSet = objNameSpace.ExecQuery(strQuery)     ' Execute the query
 For Each objProcess in objProcessSet      ' For each process in the set, ordered by oldest to newest
  intProcessID = objProcess.ProcessID
  WScript.Echo "Found process, ID: " & intProcessID
  WScript.Echo objProcess.Name & ", " & intProcessID & ", " & objProcess.CreationDate & ", " & objProcess.CommandLine & ", " & objProcess.Priority & ", " & objProcess.WorkingSetSize & ", " & objProcess.PageFileUsage
  FindProcessID = vbTrue
 Next

 Set objNameSpace = Nothing : Set objProcessSet = Nothing : Set objProcess = Nothing
End Function


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


Read more!

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. 


Read more!

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.