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")
 
$server
$RegKeyRO.GetValueNames()
}

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Rebuilding profiles can sometimes be time consuming especially documenting settings. I created a script to backup the current printers the User had and wrote it to a test file ( including Default Printer ) so that this could be run to backup , then restored from this file in the Restore Script

Backup Printer List

Const ForWriting = 2
 
Set objNetwork = CreateObject("Wscript.Network")
 
strComputer = "."
 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
 
Set DefPrinters = objWMIService.ExecQuery _
     ("Select * from Win32_Printer Where Local = FALSE AND Default = True")
 
For Each DefPrinter in DefPrinters
    strText = strText & "Default : " & DefPrinter.Name & vbCrLf
Next
 
Set colPrinters = objWMIService.ExecQuery _
    ("Select * From Win32_Printer Where Local = FALSE AND Default = False")
 
For Each objPrinter in colPrinters
    strText = strText & objPrinter.Name & vbCrLf
Next
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
 
Set objFile = objFSO.CreateTextFile _
    ("h:\Printers.txt", ForWriting, True)
 
 
objFile.Write strText
 
objFile.Close

 

Restore Printer List

 

Const ForReading = 1
Const TristateUseDefault=-2
Set wshnet = CreateObject("Wscript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile ("h:\Printers.txt", ForReading, True, TristateUseDefault)
 
Do Until objFile.AtEndOfStream
	strNextLine = objFile.Readline
	if left(strNextLine,10) = "Default : " THEN
		strNextLine = replace(strNextLine, "Default : ", "")	
		wshnet.AddWindowsPrinterConnection strNextLine
		wshnet.SetDefaultPrinter strNextLine
	END IF
	wshnet.AddWindowsPrinterConnection strNextLine
Loop
 
objFile.Close

 

 

How to reset Printers after backup then restore

 

Const ForWriting = 2
 
Set objNetwork = CreateObject("Wscript.Network")
 
strComputer = "."
 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
 
Set DefPrinters = objWMIService.ExecQuery _
     ("Select * from Win32_Printer Where Local = FALSE AND Default = True")
 
For Each DefPrinter in DefPrinters
    strText = strText & "Default : " & DefPrinter.Name & vbCrLf
Next
 
Set colPrinters = objWMIService.ExecQuery _
    ("Select * From Win32_Printer Where Local = FALSE AND Default = False")
 
For Each objPrinter in colPrinters
    strText = strText & objPrinter.Name & vbCrLf
Next
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
strDirectory = objFSO.BuildPath(WshShell.SpecialFolders("Desktop"), "Printers.txt")
 
Set objFile = objFSO.CreateTextFile _
    (strDirectory, ForWriting, True)
 
 
objFile.Write strText
 
objFile.Close
 
 
Const HKEY_CLASSES_ROOT  = &H80000000
Const HKEY_CURRENT_USER  = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_USERS         = &H80000003
 
' Object used to get StdRegProv Namespace
Set wmiLocator = CreateObject("WbemScripting.SWbemLocator")
 
' Object used to determine local machine name
Set wshNetwork = CreateObject("WScript.Network")
 
' Registry Provider (StdRegProv) lives in root\default namespace.
Set wmiNameSpace = wmiLocator.ConnectServer(wshNetwork.ComputerName, "root\default")
Set objRegistry = wmiNameSpace.Get("StdRegProv")
 
' Deletes Key with alle subkeys
sPath = "Printers"
 
lRC = DeleteRegEntry(HKEY_CURRENT_USER, sPath)
 
Function DeleteRegEntry(sHive, sEnumPath)
' Attempt to delete key.  If it fails, start the subkey
' enumration process.
lRC = objRegistry.DeleteKey(sHive, sEnumPath)
 
' The deletion failed, start deleting subkeys.
If (lRC <> 0) Then
 
' Subkey Enumerator
   On Error Resume Next
 
   lRC = objRegistry.EnumKey(HKEY_CURRENT_USER, sEnumPath, sNames)
 
   For Each sKeyName In sNames
      If Err.Number <> 0 Then Exit For
      lRC = DeleteRegEntry(sHive, sEnumPath & "\" & sKeyName)
   Next
 
   On Error Goto 0
 
' At this point we should have looped through all subkeys, trying
' to delete the registry key again.
   lRC = objRegistry.DeleteKey(sHive, sEnumPath)
 
End If
 
End Function
 
Const ForReading = 1
Const TristateUseDefault=-2
Set wshnet = CreateObject("Wscript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
strDirectory = objFSO.BuildPath(WshShell.SpecialFolders("Desktop"), "Printers.txt")
 
Set objFile = objFSO.OpenTextFile (strDirectory, ForReading, True, TristateUseDefault)
 
Do Until objFile.AtEndOfStream
              strNextLine = objFile.Readline
              if left(strNextLine,10) = "Default : " THEN
                             strNextLine = replace(strNextLine, "Default : ", "")            
                             wshnet.AddWindowsPrinterConnection strNextLine
                             wshnet.SetDefaultPrinter strNextLine
              END IF
              wshnet.AddWindowsPrinterConnection strNextLine
Loop
 
objFile.Close
 
x=msgbox("Printer ReMap Complete" ,0, "Tech Services")

 

VN:F [1.9.22_1171]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

I was trying to get a list of servers from an application via qfarm /app ‘ApplicationName’ however the output it gave me was text rather then an array.

Below is how to get an array into powershell using the Citrix Powershell Snapin Instead

Add-PSSnapin Citrix*
$servers = Get-XAServer -BrowserName 'Application Name'| select ServerName
 
foreach ($server in $servers) {
 
#do Something per server
Write-Host $server.ServerName
 
}

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

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)
$s.AutodiscoverUrl($mailAddress);
 
$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;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
 
 
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
                    [void]$item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)
                    $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 )"
}
VN:F [1.9.22_1171]
Rating: 10.0/10 (2 votes cast)
VN:F [1.9.22_1171]
Rating: +3 (from 3 votes)

