Scripting

Free Scripts:http://www.rlmueller.net/freecode4.htm –wonderful link for scripting 
WMI Query Language by Example: http://www.codeproject.com/Articles/46390/WMI-Query-Language-by-Example
MS link for scripts:http://gallery.technet.microsoft.com/scriptcenter/
Script Home:http://www.computerperformance.co.uk/Logon/logon_scripts.htm
Power shell script:http://technet.microsoft.com/en-us/library/ff730940.aspx
Bulk user creation link:http://darshanaj.wordpress.com/2011/11/23/create-bulk-users-from-csvde-exe/
Script to add workstations to domain: http://gallery.technet.microsoft.com/scriptcenter/45396ab8-d17c-41c6-9164-84c26b78c7d8
Link which will help you work with batch files:http://www.computerhope.com/batch.htm
Other link for useful scripts: http://www.akaplan.com/blog/about/

Useful scripts.

1. Script to change product key:-

‘ WMI Script – ChangeVLKey.vbs
‘ This script changes the product key on the computer.
‘***************************************************************************
ON ERROR RESUME NEXT
if Wscript.arguments.count<1 then
   Wscript.echo “Script can’t run without VolumeProductKey argument”
   Wscript.echo “Correct usage: Cscript ChangeVLKey.vbs ABCDE-FGHIJ-KLMNO-PRSTU-WYQZX”
   Wscript.quit
end if
Dim VOL_PROD_KEY
VOL_PROD_KEY = Wscript.arguments.Item(0)
VOL_PROD_KEY = Replace(VOL_PROD_KEY,”-“,””) ‘remove hyphens if any
for each Obj in GetObject(“winmgmts:{impersonationLevel=impersonate}”).InstancesOf (“win32_WindowsProductActivation”)
   result = Obj.SetProductKey (VOL_PROD_KEY)
   if err 0 then
      WScript.Echo Err.Description, “0x” & Hex(Err.Number)
      Err.Clear
   end if
Next
***************************************************************************


2. Script to retrieve last logon / logoff info of particular system:-

Syntax:
‘ LoggedOnFromProfiles.vbs  — GUI
Cscript ‘ LoggedOnFromProfiles.vbs Computername [searchstring] —Command Prompt
‘ search string is optional ‘*’.  All profiles not containing SVC or Service will
‘ be found.  Search string is not a wildcard, must be exact match.
******************************************************************************
Option Explicit
Dim fso, strcomputer
Set fso = CreateObject(“Scripting.FileSystemObject”)
dim wshShell, objWMIService
Set wshShell = WScript.CreateObject(“WScript.Shell”)
Dim batch, profdir, strUser, dLogon, DLogoff, message
Dim strSearch

‘you can set the search value by editing here, from command line 
‘or from gui
strSearch = “*”

If WScript.Arguments.Count >=1 Then 
batch = True 
strComputer = WScript.Arguments(0)
If WScript.Arguments.Count = 2 Then 
strSearch = WScript.Arguments(1)
End If 
Else
strComputer = wshShell.ExpandEnvironmentStrings(“%COMPUTERNAME%”)
strComputer = Inputbox(“Enter Computer name”,”Workstation Logon Check”,strComputer)
If strComputer = “” Then WScript.Quit

message = “Optional User Name to search for such as ” & _
Ucase(wshShell.ExpandEnvironmentStrings(“%USERNAME%”)) & _
“. An asterisk (*) is not a wildcard, ” & _
“rather it means search for all users.”
strSearch = InputBox (message,”Limit Search”,strSearch)
If strSearch = “” Then WScript.Quit
End If 

message = “”

If batch = True Then 
‘Make sure running Cscript.
If (Not IsCScript()) Then ‘If not CScript, re-run with cscript…
WshShell.Run “CScript.exe ” & quote & WScript.ScriptFullName & quote & Space(1) & WScript.Arguments(0), 1, true
   WScript.Quit             ‘…and stop running as WScript
End If
End If 


Const ForAppend = 8
If strcomputer = “” Then WScript.Quit
strcomputer = UCase(strComputer)

If PingReply(strComputer) Then 
GetFolderList(strcomputer)
Else
echoandlog strComputer & “,,,,did not reply to ping”
WScript.Quit
End If 

If not batch Then 
If Len(dLogon) = 0 Then message = “No profile found matching ” & strSearch
MsgBox “User         Logon Logoff” & vbcrlf & message, _
vbokonly + vbInformation,”Logon Summary for ” & strcomputer
  Else
If Len(dLogon) = 0 Then echoandlog strComputer & “,,,,No profile found matching ” & strSearch
End If 
********************************************************************************

Directory Services Concepts

