Windows Power Shell is a command-line shell and scripting language which is specifically designed for System Administration. Window Power Shell command. known as cmdlets, allow you to manage computer via command line. Below are some commands which I used in regular basis in my journey as a System Administrator. Here I am trying to share some with you:
Most of the time we got error to run command due to security policy so we have to enable Execution Policy
Set-ExecutionPolicy Unrestricted (Command to set Exception list in Security Policy)
When we are talking about User Management, mostly we are dealing with task like creating, modifying or deleting user etc. Below are few command lest to help you out with this.
Create a New Active Directory User
New-ADUser -name Varun -path "OU=Delhi,DC=google,DC=com" -SamAccountName varun -AccountPassword (ConvertTo-SecureString "India@123" -AsPlainText -Force)
Modify Existing Active Directory User
Set-ADUser -Identity Varun -EmailAddress varun@gmail.com
Delete Existing Active Directory User
Remove-ADUser -Identity Varun
Enable an Active Directory User
Enable-ADAccount -Identity Varun
Disable an Active Directory User
Disable-ADAccount -Identity Varun
Reset Active Directory User Password
Set-ADAccountPassword sarita -NewPassword $newpwd –Reset
Adding Group Membership to User Account
Add-ADGroupMember "Remote Desktop Users" Varun
Removing Group Membership to User Account
Remove-ADPrincipalGroupMembership -Identity "CN= Varun,OU=FrontDesk,DC=google,DC=com" -MemberOf "Enterprise Admins"
Now I would like you focus on another important aspect of System Administration is “Monitoring & Searches”. There are so many scenarios where we need to get report or specific information which can be helpful to identify and understand the issue or any specific organization requirement. Here are some frequently used commands and some short of scripts.
Get all Active Directory Users
Get-ADUser -Filter * -Properties * | Select -Property Name,Mail,Department
Get count for all users $ Groups
Get-ADUser -filter * | measure-object | select-object count
Get-ADGroup -filter * | measure-object | select-object count
Get Specific Active Directory User Membership
Get-ADPrincipalGroupMembership Varun | Select Name,DistinguishedName
Get-ADPrincipalGroupMembership Varun | select name
Get All Disabled Active Directory Users
Search-ADAccount -AccountDisabled | select -Property name
Now let’s jump into another important topic which is Exporting Data from Active Directory. There can be many formats which we can export data but here I am using CSV format only which is most used, and can we use further for analysis. Below are few good examples
Export AD Users to CSV
Get-ADUser -Filter * -Properties * | Select -Property Name,Mail,Department | Export-CSV "C:\\AllADUsers.csv" -NoTypeInformation -Encoding UTF8
Export AD Users to CSV with Filter
Get-ADUser -Filter 'City -like "*Austin*"' -Properties * | Select -Property Name,City,Mail,Department,DistinguishedName | Export-CSV "C:\\ADUsers.csv" -NoTypeInformation -Encoding UTF8
Export AD Users from specific OU to CSV
Get-ADUser -Filter * -SearchBase "OU=Austin,DC=TestDomain,DC=Local" -Properties * | Select -Property Name,Mail,Department | Export-CSV "C:\\AustinUsers.csv" -NoTypeInformation -Encoding UTF8
Export AD Computers from specific OU to Txt
Get-ADComputer -SearchBase 'OU=BaseFarm,OU=AE Servere,OU=Agder Energi,DC=a-e,DC=no' -Filter '*' | Select Name, Distinguishedname | ft -autosize
System Administration is not just limited to the activities I have mention above. There are so many tasks which are hard to categorize so I have made this as “Windows Management Command lets”. These are the commands which are frequently used by any system administrator. Let’s walk through:
Finding FSMO Roles
Import-Module ActiveDirectory
Get-ADDomain | Select PDC \Emulator
Finding Schema Versions
Get-ADObject (Get-ADRootDSE).schemaNamingContext -Property objectVersion
Collecting all Domain Controller in a Domain
Import-Module ActiveDirectory
Get-ADDomainController –Filter * | Select Name | Out-File c:\DClist.txt
Enable Remote Desktop
set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0
Allow Incoming RDP on Firewall
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
Enable secure RDP authentication
set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "UserAuthentication" -Value 1
Enable PowerShell Remote Access – Client
Enable-PSRemoting –Force
Set-Item wsman:\localhost\client\trustedhosts *
Restart-Service WinRM
Test-WsMan COMPUTER
Enter-PSSession -ComputerName COMPUTER -Credential USER
Enable PowerShell Remote Access –Server
get-service winrm
Enable-PSRemoting –force
winrm quickconfig
Enable PowerShell Remote Access –Server
import-module grouppolicy
Get-GPOReport -All -Domain a-e.no -Server KRSGC03 -ReportType HTML -Path C:\GPOReportsAll.html
-------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------
# Find Trust
Get-ADTrust –Filter * | ogv
# Find FSMO with specific attribute
Get-ADDomain | Select-object InfrastructureMaster, RIDMaster, PDCEumlator
Get-ADDomain | Select-object DomainNamingMaster, SchemaMaster
Get-ADDomainController –Service PrimaryDC –Discover
Get-ADDomainController –Filter * | Select-Object Name, Domain, Forest, OperationMasterRoles | ft –AutoSize
#Transfer One Role
Move-ADDirectoryServerOperationMasterRole –Identity CVDC1 –OperationMasterRole PDCEmulator
=== CVDC1 is name of the target server ===
#Transfer Multiple Role
Move-ADDirectoryServerOperationMasterRole –Identity CVDC1 –OperationMasterRole RIDMaster,SchemaMaster
=== CVDC1 is name of the target server ===
#Seize Multiple Role
Move-ADDirectoryServerOperationMasterRole –Identity CVDC1 –OperationMasterRole RIDMaster,SchemaMaster -Force
=== CVDC1 is name of the target server ===
#Bulk import of Topology (Site & Services)
Set-Localtion ‘C:\Script’
Get-ChildItem *.csv
# Import CSV containing all sites and pipe to New-ADReplicationSite
Import-CSV .\ADSites.csv | New-ADReplicationSite
# Import CSV containing all sites and pipe to New-ADReplicationSubnet
Import-CSV .\ADSubnets.csv | New-ADReplicationSubnet
# Import CSV and build site link
Import-CSV .\ADSites.csv | ForEach-object { New-ADReplicationSiteLink –Name $_.Name –sitesIncluded $_.SiteA,$_.siteB –Cost $_.Cost –ReplicationFrequencyInMinutes $_.Interval }
# Turn on change notification
# Get all site links where notification is not enable
Get-ADReplicationSiteLink –filter * -Properties Options | Where-Object { $_.Options –eq $null } | ft
# Enable change notification
Get-ADReplicationSiteLink –filter * -Properties Options | Where-Object { $_.Options –eq $null } | Set-ADReplicationSiteLink –Replace @{‘options’=5}
# Find manual COs generated by KCC
Get-ADReplicationConnection –Filter {AutoGenerate –eq $false}
# Find manual COs generated by KCC and set the them to Auto consider
Get-ADReplicationConnection –Filter {AutoGenerate –eq $false} |
# Replication related command lets
# repadmin /queue
Get-ADReplicationQueueOperation –Server Localhost
# /Show UTDvec
Repadmin /showUTDVec localhost “dc=homelab,dc=com”
Get-ADReplicationUpToDatenessVectorTable –Target Localhost –Partition “dc=homelab,dc=com”
#Out-grid view
Get-ADReplicationUpToDatenessVectorTable –Target Localhost | Select-object * | Out-GridView
# Illustrating various ways to call Sync-ADobject
# Create a replication issue. Shutdown a DC
Stop-Computer –ComputerName DC01 –Force
# First Sync to a good DC
Sync-ADObject –Object “CN=guest,CN=Users,DC=Homelab,DC=com” –Source DC02 –Destination DC03
# Use the Sync-ADObject to force a replication error
Sync-ADObject –Object “CN=guest,CN=Users,DC=Homelab,DC=com” –Source DC02 –Destination DC01
Get-ADUser –Identity Guest | Sync-ADObject –Destination DC01
# /Replsum
Repadmin /replsum
# Replication Failures
Get-ADReplicationFailure –Scope Forest | ogv
Get-ADReplicationFailure –Scope Domain | ogv
Get-ADReplicationFailure –Scope Server –Target DC01 | ogv
Get-ADReplicationFailure –Scope Site –Target DC01 | ogv
# Replication health overview
Get-ADReplicationPartnerMetadata –PartnerType Both –Scope Domain
-------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------
# Delete all Disabled Users at once
Search-ADAccount -AccountDisabled -UsersOnly | remove-aduser (Delete all Disabled Users at once)
# Bulk Password Reset
$pass = Import-csv E:\pass\pass.csv
Foreach ($pass1 in $pass) {
$usersam = $pass1.SamName
$userpass = $pass1.newpassword
Set-AdaccountPassword -Identity $usersam -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $userpass -Force)
Write-Host "User $($usersam) password has been reset."
}
# CSV File type
Samname Newpassword
User1 Password
User2 Password
------------------------------------------------------------------------------------------------------
# Export Active Directory group Members
$Date = get-date -format yyyy-MM-dd-hh-mm-ss
#Constant Variables
$OutputFile = "SecurityGroupMembers_($Date).csv" #The CSV Output file that is created, change for your purposes
$arrDLMembers = @{}
$users = Get-Content C:\Users\ageorg\Desktop\test\users.txt
#Prepare Output file with headers
Out-File -FilePath $OutputFile -InputObject "MemberName,GroupDisplayName,GroupSamAccounName" -Encoding UTF8
#Get all Security Groups from AD
$group = $users
$objSecurityGroups = $group | Get-ADuser
#Iterate through all groups, one at a time
Foreach ($objDistributionGroup in $objSecurityGroups)
{
write-host "Processing $($objDistributionGroup.DisplayName)..."
#Get members of this group
$objDGMembers = Get-ADPrincipalGroupMembership -Identity $($objDistributionGroup.SamAccountName)
write-host "Found $($objDGMembers.Count)"
#Iterate through each member
Foreach ($objMember in $objDGMembers)
{
Out-File -FilePath $OutputFile -InputObject "$($objDistributionGroup.Samaccountname),$($objMember.Name),$($objMember.Samaccountname)" -Encoding UTF8 -append
}}
# Move Users to specific OU
Get-Content D:\Scripts\MoveOU.csv | Foreach {Get-ADuser -filter "SamAccontName -eq '$_'" } | Move-ADObject -targetpath "OU=Orkla,DC=Global,DC=corp"
------------------------------------------------------------------------------------------------------
# Append email to description for a list of users
$users= Get-Content C:\Users\pmandal\Desktop\test\USERS.txt
ForEach ($user in $users)
{ prop=Get-ADUser -Filter "samaccountname -eq $user" -properties * foreach { Set-ADUser -Identity $_.samaccountname -Replace @{description="$($_.description) ($_.mail"} }
Set-ADUser -Identity gmjelde -Replace @{description="$($_.description) $($_.mail"}
------------------------------------------------------------------------------------------------------
# Get group membership of listed users
$getmembership = @()
$users = Get-Content C:\Users\pmandal\Desktop\test\users.txt
ForEach ($User in $users) {
$getmembership += Get-ADPrincipalGroupMembership $user |select name, {$user}
}
$getmembership | export-csv C:\Users\admssanjay\Desktop\test\rihqno_membership.csv -encoding unicode -notype
# Set Group membership of users
$grpmembers= Import-CSV "C:\Users\pmandal\Desktop\test\rihqno_membership.csv"
Foreach ($grpmember in $grpmembers) {
$user = $grpmember.user
$grp = $grpmember.name
Add-ADGroupMember -Identity $grp -Member $user}
}
------------------------------------------------------------------------------------------------------
Command Line:
nltest /dbflag:0x2080ffff
# Turn off
nltest /dbflag:0x0
------------------------------------------------------------------------------------------------------
DHCP Migration via Power Shell
# Export
Export-DhcpServer –ComputerName krsgc01.a-e.no -Leases -File C:\export\dhcpexp.xml –verbose
# Import Full
Import-DhcpServer –ComputerName DHCP1.corp.contoso.com -Leases –File C:\export\dhcpexp.xml -BackupPath C:\dhcp\backup\ -Verbose
# Import Scope wise
Import-DhcpServer –ComputerName ae03pads01 -Leases –File C:\export\dhcpexp.xml -BackupPath C:\dhcp\backup\ -Verbose –ScopeId 192.168.154.0
Get-ADUser -Filter * -Properties * | Select -Property Name,SamAccountName,UserPrincipalName,DistinguishedName,HomeDirectory,ScriptPath | Export-CSV "C:\AllADUsers.csv" -NoTypeInformation -Encoding UTF8
# Get all scope lists
Get-DhcpServerv4Scope –ComputerName <DHCPServerName>
Comments
Post a Comment