Mostrando postagens com marcador powershell. Mostrar todas as postagens
Mostrando postagens com marcador powershell. Mostrar todas as postagens

Powershell Active Directory Commands

Find Users or Computer which are expired

Use Search-AdAccount cmdlet to find user, computer or service account enable status

Search-ADAccount -AccountExpired


Check If Users password expired

Search-ADAccount -PasswordExpired


Check if Users account disabled

Search-ADAccount -AccountDisabled


Find all locked out account in active directory

Search-ADAccount -LockedOut | FT Name,ObjectClass -A


Find account inactive for last 90 days

Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 | FT Name,ObjectClass -A


Unlock User account

Unlock-ADaccount -identity "Garyw"


Get Ad User Distinguished Name

Get-AdUser -Identity "toms" | Select DistinguishedName


Get Ad User using userprincipalname

Use Get-AdUser cmdlet in Active directory to get user using provided userprincipalname.

Get-ADGroupmember -identity salesleader | % { get-aduser $_.samaccountname} | Select Name,UserPrincipalName


Get Ad User SID in active directory

Get-AdUser -Identity toms | Select Name, SID, UserPrincipalName


Modify property of Group in active directory

Lets consider an example to modify description property of group, run below command

Set-ADGroup -Server localhost:60000 -Identity "CN=AccessControl,DC=AppNC" -Description "Access Group" -Passthru

Above PowerShell script, uses Set-AdGroup to set description property using Description parameter.


List all active directory groups

PowerShell Get-AdGroup cmdlet get list of all active directory group, run below command

Get-ADGroup -filter * -properties * |select SAMAccountName, Description|


List of all users in AD group

PowerShell Get-AdGroupMember cmdlet gets active directory group members, run below command

Get-ADGroupMember -Identity "Shell_Sales" | Select-Object Name


Get all computers in Active Directory

PowerShell Get-AdComputer cmdlet get list of active directory computers.

Get-ADComputer -Filter *


Source: https://shellgeek.com


Set AdUser Home Directory in PowerShell

 Using the Set-AdUser cmdlet in PowerShell to set the home directory folder path.

Set-ADUser -Identity Arons -HomeDirectory 'D:\Arons'
 
Get-Aduser -Identity Arons -Properties * | Select SamAccountName,HomeDirectory,HomeDrive,ProfilePath

Rename windows computer command

Command Prompt:

netdom renamecomputer Thecomputernamehere /newname:newnamehere /force /userd:domain\username /passwordd:***** /reboot

 

Powershell:

Example 1: Rename the local computer

This command renames the local computer to Server044 and then restarts it to make the change effective.
PowerShell

Rename-Computer -NewName "Server044" -DomainCredential Domain01\Admin01 -Restart

Example 2: Rename a remote computer

This command renames the Srv01 computer to Server001. The computer is not restarted.

The DomainCredential parameter specifies the credentials of a user who has permission to rename computers in the domain.

The Force parameter suppresses the confirmation prompt.
PowerShell

Rename-Computer -ComputerName "Srv01" -NewName "Server001" -DomainCredential Domain01\Admin01 -Force

 

Create DHCP scope with powershell

Create scope:

 Add-DhcpServerv4Scope -Name "dhcp.contoso.com" -StartRange 10.110.0.10 -EndRange 10.110.0.250 -SubnetMask 255.255.255.0 -LeaseDuration 8.00:00:00

 

Set scope options:
Set-DhcpServerv4OptionValue -ComputerName "dhcp.contoso.com" -ScopeId 10.110.0.10 -DnsServer 10.110.0.2,10.110.0.3 -WinsServer 10.110.0.2 -DnsDomain "contoso.com" -Router 10.110.0.1

 

Get the modified date with powershell

 

To get the modified date on a single file try:

$lastModifiedDate = (Get-Item "C:\foo.tmp").LastWriteTime

To compare with another:

$dateA= $lastModifiedDate 
$dateB= (Get-Item "C:\other.tmp").LastWriteTime

if ($dateA -ge $dateB) {
  Write-Host("C:\foo.tmp was modified at the same time or after C:\other.tmp")
} else {
  Write-Host("C:\foo.tmp was modified before C:\other.tmp")
} 
 
Get-ChildItem -Path D:\PowerShell\ActiveDirectoryGroupList.csv | select Name,CreationTime
 

Get file version information from the command line

 

PS> (Get-Command C:\Path\To\Thing.dll).FileVersionInfo.FileVersion
3.1.0.2

The version number parts of the File­Version­Info are

Product Field File Field Meaning Example
ProductVersion FileVersion String version 3.1.0.2 (alpha)
ProductMajorPart FileMajorPart First number 3
ProductMinorPart FileMinorPart Second number 1
ProductBuildPart FileBuildPart Third number 0
ProductPrivatePartFilePrivatePartFourth number2

