sysadmin:scripting:powershell
Table of Contents
PowerShell Stuff
Active Directory
# Copy group members to another group $Source_Group = "CN=srcGroup,OU=Groups,DC=domain,DC=local,DC=net" $Destination_Group = "CN=dstGroup,OU=Groups,DC=domain,DC=local,DC=net" # Add -Recursive to end of this line to flatten the group $Target = Get-ADGroupMember -Identity $Source_Group foreach ($Person in $Target) { Add-ADGroupMember -Identity $Destination_Group -Members $Person.distinguishedname } # Gets time stamps for all computers in the domain that have NOT logged in since after specified date # Mod by Tilo 2013-08-27 import-module activedirectory $domain = "domain.mydom.com" $DaysInactive = 90 $time = (Get-Date).Adddays(-($DaysInactive)) # Get all AD computers with lastLogonTimestamp less than our time Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties LastLogonTimeStamp | # Output hostname and lastLogonTimestamp into CSV select-object Name,@{Name="Stamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} | export-csv OLD_Computer.csv -notypeinformation # Disabled a list of users Import-Module activedirectory $list = Import-CSV c:\scripts\disableusers.csv forEach ($item in $list) { $samAccountName = $item.samAccountName Disable-ADAccount -Identity $samAccountName } # Demote a server Import-Module ADDSDeployment Uninstall-ADDSDomainController ` -DemoteOperationMasterRole:$true ` -Force:$true
Get Last Login for all Users
Import-Module ActiveDirectory function Get-ADUsersLastLogon() { $dcs = Get-ADDomainController -Filter {Name -like "*"} $users = Get-ADUser -Filter * $time = 0 $exportFilePath = "c:\lastLogon.csv" $columns = "name,username,datetime" Out-File -filepath $exportFilePath -force -InputObject $columns foreach($user in $users) { foreach($dc in $dcs) { $hostname = $dc.HostName $currentUser = Get-ADUser $user.SamAccountName | Get-ADObject -Server $hostname -Properties lastLogon if($currentUser.LastLogon -gt $time) { $time = $currentUser.LastLogon } } $dt = [DateTime]::FromFileTime($time) $row = $user.Name+","+$user.SamAccountName+","+$dt Out-File -filepath $exportFilePath -append -noclobber -InputObject $row $time = 0 } } Get-ADUsersLastLogon
Random Stuff
# Allow scripts to be ran Set-ExecutionPolicy RemoteSigned
sysadmin/scripting/powershell.txt · Last modified: by pfowler