AD Monitoring: http://technet.microsoft.com/en-us/library/bb727046.aspx
What happens if GC and infrastructure master are on same DC in active directory?
Ans: If you only have one domain in your forest, nothing will be wrong.
If you have multiple domains in you forest, and you put your GC and infrastructure master on the same machine, things can go horribly wrong. This is because GC and Infrastructure Master use the same NTDS.dit file, changes will be changed by GC and Infrastructure Master checks the NTDS.dit and doesn’t see any change, because GC already changed the NTDS.dit.
GC has two important functions: one is provides group membership information during logon and authentication and the other is helps users locate resources in Active Directory
Infra Master:DC responsible for updating an object’s SID and distinguished name in a cross-domain object reference.The Infrastructure Master (IM) role should be held by a DC that is not a Global Catalog server (GC). If the Infrastructure Master runs on a Global Catalog server it will stop updating object information because it does not contain any references to objects that it does not hold. This is because a Global Catalog server holds a partial replica of every object in the forest. As a result, cross-domain object references in that domain will not be updated and a warning to that effect will be logged on that DC’s event log. If all the domain controllers in a domain also host the global catalog, all the domain controllers have the current data, and it is not important which domain controller holds the infrastructure master role.
Commands To find
Infra master: dsquery server -domain domain name -hasfsmo infr
Also netdom query fsmo command will give server roles of DC
Global Catalog: dsquery server -domain domain name –isgc
Note: At any time, there can be only one DC acting as the infrastructure master in each domain.
How do I force replication between two domain controllers in a site?

  1. Start the Microsoft Management Console (MMC) Active Directory Sites and Services snap-in.
  2. Expand the Sites branch to show the sites.
  3. Expand the site that contains the DCs. (The default site Default-First-Site-Name might be the only site.)
  4. Expand the servers.
  5. Select the server you want to replicate to, and expand the server.
  6. Double-click NTDS Settings for the server.
  7. Right-click the server you want to replicate from.
  8. Select Replicate Now from the context menu, as the Screen shows Click here to view image
  9. Click OK in the confirmation dialog box
FSMO role overview. : http://blogs.technet.com/b/bpuhl/archive/2005/12/07/415761.aspx
Is the PDC Emulator required for user authentication & How long can a domain operate without a server that is running the PDC Emulator role? http://blogs.technet.com/b/askds/archive/2011/02/25/friday-mail-sack-xxxxxxxxxxxx.aspx#pdceauth
Restoring GPOs:http://technet.microsoft.com/en-us/library/cc783147(WS.10).aspx
http://social.technet.microsoft.com/forums/en-us/winserverGP/thread/A8EFFB73-A115-43CB-923D-3A7301260292
**Best Practice configuring GPO:http://www.grouppolicy.biz/2011/03/best-practice-using-group-policy-to-configure-desktop-wallpaper-background/
Task list using GP:http://www.grouppolicy.biz/tag/scheduled-task/
New Slow Logon, Slow Boot Troubleshooting Content: http://blogs.technet.com/b/askds/archive/2012/05/01/new-slow-logon-slow-boot-troubleshooting-content.aspx
Trust relationships concepts:
You can’t configure the trust with two forest, if below conditions are tue.
1. Similary DNS domain name.
2. Similar Netbios Name of both the domains.
3. Similar SID of both the domain.
Read Collision detection in the below posted article.
http://technet.microsoft.com/en-us/library/cc784334%28WS.10%29.aspx
Make sure necessary ports are opened along with DNS resolution is configured properly between both the domains.
Checklist: Creating a forest trust: http://technet.microsoft.com/en-us/library/cc756852%28WS.10%29.aspx
Domain and Forest Trust Tools and Settings: http://technet.microsoft.com/en-us/library/cc756944%28WS.10%29.aspx
Trust Link with screen shots:http://www.misdivision.com/blog/how-to-create-a-trust-in-windows-server-2008-r2
Shortcut Trust: When to Create:http://technet.microsoft.com/en-us/library/cc737939(v=WS.10).aspx
How to:http://technet.microsoft.com/en-us/library/cc725721.aspx
Windows Time conf:

AD Troubleshooting guide:http://social.technet.microsoft.com/wiki/contents/articles/2285.aspx
What does Dcdiag can do?:http://blogs.technet.com/b/askds/archive/2011/03/22/what-does-dcdiag-actually-do.aspx