I based this script off of one referenced here : http://blogs.msdn.com/b/emeamsgdev/archive/2012/10/29/outlook-code-importing-bank-holidays-from-an-outlook-hol-based-csv-file.aspx?CommentPosted=true#commentmessage

CSV Format

6011-image_thumb_6a014d4e1

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 ( http://blogs.technet.com/b/sukum/archive/2013/04/03/send-welcome-email-to-new-mailbox-users.aspx ) with a .HOL file to run ( P.S. The XML did not work in this , I have to add Lines 6-8 from this http://itnuts.wordpress.com/2013/09/03/exchange-2010-automatic-welcome-message-for-a-new-user/)


https://github.com/pariswells/pariswells.com/blob/master/saveappointmentintoalluserscalendar.ps1
VN:F [1.9.22_1171]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)

Recently a user lost their favorites in iManage. This was due to a Preferred Database change. Below was an SQL Query you can run on the iManage database server to check where the users old favorites are and also check for Duplicates

SELECT PRJ_OWNER, PRJ_ID, PRJ_NAME, SUBTYPE FROM MHGROUP.PROJECTS
 WHERE PRJ_OWNER = 'imanage username' AND SUBTYPE = 'S' 
 OR PRJ_OWNER = 'imanage username' AND SUBTYPE = 'F' 
 ORDER BY PRJ_NAME

This will give you the PRJID for My  Favorites ( F ) and My Matters ( S )

To query the folders for thoose workspaces perform the following  :

SELECT PRJ_OWNER, PRJ_ID, PRJ_NAME, PRJ_DESCRIPT FROM MHGROUP.PROJECTS WHERE TREE_ID = 'PRFID'

 

VN:F [1.9.22_1171]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)

Per this article which is out of date and incorrect : http://support2.microsoft.com/kb/556019

This code works with Windows 7

@echo off
 
SET srvlist=C:\Srvlist.txt
 
Echo Computer Name, Internet Explorer Version >> Result.csv
 
SET IE_Ver=
 
For /F "Tokens=*" %%a In (%srvlist%) Do (
 
echo %%a  >> c:\regquery.txt
reg query "\\%%a\hklm\Software\Microsoft\Internet Explorer" /v Version >> c:\regquery.txt
 
 
)

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Recently we needed to create an Exchange Web Services Script to Auto Reply from a Mailbox due to Auto Replies being disabled for Spam Reasons on the Hubtransports, below will do this and will move the item to a subfolder of Inbox when done

This can be run as a scheduled task as a powershell script

# Connect to Exchange server and load Exchange powershell modules
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
 
$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]::Exchange2007_SP1)
$s.AutodiscoverUrl($mailAddress);
 
$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;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
 
