Powershell – Add Users to Security Group

Nov 27, 2012 • Jonathan -

Powershell to add users to groups with Get-ADGroup and Add-ADGroupMember cmdlets.

Add single user to security group:

Get-ADGroup -Identity "SomeGroup" | Add-ADGroupMember "some.user"

Add multiple users from a text file to security group, one user per line.

$list = Get-Content -Path "c:\tmp\list.txt"
$group = Get-ADGroup "SomeGroup"
ForEach ($user in $list) { Add-ADGroupMember $group $user }
.



Powershell – Find All Users Who Report To Specific Manager

Nov 26, 2012 • Jonathan -

Quick Powershell One-Liner to find users who report to a specific person.

Get-ADUser -Filter { Manager -eq "CN=Some Manager,OU=Users,DC=contoso,DC=com" } -Properties telephoneNumber | ft Name, telephoneNumber
.



Powershell – Get Service Tags Remotely

Nov 15, 2012 • Jonathan -

Quick Powershell snippet to retrieve service tags from remote machines. Create a text file with one FQDN or IP per line. Adjust the Get-Content line in the snippet below and run.

$list = Get-Content -Path "c:\some\file.txt"

ForEach ($machine in $list) {
	$colItems = Get-WmiObject Win32_BIOS -Namespace “root\CIMV2" -Computername $machine
	ForEach($item in $col) { 
		Write-Host $machine "=" $item.SerialNumber
	}
}
.



Powershell – SCVMM Get List of All Virtual Machines

Oct 29, 2012 • Jonathan -

Quick one-liner to generate a CSV of virtual machines, sorted by their hosts. Report will include Host Name, VM Name, VM Hostname, Status, Action on host stop, and Action on host start.

Get-VM -VMMServer scvmm.contoso.com | Sort-Object Hostname | Select-Object HostName, Name, ComputerName, Status, StopAction, StartAction | Export-Csv .\vm-list.csv -NoTypeInformation
.



Powershell – Use Profiles to Automatically Add Modules and Snappins

Oct 13, 2012 • Jonathan -

Automatically run commands when Powershell launches by using Powershell profiles. Kind of like .bashrc in *nix.

Open Powershell and create a profile:

New-Item -path $profile -type file –force
notepad $profile

Add the commands you want to run on startup. I load the Active Directory, Exchange 2010, Systems Center Virtual Machine Manager, and Quest ActiveRoles cmdlets:

Get-Module -Name ActiveDirectory
Add-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010
Add-PSSnapin -Name Microsoft.Exchange.Management.Powershell.Support
Add-PSSnapin -Name Microsoft.SystemCenter.VirtualMachineManager 
Add-PSSnapin -Name Quest.ActiveRoles.ADManagement

Save it. Now the next time you open Powershell the commands in this profile script will run.

You can get a list of modules / snappins in your Powershell instance running:

Get-PSSnapin -Registered
Get-Module -ListAvailable 
.



Exchange 2010 – Increase Number of MRS Concurrent Mailbox Moves

Oct 10, 2012 • Jonathan -

Increasing the number of simultaneous mailbox moves requires a change of the MSExchangeMailboxReplication.exe.config located in %ProgramFiles%\Microsoft\Exchange Server\V14\Bin. You will need to increase the highlighted sections below as you see fit. Note, this change needs to be made on all CAS servers in the organization and will need to be re-applied following any service pack updates.