Metadata Clean up&Delete failed DCs from AD: http://www.petri.co.il/delete_failed_dcs_from_ad.htm
Tool to check AD user lockout status: http://technet.microsoft.com/en-us/library/cc738772(v=WS.10).aspx
Planning group Membership: http://www.enterprisenetworkingplanet.com/netsecur/article.php/624881/Planning-Your-Group-Structure-Implementation.htm
ADDS Port requirements: http://technet.microsoft.com/en-us/library/dd772723%28v=ws.10%29.aspx
Remove Orphaned DC:http://support.microsoft.com/kb/555846
Force Replication:http://support.microsoft.com/kb/229896/
2K8 lingering objects & Tombstones:http://msmvps.com/blogs/acefekay/archive/2011/12/27/active-directory-lingering-objects-journal-wraps-tombstone-lifetime-and-event-ids-13568-13508-1388-1988-2042-2023.aspx
AD backup/Restore (2k3):http://usefulglyphs.wordpress.com/2009/11/13/how-to-backuprestore-a-windows-2003-domain-controller/
AD lock-out troubleshooting:http://social.technet.microsoft.com/wiki/contents/articles/4585.account-locked-out-troubleshooting.aspx
What’s in an Active Directory DNS Name?  Choosing the Same As Your Public Domain Name, a “.net” Version of Your Public Name, or “.local” http://msmvps.com/blogs/acefekay/archive/2009/09/07/what-s-in-an-active-directory-dns-name-choosing-a-domain-name.aspx
AD Maximum limitations and scalability:http://technet.microsoft.com/en-us/library/active-directory-maximum-limits-scalability(v=ws.10).aspx
//More concepts are going to come to this post.
So give me time to post that…

FAQs

Powelshell CLI & Command Reference

Powershell:Citrix ‘Always add Asnp citrix.* @ starting of command or script’ run in XD environment

>Powershell cli is not a case-sensitive command line utility.

  • Get-configzone |select name, controllernames — to get XD zone name along with DDCs
  • Get-brokercontroller -state active | select DNSname — active DDCs/Broker info
  • Get-BrokerMachine -MachineName domain\VDI name |select sessionusername,Sessionstarttime, machinename,DesktopGroupName — to get details of User who logged in the specific VDI
  • Get-BrokerMachine -Filter { registrationState -eq ‘unregistered‘ -and HypervisorConnectionUid -eq 2 } | Select machinename — unregistered VDIs info.
  • Get-BrokerMachine -Filter { registrationState -eq ‘unregistered‘ -and HypervisorConnectionUid -eq 2 -and Desktopgroupname -eq “del. group name” } | Select machinename, Desktopgroupname — unregistered VDIs from particular Delivery group. 
  • get-brokermachine |Select machinename, desktopgroupname, Sessionsestablished, loadindex |Sort-Object -Property loadindex — to view VDI based on loadindex

Loadindex:- memory + {(CPU+disk+sessioncount)/3}* 0.05

Note:  Sometimes we get this warning if output contains info more than 250 lines. Only first 250 records returned. Use -MaxRecordCount to retrieve more.
Normal commands:-
1.Cluster commands:

    • cluster netint —- Interfaces status
    • cluster res     —- Resources status

 

  • cluster res /prop —- Cluster resources and properties

 

 

  • cluster group —- Listing status for all available resource groups

 

 

  • cluster node —- Listing status for all available nodes
  • PowerShell -Command “&{Import-Module FailoverClusters}” ; “&{get-Clustergroup}” — To get list of cluster group status using PS.

 

 

2. WMIC commands

  • wmic useraccount where (name=’administrator’ and domain=’user domain netBIOS only’) get name,sid —- to know the SID of domain user.
  • wmic useraccount where (name=’administrator’ and domain=’system name’) get name,sid —- to know the SID of Local admin.
  • To Know the user name of SID