Finding Stale User and Computer Accounts

Find Users Who Have Never Logged On

Use the following PowerShell Command;

Get-ADUser -Filter { LastLogonDate -notlike "*" -and Enabled -eq $true } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName | Export-Csv C:\temp\Users-Never-Logged-On.csv

Note: This will output the users to a csv file, and requires you to have a C:\Temp directory.


Find Users Who Have Not Logged On In ‘x‘ Days

I’m going to use the value of 90 days (remember some staff might be on long term sick/maternity so check with HR!) Execute the following three commands;

$DaysInactive = 90
$TrueInactiveDate = (Get-Date).Adddays(-($DaysInactive))
Get-ADUser -Filter { LastLogonDate -lt $TrueInactiveDate -and Enabled -eq $true } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName | Export-Csv C:\temp\Users-Inactive-90-days.csv


Note: This will output the users to a csv file, and requires you to have a C:\Temp directory.


Find Computers Who Have Not Logged On In ‘x‘ Days

Again I’m using 90 days.

$DaysInactive = 90
$TrueInactiveDate = (Get-Date).Adddays(-($DaysInactive))
Get-ADComputer -Filter { PasswordLastSet -lt $TrueInactiveDate} -properties PasswordLastSet | Select-Object Name, PasswordLastSet, DistinguishedName | Export-Csv C:\temp\Computers-Inactive-90-days.csv


Note: This will output the users to a csv file, and requires you to have a C:\Temp directory.

Add All Members of an OU to a Security Group

 

Get-ADUser -SearchBase ‘OU=Source-OU,OU=PNL,DC=pnl,DC=com’ -Filter * | 
ForEach-Object {Add-ADGroupMember -Identity ‘SG-Test-Group’ -Members $_ }

 

 

Getting Object Numbers From Active Directory

Users:
(Get-ADUser -Filter *).Count

Computers:
(Get-ADComputer -Filter *).Count

Groups:
(Get-ADGroup -Filter *).Count

Enabled or disabled users:
(Get-AdUser -filter 'Enabled -eq $true').count
(Get-AdUser -filter 'Enabled -eq $false').count


Group users:
(Get-ADGroup GS-VPN-Users -Properties *).Member.Count

OU users:
(Get-ADUser -Filter * -SearchBase "OU=Users, OU=PNL,DC=pnl,DC=com").Count

 

 

Send e-mail with powershell

 Create a file with ps1 extension, like send_mail.ps1, with this content:


# Make Windows negotiate higher TLS version:
[System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Send-MailMessage -From from@example.com -To to@example.com -Credential (Get-Credential) -Subject "Hello World" -Body "Your text here" -SmtpServer "smtp.office365.com" -Port 587 -UseSsl 

 

 With cred:

# Make Windows negotiate higher TLS version:
[System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
$EmailTo = "myself@gmail.com"
$EmailFrom = "me@mydomain.com"
$Subject = "Test"
$Body = "Test Body"
$SMTPServer = "smtp.gmail.com"

Send-MailMessage -From $EmailFrom -To $EmailTo -Credential $Cred -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port 587 -UseSsl

Powershell remove confirm action

 

If you are using Remove-Item cmdlet use confirm switch like in below example

Remove-Item .\v.txt -Confirm:$false

 

 

 

WMI filter by OS Name

 

For Windows 10 in general:
Select * from Win32_OperatingSystem WHERE Caption LIKE 'Microsoft Windows 10%'

Example for english Windows 7, Server 2008r2 and 10 (but not Windows 8.x or 2008):
Select * from Win32_OperatingSystem WHERE (Caption LIKE 'Microsoft Windows 7%' OR Caption LIKE ‘Microsoft Windows Server 2008 R2%' OR Caption LIKE 'Microsoft Windows 10%’) AND OSLanguage = 1033

Windows DFSR Troubleshooting


A few cmds to help with the DFS troubleshooting aspects, keep in mind all should be run from an elevated PowerShell
Dfsdiag /TestDCs

DFSDiag /TestDFSIntegrity /DFSRoot:\\Contoso.com\MyNamespace /Recurse /Full
Dfsutil /pktinfo
Dfsutil /spcinfo
Dfsr pollad
Klist tgt
Klist tickets
DfsrAdmin Health New /RgName:"Contoso.com\Path1\Folder1" /RefMemName:SERVER /RepName:C:\DFSReports\HealthReport_DATE.html /FsCount:true
dfsrdiag ReplicationState /member:SERVER /all
wmic /namespace:\\root\microsoftdfs path DfsrReplicatedFolderInfo get * /format:textvaluelist
Get-ChildItem C:\Temp -recurse | Out-File E:\DFS-Data\Path1\DfsrPrivate\Staging > C:\Export\allfiles.txt
dfsrdiag backlog /receivingmember:SERVER2 /sendingmember:SERVER1 /rgname:"ReplicationGroup1" /rfname:"Folder Name"

To search for replicated folder name:
1. From Elevated PowerShell: Notepad "C:\Windows\Debug\Dfsr####.log"

2. Find "parent" GUID (will look like {D767AC01-8375-447A-88E4-1CCF6A18DD95}-v167695)
Search for GUID

Run: wbemtest
Namespace: root\microsoftdfs connect

Query: "Select * from dfsreplicatedfolderconfig"


Completely Flush Server
  • dfsutil /pktflush
  • dfsutil /spcflush
  • dfsutil /purgeMupcache
  • klist purge
  • ipconfig /flushdns 

Moving users to OU - powershell


 
# Specify target OU. This is where users will be moved.
$TargetOU =  "OU=Districts,OU=IT,DC=enterprise,DC=com"
# Specify CSV path. Import CSV file and assign it to a variable. 
$Imported_csv = Import-Csv -Path "C:\temp\MoveList.csv" 

$Imported_csv | ForEach-Object {
     # Retrieve DN of user.
     $UserDN  = (Get-ADUser -Identity $_.Name).distinguishedName
     # Move user to target OU.
     Move-ADObject  -Identity $UserDN  -TargetPath $TargetOU
   
 }

Enabling / Disabling single and multiple user accounts


Disabling a single user account can be done by executing below one-liner PowerShell commands:

Disable-ADAccount –Identity “TestAccount”

or

Disable -ADAccount –Identity “CN=TestAccount,OU=Users,DC=example,DC=Com”


Disabling - bulk


$UserAccounts = "C:\Temp\Users.txt"
Foreach ($ThisUser in Get-Content "$UserAccounts")
{
Disable-ADAccount -Identity $ThisUser
}




To enable, just change Disable-ADAccount by Enable-ADAccount


Checking who rebooted a production server


One of the production servers got rebooted unexpectedly and you would like to find out who rebooted it and when the server got rebooted. In PowerShell, you can take a look at the event log using the PowerShell one-liner command shown below. You don’t need to write a bunch of lines in a script and then run the script. Here is how you do it.

Get-EventLog –Log System –Newest 100 | Where-Object {$_.EventID –eq ‘1074’} | FT MachineName, UserName, TimeGenerated -AutoSize

The above command checks the System event log and searches for Event ID 1074 and then prints the machine name, username, and time the event got generated. If you would like to save the output to a CSV file, simply use Export-CSV cmdlet as shown in the command below:

Get-EventLog –Log System –Newest 100 | Where-Object {$_.EventID –eq ‘1074’} | FT MachineName, UserName, TimeGenerated –AutoSize | Export-CSV C:\Temp\AllEvents.CSV -NoTypeInfo






Back up all production Group Policy Objects

If you would like to backup all production Group Policy Objects (GPOs) in an Active Directory environment, use Backup-GPO PowerShell cmdlet as it is highlighted in the command below:

Backup-GPO –All –Path C:\Temp\AllGPO

Get bigfiles in Windows

1. Run:
Get-ChildItem c:\temp -recurse | Sort-Object length -descending | select-object -first 32 | ft name,length -wrap –auto
This command will return the file names and the size of the files in bytes. Useful if you want to know what 32 files are the largest in the Replicated Folder so you can “visit” their owners.

2. Run:
Get-ChildItem c:\temp -recurse | Sort-Object length -descending | select-object -first 32 | measure-object -property length –sum
This command will return the total number of bytes of the 32 largest files in the folder without listing the file names.

3. Run:
$big32 = Get-ChildItem c:\temp -recurse | Sort-Object length -descending | select-object -first 32 | measure-object -property length –sum
$big32.sum /1gb
This command will get the total number of bytes of 32 largest files in the folder and do the math to convert bytes to gigabytes for you. This command is two separate lines. You can paste both them into the PowerShell command shell at once or run them back to back.

List Windows AD active users



Get-ADUser -LDAPFilter "(&(sAMAccountName=*)(!userAccountControl:1.2.840.113556.1.4.803:=2))" ` -Properties sAMAccountName, givenName, sn, mail, enabled | Select sAMAccountName, givenName, sn, mail, enabled | ` Export-Csv -Path c:\Users.csv -NoTypeInformation


Adicionar registro DNS windows linha de comando

 Usando o Prompt de Comando (dnscmd)Abra o Prompt de Comando como Administrador e utilize a seguinte estrutura para adicionar um registro do...

Mais vistos