$folderid = new-object  Microsoft.Exchange.WebServices.Data.Folderid([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$mailAddress)
$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$folderid)
 
$mails = $inboxFolder.FindItems(20) 
$mails | % {$_.Load()}
    foreach($Item in $mails.Items)
	{ 
 
#Get the email body
$body = Get-Content “C:\scripts\CareersEmailTemplate.htm”
$body = $body -replace “Placeholder”, $Placeholder
 
#Have to convert the object to a string to use in the mail body.
[string]$msgBody = $body
 
#Create the email message and set the Subject and Body
$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $s
#Put Images inline
$message.Attachments.AddFileAttachment("C:\images\logo.png") | Out-Null
$message.Attachments[0].ContentId = "logo.png";
$message.From = “email@domain.com”
$message.Subject = “MessageSubject”
$message.Body = $msgBody
#Sets reciepients as sender
$message.ToRecipients.Add($item.Sender.Address)
 
#Send the message and save a copy in the users Sent Items folder (Alt is message.Send which will not save a copy.)
$message.SendAndSaveCopy()
 
#Move to Folder After Replying
$FolderObject = GetFolder($MailboxRoot, "\Inbox\Replied\");
		try
		{
		$Item.Move($FolderObject.Id) | out-null;
		}
		catch
		{
		Write-Host "Failed to move item", $Item.Id.UniqueId
		}
 
 
	}

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

During an Office 2003 Migration to 2010 , some custom Interwoven Macro’s got converted into a User’s Normal.dotm file from Normal.dot and Displayed in the Users Add-In. The buttons did nothing when you pressed them.

Per this doco : http://blogs.msdn.com/b/cristib/archive/2012/03/30/vba-how-to-find-and-edit-the-office-2003-legacy-commandbars-and-menus-in-office-2010-add-remove-edit-controls-in-menu-commands-group-from-add-ins-tab.aspx

I tried to list all the controls using the below VB Script however the unlinked buttons where not listed, so I couldn’treference them in VB to remove by using :

Commandbars(1).Controls(“TheControl”).Delete

Sub ListAllControls()
 
Dim cmd As CommandBar
Dim ctr As CommandBarControl
 
Set cmd = Application.CommandBars("Menu Bar").Controls
 
On Error Resume Next
   For Each ctrl In ctr.Controls
     Debug.Print " " & ctrl.Caption & " "
 
     For Each sub_ctrl In cmd.Controls
         Debug.Print "  >> Caption: " & sub_ctrl.Caption & vbTab & vbTab; " OnAction: " & sub_ctrl.OnAction
     Next
   Next

 

I could remove them using the Gui in Word “Delete custom command” , however needed to roll this out across multiple users.

Instead I had to run the following command : ( Either as immediate ) ( Alt F11 then Ctrl G ) or in the macro code for main() which reset the whole toolbar

CommandBars.ActiveMenuBar.Reset

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

bcc-show-all-messages[1]Recently we had a need to query emails sent to an Inbox and find out who the emails had been BCC’ed to. These would then need to be filed into folders based on the BCC address. When an email arrived in the inbox , the server striped the BCC field ( as normal ) so we had to find a way to get this value.

There are a few ways to get the BCC from a message in Exchange

We opted for the third option and below is the scheduled task

# Connect to Exchange server and load Exchange powershell modules
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
 
$mailbox = Get-Mailbox -id 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]::Exchange2007_SP1)
$s.AutodiscoverUrl($mailAddress);
 
#Bind Root of Mailbox
$folderid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$folderid)
 
# Function to Get Folder ID from Folder 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;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
 
#Bind Inbox of Mailbox
$Inboxid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$mailAddress)
$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$Inboxid)
 
# Get x Items in Inbox
$mails = $InboxFolder.FindItems(5) 
 
    foreach($Item in $mails.Items)
	{  
	# Get list of Reciepients from Message ID that has been BCC'ed 
	$mailrecipeients = Get-MessageTrackingLog -MessageID $item.InternetMessageId | where{$_.RecipientStatus -eq "Bcc"} |% {$_.recipients}
 
		if ($mailrecipeients -match "Test@Test.com") 
		{
			$FolderObject = GetFolder($MailboxRoot, "\Moved\Folder");
			try
			{
				$Item.Move($FolderObject.Id) | out-null;
			}
				catch
			{
				Write-Host "Failed to move item", $Item.Id.UniqueId
		}
 
		}
 
 
 
	}

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)