<MRSConfiguration 
    MaxRetries = "60"
    MaxCleanupRetries = "5"
    MaxStallRetryPeriod = "00:15:00"
    RetryDelay = "00:00:30"
    MaxMoveHistoryLength = "2" 
    MaxActiveMovesPerSourceMDB = "5"
    MaxActiveMovesPerTargetMDB = "2"
    MaxActiveMovesPerSourceServer = "50"
    MaxActiveMovesPerTargetServer = "5"
    MaxTotalMovesPerMRS = "100"
    FullScanMoveJobsPollingPeriod = "00:10:00"
    MinimumTimeBeforePickingJobsFromSameDatabase = "00:00:04"
    ServerCountsNotOlderThan = "00:10:00"
    MRSAbandonedMoveJobDetectionTime = "01:00:00"
    BackoffIntervalForProxyConnectionLimitReached = "00:30:00"
    DataGuaranteeCheckPeriod = "00:00:10"
    DataGuaranteeTimeout = "00:30:00"
    DataGuaranteeLogRollDelay = "00:01:00"
    EnableDataGuaranteeCheck = "true"
    DisableMrsProxyCompression = "false"
    DisableMrsProxyBuffering = "false"
    MinBatchSize = "100"
    MinBatchSizeKB = "256" />

After making changes, restart the Exchange Mailbox Replication service.

net stop MSExchangeMailboxReplication
net start MSExchangeMailboxReplication
.



Powershell – Backing Up Group Policy

Sep 18, 2012 • Jonathan -

Powershell script to backup ALL Group Policy Objects to a network share complete with email notification.

# import the Group Policy module
if (-not (Get-Module GroupPolicy)){
	Import-Module GroupPolicy -ErrorAction Stop            
}
# remove backups older than 7 days
$max_days = "-7"
  
# get the current date
$curr_date = Get-Date
 
# determine how far back we go based on current date
$del_date = $curr_date.AddDays($max_days)

# set the backup path
$backupRoot = "\\server.contoso.com\backups\group-policy"

# set the email options
$smtpServer = 'mail.contoso.com'
$smtpPort = '25'
$fromAddy = '[email protected]'
$toAddy = '[email protected]'
$mailMsg = "GPO Backup for $curr_date complete. Backups saved in $backupRoot\$((get-date).toString('MM-dd-yyyy'))"
$mailSubject = "GPO Backup $curr_date"
 
# create the folder for todays date
md "$backupRoot\$((get-date).toString('MM-dd-yyyy'))"

# backup the GPOs
Backup-Gpo -All -Path "$backupRoot\$((get-date).toString('MM-dd-yyyy'))"

# delete the files
Get-ChildItem $backupRoot -Recurse | Where-Object { $_.LastWriteTime -lt $del_date } | Remove-Item

# send an email stating it was backed up
Send-MailMessage -SmtpServer $smtpServer -From $fromAddy -To $toAddy -Body $mailMsg -Subject $mailSubject
.



Powershell – Bulk User Password Resets

Sep 13, 2012 • Jonathan -

Simple Powershell script to bulk reset passwords from a text file containing one user per line. This makes use of the Get-ADUser, Set-ADUser, and Set-ADAccountPassword Powershell active directory cmdlets.

# import the AD module
if (-not (Get-Module ActiveDirectory)){
	Import-Module ActiveDirectory -ErrorAction Stop            
}

# set new default password
$password = ConvertTo-SecureString -AsPlainText "Password01" -Force  

# get list of account names (1 per line)
$list = Get-Content -Path c:\scripts\users.txt

# loop through the list
ForEach ($u in $list) {

	if ( -not (Get-ADUser -LDAPFilter "(sAMAccountName=$u)")) { 
		Write-Host "Can't find $u" 
	}
	else { 
		$user = Get-ADUser -Identity $u
		$user | Set-ADAccountPassword -NewPassword $password -Reset
		$user | Set-AdUser -ChangePasswordAtLogon $true
		Write-Host "changed password for $u"
	}
}
.



Scripting – Push OpenFire Spark Client spark.properties file to multiple machines

Sep 12, 2012 • Jonathan -

The batch script below can be used to copy the spark.properties for the OpenFire Spark IM Client file over to new machines on startup/logon. The batch script will copy/create the necessary structure on both Windows 7 and Windows XP machines.

@echo off
cls

