Powershell Snippets for System Admins

Powershell AD User Management

Delete Disabled AD accounts

Get-ADUser -Filter 'Enabled -eq $false' | Select GivenName
Get-ADUser -Filter 'Enabled -eq $false' | Remove-ADUser -whatif
Get-ADUser -Filter 'Enabled -eq $false' | Remove-ADUser -Confirm

Add Active Directory Module

Import-Module activedirectory

Add User

New-ADUser -SamAccountName "$username" -GivenName "$first" -Surname "$last" -Department "$dept" -Name "First Last" -AccountPassword (ConvertTo-SecureString -AsPlainText "$password" -Force) -CannotChangePassword 1 -ChangePasswordAtLogon 0 -PasswordNeverExpires 1 -Enabled 1 -Path "CN=Users,dc=something,dc=something" -passthru -confirm

Remove local user profile

Get-WmiObject win32_userprofile | where {$_.LocalPath -like "*bert"} | Remove-WmiObject -whatif

Set User’s Password

Set-ADAccountPassword -Identity "$username" -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$password" -Force)

Environment Variables

[Environment]::UserName
[Environment]::UserDomainName
[Environment]::MachineName

Delete User

Remove-ADUser -Identity "$username"

Scheduled task to run powershell script

Program/script: powershell -file “pathto.ps1”

Script to restart service if stopped

$serviceName = "Sam Client Control"

If ( (Get-Service $serviceName).Status -ne "Running") {
    Write-Output "$serviceName is stopped. It was started on $(Get-Date)" | Out-File C:\SamSvcRestart_log.txt -Append
    Start-Service $serviceName
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s