$objSID = New-Object System.Security.Principal.SecurityIdentifier `
(“S-1-5-21-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXX-XXXXXX”) # here enter SID details.

$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])

$objUser.Value

  • wmic logicaldisk get size,freespace,caption: To list out all partitions info in a server/system.
  • wmic NIC where NetEnabled=true get Name, Speed —-to know NIC’s speed.
  • wmic qfe list or wmic /node:server qfe get hotfixid,installedon Wmic commands to get hotfix info installed on server
  • wmic os get name –To know the installed OS on server
  • wmic product where “name LIKE ‘%java%'” get * /format:textvaluelist —-Command to determine installed Java version in a Server
  • wmic csproduct get uuid – Command to find UUID of a server/system

3. Other commands

    • ping -a —Ping reply status with hostname
    • qwinsta  — To know RDP sessions status of a server
    • rwinsta or reset session —- To terminate RDP sessions of a server.
    • msra.exe —- To take remote assistance of other user session.
    • logoff  @session ID@ /v — To terminate particular RDP session
    • logoff  sessionID /Servername:<server hostname) /v — To terminate particular RDP session in remote server/machine.

 

  • fsutil volume diskfree c: —— free space C-disk (to know other disk details change drive letter)
  • chkntfs c:    —– Show – Disk status & checks if c-disk is dirty or not

 

 

  • net user  —-list local user accounts. More about net user.
  • net user “local system username” /active:yes —> to enable (no:for disable) local user account.
  • net user localadmin — #3edC$4rfV is best password we can use to reset local admin password from command prompt.
  • Winver or Ver or wmic os get Caption,CSDVersion /value—– To know the version of the OS
  • systeminfo | findstr /C:”OS”:Command to display info about OS.

 

 

  • netstat -a -b   —-Running services with port numbers
  • netstat -aon  &  netstat -anob   —Port details along with PIDs

 

 

  • netstat -b -v -n —-Running processes with IP/port numbers
  • netstat –ano ¦find /i “listening”—Listening port details with PIDs

 

 

  • schtasks  —Scheduled tasks-win2k3
  • Tasklist /v /fi “Imagename eq “processname” –to list out all the details of particular process.
  • at  — Scheduled tasks-win2k
  • net stop “service name” && net start “service name”—– for restarting service 
  • type <log file> —-To view the log file content 
  • mountvol — to know the GUID of disk/partition
  • wevtutil– To retrieve information about event log.(2K8, W7, Vista)
  • eventquery —To retrieve information about event log.(2K3)
  • query termserver/domain:— Command to know terminal server in a domain.
  • subst : :\create a virtual drive (replica of physical drive)
  • Get-WmiObject win32_quickfixengineering or get-hotfix —ps commands to get hotfix info installed on server 
  • Cacls or icacls —To know the permissions of share folder
  • openssl version— Command to find open SSL version to know more run openssl/?
  • forfiles /p “D:\Test folder” /d -30 /m “*.*” /c “cmd /c del @file /s /q”Command to delete last one month files in a folder.
  • DISM /online /Cleanup-Image /SpSuperseded—To clear winsxs folder (*2008 R2 onwards) or installed hot fix for disk cleanup option https://support.microsoft.com/en-gb/kb/2852386

 

4. Commands for AD
***use switch  /?  after the command for more options: AD command are more important and each one having its own significance.
  • ServerManagerCmd.exe -queryCommand to display roles in WS2008
  • command to display the time difference between the local computer and a target computer: w32tm /stripchart /computer: target /samples: n /dataonly
  • command to configure the PDC emulator: w32tm /config /manualpeerlist: peers /syncfromflags:manual /reliable:yes /update where peers specifies the list of DNS names or IP addresses of the NTP time source that the PDC emulator synchronizes
  • ntdsutil —- Best command used in AD for almost all the issues like (configuration/transfer/seize of fsmo roles, maintenance and restoration of AD database etc)
  • repadmin —-Best command used especially for replication checks. for example repadmin/failcache for replication failures add switch “/v” for verbose mode.
  • repadmin/replsingleobj —for single object replication for more details follow the link http://technet.microsoft.com/en-us/library/cc742123(WS.10).aspx
  • replmon — Best tool helps us to monitor replication issues.
  • ntfrsutl forcerepl [computer] /r SetName /p PartnerDnsName –Force FRS to start a replication cycle ignoring the schedule.
  • ldp  —- Command/tool help us to fix replication issues.
  • dcdiag—- Domain controller Diagnostics. for examples dcdiag/test:replications for replication info and dcdiag/test:dns for DNS server issue etc.
  • netdom  Lot can do with it in a domain/forest. for example to know the info about the servers holding fsmo roles netdom query fsmo. Also using this command we can add computers into domain and lot many can do with it.
  • nltest — for example to know the list DCs in domain nltest/dclist:domain name. Help to know the status of trusts and plays major role in configuration of secure channel authentication.
  • nltest/dsgetsite—To know site which your system/server belongs to
  • netsh dhcp show server–Display the List of Authorized Servers in Active Directory for the Current Domain.
  • netsh interface ipv4 show interface—Display IP packet size(MTU) of NICs.
  • dsquery —- gives us to know the details about AD like (users, groups, OUs and fsmo roles etc.)
  • nslookup — used to know/resolve DNS server issues.
  • csvde command will help us to create bulk users in AD.
  • ldifde another one similar to csvde
  • for /f %i in (userlist.txt) do dsquery user -samid %i | dsrm -noprompt —to delete bulk users in single step.
  • set — Especially at client level and great command to give enough details about domain.
  • set -l  or echo %logonserver% commands to know logon server you logged in.
  • “c:\Program Files\Trend Micro\OfficeScan Client\PccNTUpd.exe” -to update office scan and restart real time scan service.
  • dnscmd/EnumZones —Command to get the zone file data
  • dcgpofixused to reset the Default Domain Group Policy Objects
Other Registry references:
  • Program’s shortcuts of startmenu
C:\Users\USERNAME\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\start menu
  • Program’s shortcuts of taskbar
C:\Users\USERNAME\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar
 
MS Command line reference A-Z: http://technet.microsoft.com/en-us/library/cc754340(v=ws.10)***run these commands with admin rights for better results.

Friends still more commands have to come to this post. Since I’ve started today need more time to update all the commands.