Posts Tagged ‘powershell’

Powershell script to query multiple servers for their Local Machine Run Registry Keys

$servers = Get-Content c:\scripts\servers.txt 
 foreach ($server in $servers) {
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $server.ServerName)
$RegKey= $Reg.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run")


GD Star Rating
GD Star Rating

Below is the command to extract ( Archive ) emails from a particular folder into a PST

#Archive Items from a certain folder
New-MailboxExportRequest -mailbox %mailboxname% -IncludeFolders "path/to/folder/ -ContentFilter {(Received -lt '08/01/2014')} -FilePath \\path\to\pstfile.pst

However due to Exchange updates , the MailboxExport command does not work anymore ( which had the -deletecontent command) and Search-Mailbox does not have any functionality to Include just specific folders. So we have to use powershell EWS below

Note – By default ItemView has a limit of 1000 in exchange, the command below you will probably want to increase this say to 10,000 or even 50,000 so you don’t have to rerun this lots of times. After each run it will tell you how many items it has deleleted. You need to run the powershell script with a useraccount that has a throttling policy set above 1000.

e.g. Set-ThrottlingPolicy PolicyName -EWSFindCountLimit 50000

Set-Mailbox useraccount -ThrottlingPolicy PolicyName

$mailbox = Get-Mailbox %mailboxname%
$mailAddress = $mailbox.PrimarySmtpAddress.ToString();
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010)
$ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(10000)
$MailboxRootid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$MailboxRootid)
# Get Folder ID from Path
Function GetFolder()
	# Return a reference to a folder specified by path
	$RootFolder, $FolderPath = $args[0];
	$Folder = $RootFolder;
	if ($FolderPath -ne '\')
		$PathElements = $FolderPath -split '\\';
		For ($i=0; $i -lt $PathElements.Count; $i++)
			if ($PathElements[$i])
				$View = New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
				$View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
				$View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
				$SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements[$i]);
				$FolderResults = $Folder.FindFolders($SearchFilter, $View);
				if ($FolderResults.TotalCount -ne 1)
					# We have either none or more than one folder returned... Either way, we can't continue
					$Folder = $null;
					Write-Host "Failed to find " $PathElements[$i];
					Write-Host "Requested folder path: " $FolderPath;
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
try {
	$FolderObject = GetFolder($MailboxRoot, "path\folder\");
#Date from and To
    $findItemResults = $FolderObject.FindItems("System.Message.DateReceived:01/01/2014..01/08/2014",$ItemView)
        foreach ($item in $findItemResults.Items) {
                try {
#Comment Below out to not delete
                    $Deleted ++
#Uncomment below to list before deleting
					#Write-host $item.DateTimeReceived 
                } catch {
                    Write-warning "Unable to delete item, $($item.subject).  $($Error[0].Exception.Message)"
    if ($Deleted -gt 0) { Write-host "$Deleted mail items deleted from the Inbox." }
} catch {
    Write-warning "Could not connect to Inbox.  $( $_.exception.message )"
GD Star Rating
GD Star Rating

I based this script off of one referenced here :

CSV Format


However I modified Adding a Category to the item, as well as adding this to All Users of a AD Group recursively instead of a single user. This will add a list of Holidays to Users Calendars across an organisation. If run again it will not import duplicates and have fields there to delete the duplicate Calendar enteries if needed

The user running this will need the impersonation role setup see this :

New users can then have an email sent to them automatically ( ) with a .HOL file to run ( P.S. The XML did not work in this , I have to add Lines 6-8 from this
GD Star Rating
GD Star Rating

I was trying to get a list of Active Computers on our Network. A DSQuery can give me a list of all computer , and I tried to get an inactive list for 4 weeks and subtract the value , however the Inactive List was not that acurate.

Instead I wanted to Query the PwdLastSet to

I found a few scripts online but they moved the computer accounts to OU’s , and I just needed this for auditing purposes. So I edited the tracked back script

Save the script as script.ps1 then run with .\script -OlderThan 30

    [int] $OlderThan = 20
try {
    Import-Module ActiveDirectory -ErrorAction Stop -Verbose:$false
} catch {
    Write-Error "Active Directory module failed to Import. Terminating the script. More details : $_"
try {
    #Get domain name
    $DomainDN = (Get-ADDomain -ErrorAction Stop).DistinguishedName
    #Get Computers in Domaing
    $Computers = Get-ADComputer -Filter * -Properties PasswordLastSet -SearchBase $DomainDN -ErrorAction Stop
} catch {
    Write-Error "Failed to query active Directory for computers. Exiting the script. More details : $_"
$now = Get-Date
$agedate = (Get-Date).AddDays(-$OlderThan)
foreach($Computer in $Computers) {
$ComputerName = $computer.Name
$Computerpwdsetdate = $Computer.PasswordLastSet
    if($Computerpwdsetdate -lt $agedate) {
	#Write-Host "Expired $ComputerName"
	$computernumber = $computernumber + 1         
Write-Host "Total = $computernumber"


GD Star Rating
GD Star Rating

Recently I rolled out an updated to Update the styles inside Word for The update only updated the styles and did not change the autotext etc. After the update we wanted to check on a terminal server who had not been updated.

Open powershell and run the follinwg command

Get-ChildItem E:\RoamingProfilePath -Recurse | Where-Object {$_.LastWriteTime -lt “2012-06-23 00:00:00” -and $_.Name -eq ““} | Export-Csc “C:\file.csv”

The excel sheet can be pruned for users via their profile path using the excel function



GD Star Rating
GD Star Rating

ADUsers&Comps**SolarWinds make a free tool GUI for this :

*****More AD Cleaup Tools

You can run these commands in a command prompt on any DC or PC With Active Directory Tools installed

Time Perioud = Weeks so for example let’s work with 6

How to find the CN or OU Path

Open Active Directory Users and Compuer , Click on View and Advanced Features

Find the OU you need to reference and Click on Properties, Attribute Editor Tab and Copy the distinguishedName 


Computer Accounts

Find Old Disabled or Enabled Computer accounts across the whole domain older than 6 weeks

dsquery computer -inactive 6 -limit 0

Powershell Find Only Enabled Computer inactive for 3 Months 

Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan "90" | ?{$_.enabled -eq $True}

Find computer accounts old than 6 weeks and disable

dsquery computer -inactive 6 -limit 0 | dsmod computer -disabled yes

Find Old Computers in a Group CN e.g. if the Icon Looks like this : CN_Group

dsquery computer -inactive 6 -limit 0 CN=Computers,DC=domain,DC=local (Add to stop it going further then the current folder) -scope onelevel

Find Old Computers in a Operation Unit OU e.g. if the Icon Looks like this : OU

dsquery computer -inactive 6 -limit 0 OU=Clients,DC=domain,DC=local (Add to stop it going further then the current folder) -scope onelevel

Query THEN DELETE computer objects which have been inactive for 8 weeks in a specific OU and name starts with PCNAME

dsquery computer "OU=Computers,OU=OUNAME,DC=domain,DC=local" -inactive 8 -name PCNAME* | dsrm -noprompt

User Accounts

Find Old Disable or Enabled User accounts across the whole domain older than 6 weeks

dsquery user domainroot -name * -inactive 6

Powershell Find Only Enabled User inactive for 3 Months 

Search-ADAccount -UsersOnly -AccountInactive -TimeSpan "90" | ?{$_.enabled -eq $True}

Exchange Active User accounts

(Get-MailboxStatistics -Server <exchangeservername> | where {$_.LastLogonTime -gt ((get-date).AddDays(-60))}).count

Find Old User accounts across the whole domain older than 6 weeks and disable 

dsquery user domainroot -name * -inactive 6 | dsmod user -disabled yes


Get-ADUser –filter * -Properties passwordLastSet,whencreated,lastlogondate,Enabled,PasswordNeverExpires | Where { ($_.passwordLastSet –eq $null –or $_.lastlogondate –gt (Get-Date).AddDays(-30)) -and ($_.Name -notlike “*svc*” -and $_.Name -notlike “*Admin*” -and $_.Name -notlike “*test*” -and $_.Name -notlike “*huonit*” -and $_.Name -notlike “*Room*” -notlike “*Mailbox*” -notlike “*Exchange*” -notlike “*Service*” -notlike “*Helpdesk*”) }| Select Name


GD Star Rating
GD Star Rating