:: set the location of the spark.properties file
set sparkLocation=\\server.contoso.com\software$\spark.properties

:: determine OS version
ver | findstr /i "5\.1\." > nul
IF %ERRORLEVEL% EQU 0 GOTO ver_XP
ver | findstr /i "6\.1\." > nul
IF %ERRORLEVEL% EQU 0 GOTO ver_Win7

:ver_Win7
:: windows 7, check to see if properties file exists
IF EXIST %HOMEPATH%\AppData\Roaming\Spark\spark.properties GOTO alreadyThere7
IF NOT EXIST %HOMEPATH%\AppData\Roaming\Spark\spark.properties GOTO notThere7
GOTO end

:alreadyThere7
:: already there, copy over
copy /Y %sparkLocation% %HOMEPATH%\AppData\Roaming\Spark\spark.properties
goto end

:notThere7
:: not there, make directory and copy over
md %HOMEPATH%\AppData\Roaming\Spark
copy /Y %sparkLocation% %HOMEPATH%\AppData\Roaming\Spark\spark.properties
goto end

:ver_XP
:windows xp check to see if file exists
IF EXIST %USERPROFILE%\Local Settings\Application Data\Spark\spark.properties GOTO alreadyThereX
IF NOT EXIST %USERPROFILE%\Local Settings\Application Data\Spark\spark.properties GOTO notThereX
GOTO end

:alreadyThereX
:: already there, copy over
copy /Y %sparkLocation% %USERPROFILE%\Local Settings\Application Data\Spark\spark.properties
goto end

:notThereX
:: not there, make directory and copy over
md %USERPROFILE%\Local Settings\Application Data\Spark\spark.properties
copy /Y %sparkLocation% %USERPROFILE%\Local Settings\Application Data\Spark\spark.properties
goto end

:end
.



Powershell – Delete Computer from AD and SCCM

Sep 8, 2012 • Jonathan -

Powershell script to delete computer account from active directory and remove the computer object from SCCM. Threw this together after having to delete/remove 10+ computers in a single sitting. Much quicker than using the GUI.

<#
.SYNOPSIS
    Deletes computer from SCCM and AD
.DESCRIPTION
    Queries AD & SCCM, deletes the computer account from AD, and removes the computer object from SCCM 
.NOTES
    Author: Jonathan - [email protected] 
.LINK 
    http://elderec.org
.PARAMETER computerName
	Name of computer to delete from AD/SCCM
.PARAMETER sccmServer
	Name of the SCCM server to use
.PARAMETER sccmSite
	Name of the SCCM site to use
.EXAMPLE
	.\delcomp-adsccm.ps1 -computerName CON-01337
	.\delcomp-adsccm.ps1 -computerName CON-01337 -sccmServer sccm.contoso.com
	.\delcomp-adsccm.ps1 -computerName CON-01337 -sccmServer sccm.contoso.comm -sccmSite YOURSITE
#> 

param (
	[parameter(Mandatory=$true, HelpMessage="Enter a computer name")][string]$computerName,
	[parameter(Mandatory=$false, HelpMessage="Enter SCCM server")][string]$sccmServer='sccm-server.contoso.com',
	[parameter(Mandatory=$false, HelpMessage="Enter SCCM server")][string]$sccmSite='YOURSITE'
)

# find and delete the computer from AD
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = $dom.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.filter = "(&(objectclass=computer)(name=$computerName))"
$search.findall() | %{$_.GetDirectoryEntry() } | %{$_.DeleteObject(0)}

# find and delete from SCCM
$comp = get-wmiobject -query "select * from SMS_R_SYSTEM WHERE Name='$computerName'" -computername $sccmServer -namespace "ROOT\SMS\site_$sccmSite"
$comp.psbase.delete()

# spit out results
Write-Host "Deleted $computerName from AD. Removed $computerName from SCCM server $sccmServer, site $sccmSite"
.



subscribe via RSS