Windows PowerShell Script for convertig Microsoft Office Documents to OpenDocument Format

February 25, 2014 Leave a comment

Though OpenOffice/LibreOffice officially supports the Microsoft Office Formats, you might want to convert your documents to the native OpenDocument Format when migrating sway from MS-Office. Here are some PowerShell Scripts that automate this task for you. Plase note that you’ll need MS-Office on the converting PC.

Microsoft Word (DOCX) to OpenOffice Writer (ODT)

param
(

)

begin
{

}

process
{

	$strStartFolder = "C:\MyDocument"

    $arrFiles = Get-ChildItem $strStartFolder -recurse -include @("*.docx") -erroraction silentlycontinue | Sort-Object

    $objWinWord = New-Object -ComObject "word.application" -erroraction silentlycontinue
    $objWinWord.Visible = $true

    foreach ($objFile in $arrFiles)
    {

		$strOriginalPath = $objFile.fullname
	
		write-host $strOriginalPath
	
		$objDocument = $objWinWord.documents.open($strOriginalPath)
		
		$strSaveAsPath = $strOriginalPath
		$strSaveAsPath = [ref] $strSaveAsPath.Replace(".docx", ".odt")	

		# see WdSaveFormat enumeration constants: 
		# http://msdn.microsoft.com/en-us/library/office/ff839952.aspx		
		
        $intFileFormat = [ref] 23
		
		if (Test-Path $strSaveAsPath) {
			Remove-Item $strSaveAsPath
		}
		
        $objDocument.SaveAs($strSaveAsPath, $intFileFormat)

        $objDocument.close()
		[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objDocument)
		
		Remove-Item $strOriginalPath
        
    }
	
	$objWinWord.Quit()

	[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objWinWord)
	[GC]::Collect()
	[GC]::WaitForPendingFinalizers()
	
}

end
{

}

Microsoft Word (DOC) to OpenOffice Writer (ODT)

param
(

)

begin
{

}

process
{

	$strStartFolder = "C:\MyDocuments"

    $arrFiles = Get-ChildItem $strStartFolder -recurse -include @("*.doc") -erroraction silentlycontinue | Sort-Object

    $objWinWord = New-Object -ComObject "word.application" -erroraction silentlycontinue
    $objWinWord.Visible = $true

    foreach ($objFile in $arrFiles)
    {

		$strOriginalPath = $objFile.fullname
	
		write-host $strOriginalPath
	
		$objDocument = $objWinWord.documents.open($strOriginalPath)
		
		$strSaveAsPath = $strOriginalPath
		$strSaveAsPath = [ref] $strSaveAsPath.Replace(".doc", ".odt")	

		# see WdSaveFormat enumeration constants: 
		# http://msdn.microsoft.com/en-us/library/office/ff839952.aspx
		
        $intFileFormat = [ref] 23
		
		if (Test-Path $strSaveAsPath) {
			Remove-Item $strSaveAsPath
		}
		
        $objDocument.SaveAs($strSaveAsPath, $intFileFormat)

        $objDocument.close()
		[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objDocument)
		
		Remove-Item $strOriginalPath
        
    }
	
	$objWinWord.Quit()

	[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objWinWord)
	[GC]::Collect()
	[GC]::WaitForPendingFinalizers()
	
}

end
{

}

Microsoft Excel (XLSX) to OpenOffice Calc (ODS)

param
(

)

begin
{

}

process
{

	$strStartFolder = "C:\MyDocument"

    $arrFiles = Get-ChildItem $strStartFolder -recurse -include @("*.xlsx") -erroraction silentlycontinue | Sort-Object

    $objExcel = New-Object -ComObject "excel.application" -erroraction silentlycontinue
    $objExcel.Visible = $true

    foreach ($objFile in $arrFiles)
    {

		$strOriginalPath = $objFile.fullname
	
		write-host $strOriginalPath
	
		$objDocument = $objExcel.workbooks.open($strOriginalPath)
		
		$strSaveAsPath = $strOriginalPath
		$strSaveAsPath = $strSaveAsPath.Replace(".xlsx", ".ods")	

		# see XlFileFormat enumeration constants: 
		# http://msdn.microsoft.com/en-us/library/office/ff198017.aspx
		
        $intFileFormat =  60
		
		if (Test-Path $strSaveAsPath) {
			Remove-Item $strSaveAsPath
		}
		
        $objDocument.SaveAs($strSaveAsPath, $intFileFormat)

        $objDocument.close()
		[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objDocument)
		
		Remove-Item $strOriginalPath
        
    }
	
	$objExcel.Quit()
	
	[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objExcel)
	[GC]::Collect()
	[GC]::WaitForPendingFinalizers()

}

end
{

}

Microsoft Excel (XLS) to OpenOffice Calc (ODS)

param
(

)

begin
{

}

process
{

	$strStartFolder = "C:\MyDocument"

    $arrFiles = Get-ChildItem $strStartFolder -recurse -include @("*.xls") -erroraction silentlycontinue | Sort-Object

    $objExcel = New-Object -ComObject "excel.application" -erroraction silentlycontinue
    $objExcel.Visible = $true

    foreach ($objFile in $arrFiles)
    {

		$strOriginalPath = $objFile.fullname
	
		write-host $strOriginalPath
	
		$objDocument = $objExcel.workbooks.open($strOriginalPath)
		
		$strSaveAsPath = $strOriginalPath
		$strSaveAsPath = $strSaveAsPath.Replace(".xls", ".ods")	

		# see XlFileFormat enumeration constants: 
		# http://msdn.microsoft.com/en-us/library/office/ff198017.aspx
		
        $intFileFormat =  60
		
		if (Test-Path $strSaveAsPath) {
			Remove-Item $strSaveAsPath
		}
		
        $objDocument.SaveAs($strSaveAsPath, $intFileFormat)

        $objDocument.close()
		[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objDocument)
		
		Remove-Item $strOriginalPath
        
    }
	
	$objExcel.Quit()

	[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objExcel)
	[GC]::Collect()
	[GC]::WaitForPendingFinalizers()
	
}

end
{

}

Microsoft PowerPoint (PPTX) to OpenOffice Impress (ODP)

param
(

)

begin
{

}

process
{

	$strStartFolder = "C:\MyDocument"

    $arrFiles = Get-ChildItem $strStartFolder -recurse -include @("*.pptx") -erroraction silentlycontinue | Sort-Object

    $objPowerPoint = New-Object -ComObject "PowerPoint.Application" -erroraction silentlycontinue

    foreach ($objFile in $arrFiles)
    {

		$strOriginalPath = $objFile.fullname
	
		write-host $strOriginalPath
	
		$objDocument = $objPowerPoint.Presentations.open($strOriginalPath)
		
		$strSaveAsPath = $strOriginalPath
		$strSaveAsPath = $strSaveAsPath.Replace(".pptx", ".odp")	

		# see PpSaveAsFileType enumeration constants: 
		# http://msdn.microsoft.com/en-us/library/office/ff746500.aspx		
		
        $intFileFormat = 35
		
		if (Test-Path $strSaveAsPath) {
			Remove-Item $strSaveAsPath
		}
		
        $objDocument.SaveAs($strSaveAsPath, $intFileFormat)

        $objDocument.close()
		[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objDocument)
		
		Remove-Item $strOriginalPath
        
    }
	
	$objPowerPoint.Quit()
	
	[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objPowerPoint)
	[GC]::Collect()
	[GC]::WaitForPendingFinalizers()
	
}

end
{

}

Microsoft PowerPoint (PPT) to OpenOffice Impress (ODP)

param
(

)

begin
{

}

process
{

	$strStartFolder = "C:\MyDocument"

    $arrFiles = Get-ChildItem $strStartFolder -recurse -include @("*.ppt") -erroraction silentlycontinue | Sort-Object

    $objPowerPoint = New-Object -ComObject "PowerPoint.Application" -erroraction silentlycontinue

    foreach ($objFile in $arrFiles)
    {

		$strOriginalPath = $objFile.fullname
	
		write-host $strOriginalPath
	
		$objDocument = $objPowerPoint.Presentations.open($strOriginalPath)
		
		$strSaveAsPath = $strOriginalPath
		$strSaveAsPath = $strSaveAsPath.Replace(".ppt", ".odp")	

		# see PpSaveAsFileType enumeration constants: 
		# http://msdn.microsoft.com/en-us/library/office/ff746500.aspx		
		
        $intFileFormat = 35
		
		if (Test-Path $strSaveAsPath) {
			Remove-Item $strSaveAsPath
		}
		
        $objDocument.SaveAs($strSaveAsPath, $intFileFormat)

        $objDocument.close()
		[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objDocument)
		
		Remove-Item $strOriginalPath
        
    }
	
	$objPowerPoint.Quit()
	
	[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($objPowerPoint)
	[GC]::Collect()
	[GC]::WaitForPendingFinalizers()
	
}

end
{

}

Disabling Touch Input and Speeding up the Thinkpad Tablet 2 for Usage with the Digitizer

December 16, 2013 Leave a comment

Hello everyone,

I own a Lenovo Thinkpad Tablet 2 and use it intensively with . The TPT2 is a fine invention, but there are several points that alwas annoyed me:

  • The TPT2 is based on an Intel Atom processor. That gibes it a good battery lifetime – however, it’s also very slow, especially when the Windows Update Client, the Windows Search Indexer and The Anti-Virus Agent are running in the background.
  • The combination of Touch Input and Digitizer makes it hard not to smudge on your PDF files.

I came up with a solution for me to eliminate these issues by…

  • Creating a local Group Policy that prevents the search indexer from running when on battery (I only use the device on battery).
  • Writing a script that…
    • Disables the Touch Input device in device Manager
    • Sets a local GPO which disables Windows Defender
    • Sets a local GPO which disables Windows Update
  • Writing a second script that reverts the changes of the first script.Here’s the source…
    annotation_mode.cmd

    @echo off
    
    echo Disabling Touch Input...
    echo -----------------------------------------------------------------------
    devcon disable "HID\VEN_ATML&DEV_1000&Col01"
    
    echo.
    
    echo Disabling Windows Defender...
    echo -----------------------------------------------------------------------
    reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v DisableAntiSpyware /t REG_DWORD /d 00000001 /f
    
    echo.
    
    echo Disabling Windows Update...
    echo -----------------------------------------------------------------------
    reg add "HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" /v NoAutoUpdate /t REG_DWORD /d 00000001 /f
    

    ordinay_mode.cmd

    @echo off
    
    echo Enabling Touch Input...
    echo -----------------------------------------------------------------------
    devcon enable "HID\VEN_ATML&DEV_1000&Col01"
    
    echo.
    
    echo Enabling Windows Defender...
    echo -----------------------------------------------------------------------
    reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v DisableAntiSpyware /t REG_DWORD /d 00000000 /f
    
    echo.
    
    echo Enabling Windows Update...
    echo -----------------------------------------------------------------------
    reg add "HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" /v NoAutoUpdate /t REG_DWORD /d 00000000 /f
    

    Just run them when you start/stop annotating pdf files or similar. Note that the device can only be controlled via the digitizer pen when in Annotation Mode. You may combine it with so that you can work without Admin Rights/wont’t get any UAC prompts.

    Please note that you need to have devcon.exe installed on your system.

Categories: Scripting

Batch Script to create a scheduled job that updates VPN routes on connection or disconnection

December 10, 2013 Leave a comment

Imagine you are using the built-in Windows VPN client – for example with StrongSwan. Imagine further that you have multiple remote subnets. You don’t want to set the default gateway onto the VPN connection – but you want to reach those extra networks behind your vpn gateway.

You would have to set up a route to your remote subnet via your VPN gateway’s internal IP adress every time you connect to the gateway, which is very nasty.

Below, you’ll find a script that creates two scheduled taska that catch the corresponding events in Windows Event Viewer and trigger the appropriate route command. Just fill in the variables and the run it once with Administrator permissions.

:: http://technet.microsoft.com/de-de/library/ee431704(v=ws.10).aspx
@echo off

set sNETWORK=192.168.2.0
set sNETMASK=255.255.255.0
set sGATEWAY=192.168.0.1
set sRASNAME=MyVPNTunnel

schtasks /create /RU SYSTEM /F /TN "Update VPN Route for %sRASNAME% on connect" /TR "route add %sNETWORK% mask %sNETMASK% %sGATEWAY%" /SC ONEVENT /EC Application /MO " *[System[(Level=4 or Level=0) and (EventID=20225)]] and *[EventData[Data='%sRASNAME%']] "
schtasks /create /RU SYSTEM /F /TN "Update VPN Route for %sRASNAME% on disconnect" /TR "route delete %sNETWORK% mask %sNETMASK% %sGATEWAY%" /SC ONEVENT /EC Application /MO " *[System[(Level=4 or Level=0) and (EventID=20226)]] and *[EventData[Data='%sRASNAME%']] "
Categories: Scripting

Windows PowerShell Script to remotely start or stop multiple Windows Services

Hello everyone,

here’s a simple script that reads Host Names from a CSV File, then it calls sc.exe to start or stop a bunch of services.

#
# uwe.stoppel/at/cgi.com
#

$InFile = "Mappe1.csv"
$OutFile = "Log.txt"
$Services = "AudioSrv", "WMPNetworkSvc", "WSearch"
$Action = "stop" # may be start or stop or query

Import-CSV $InFile | Foreach-Object {

    $HostName = $_.HostName
    $Services | Foreach-Object {

        $Service = $_

        sc.exe "\\$($HostName)" $Action "$Service" | Out-Null
    
        $Message = "$($HostName): Result of Action $Action for Service $Service is $? with Return Code $LASTEXITCODE ($($([ComponentModel.Win32Exception] $LASTEXITCODE).Message))"

        Write-Output $Message
        Write-Output $Message | Out-File $OutFile -Append
    }

}

I know that it could have been dione without sc.exe, but time was rare ;o).

Kind regards

Scripts to rename your Outlook Contacts E-Mail Adresses with a new Suffix

March 23, 2013 Leave a comment

Hello everyone,

my employer Logica has merged with CGI, so we had the requirement to change all our contact’s E-Mail Adresses from @logica.com to @cgi.com.

Here you find a VBscript and a Powershell Script to do that. Simply replace the variables at the beginning with your suffixes.

VBscript (simply double-click the file):


' Logica2CGI.vbs
' uwe.stoppel/at/cgi.com, 2013
' https://heyfryckles.wordpress.com

Option Explicit

Const oldSuffix = "@logica.com"
Const newSuffix = "@cgi.com"

Function FindContactsToFix(byVal DoIt)

	Const olFolderContacts = 10

	Dim objOutlook, objFolder, objContact, Counter
	
	Set objOutlook = CreateObject("Outlook.Application")
	Set objFolder = objOutlook.Session.GetDefaultFolder(olFolderContacts)

	Counter = 0
	
	For Each objContact In objFolder.Items

		Dim ItemFound, oldAddr1, oldAddr2, oldAddr3, newAddr1, newAddr2, newAddr3
	
		ItemFound = False

		oldAddr1 = LCase(objContact.Email1Address)
		oldAddr2 = LCase(objContact.Email2Address)
		oldAddr3 = LCase(objContact.Email3Address)

		newAddr1 = oldAddr1
		newAddr2 = oldAddr2
		newAddr3 = oldAddr3
		
		If InStrRev(oldAddr1, oldSuffix) > 0 Then
		
			ItemFound = True
			newAddr1 = Replace(oldAddr1, oldSuffix, newSuffix)
			
		End If
		
		If InStrRev(oldAddr2, oldSuffix) > 0 Then
		
			ItemFound = True
			newAddr2 = Replace(oldAddr2, oldSuffix, newSuffix)
			
		End If
		
		If InStrRev(oldAddr3, oldSuffix) > 0 Then
		
			ItemFound = True
			newAddr3 = Replace(oldAddr3, oldSuffix, newSuffix)
			
		End If

		If ItemFound Then
		
			Counter = Counter + 1
		
			If DoIt Then
		
				With objContact
					
					.Email1Address = newAddr1
					.Email2Address = newAddr2
					.Email3Address = newAddr3
					.Save

				End With
				
			End If

		End If
		
	Next
	
	FindContactsToFix = Counter
	
End Function

Dim intContactsFound, intContactsFixed, intAnswer

intContactsFound = FindContactsToFix(False)
If intContactsFound > 0 Then

	intAnswer = Msgbox("Es wurden " & intContactsFound & " Kontakte gefunden, deren E-Mail Adressen von " & oldSuffix & " nach " & newSuffix & " geändert werden können. Möchte Sie die Kontakte jetzt entsprechend ändern?", vbYesNo, "Kontakte korrigieren")

	If intAnswer = vbYes Then
		intContactsFixed = FindContactsToFix(True)
		Msgbox "Es wurden " & intContactsFixed & " Kontakte korrigiert!"
	End If

Else

	MsgBox "Es wurden keine Kontakte gefunden gefunden, welche von " & oldSuffix & " nach " & newSuffix & " geändert werden können."

End If

Powershell (you must run the 32-bit Powershell if you have a 64-Bit Windows with a 32-Bit Outlook installed).


# fix-logicacgi.ps1
# uwe.stoppel/at/cgi.com, 2013
# https://heyfryckles.wordpress.com

param(

	[Parameter(Mandatory=$false, ValueFromPipeline=$false)] [switch]$DoIt = $False

)

begin {

}
 
process {

	$oldSuffix = "logica.com"
	$newSuffix = "cgi.com"

	$((New-Object -comobject "Outlook.Application").getnamespace("mapi").getDefaultFolder(10).items) | where { 
		(
			$_.Email1Address -match "@$oldSuffix" -or 
			$_.Email2Address -match "@$oldSuffix" -or 
			$_.Email3Address -match "@$oldSuffix"
		) 
	} | Foreach-Object {

		write-host $_.Subject
	
		$oldAddr1 = $_.Email1Address.toLower()
		$oldAddr2 = $_.Email2Address.toLower()
		$oldAddr3 = $_.Email3Address.toLower()
	
		if ($_.Email1Address -match "@$oldSuffix") {
			$newAddr1 = $_.Email1Address.toLower().replace("$oldSuffix", "$newSuffix")
			write-host "  1: $oldAddr1 -> $newAddr1" -ForegroundColor Yellow
		} else {	
			$newAddr1 = $oldAddr1
		}
		
		if ($_.Email2Address -match "@$oldSuffix" ) {
			$newAddr2 = $_.Email2Address.toLower().replace("$oldSuffix", "$newSuffix")
			write-host "  2: $oldAddr2 -> $newAddr2" -ForegroundColor Yellow
		} else {	
			$newAddr2 = $oldAddr2
		}
		
		if ($_.Email3Address -match "@$oldSuffix") {
			$newAddr3 = $_.Email3Address.toLower().replace("$oldSuffix", "$newSuffix")
			write-host "  3: $oldAddr3 -> $newAddr3" -ForegroundColor Yellow
		} else {
			$newAddr3 = $oldAddr3
		}
		
		if ($DoIt) {
			$_.Email1Address = $newAddr1
			$_.Email2Address = $newAddr2
			$_.Email3Address = $newAddr3
			$_.save()
			
			write-host "  Fixed!" -ForegroundColor Green
			write-host ""
		}
	}
}

end {

}

Categories: Scripting, Uncategorized

Windows PowerShell Script to repair broken ACLs in Windows Folder Redirection

February 22, 2013 7 comments

If you’re using Windows Folder Redirection (aka Redirected Folders), you may stumble across the problem that – for whatever reason – the Access Control Lists (ACLs) might have been broken, thus the User may get an Error and might be unable to log on to his computer.

Of course, you can fix ACL errors by Hand, however, this might work if you have 5-10 faulty users. But what if you have several thousands of them?

Here’s the solution!

The below Script can be fired up against you File Server. It will…

  • create a list of all Folders…
  • comparing them to their User name in AD…
  • check if this Account is the owner of the directory…
  • and then check if he has “Full Control” permissions for the folder and all sub-folders

If you run the Script with the -FixErrors Argument, it will fix the errors found.

For detailed help, you may run Get-Help ./Fix-BrokenFolderRedirectionACLs.ps1.

Fix-BrokenFolderRedirectionACLs.ps1

<#

.SYNOPSIS 
This is a Powershell Script that enables you to check and correct permission errors in redirected User Folders.

.DESCRIPTION 
Redirected Folders (or Folder Redirection) is a feature of the Windows Operating System. It is widely used, 
especially when Users are using multiple computers which may be the Case in Terminal Server or 
VDI (Virtual Desktop Infrastructure) Deployments. From time to time, it may happen that the Access Control 
Lists (ACLs) in get messed up. This may be caused by a wrong policy or other circumstances and is really 
painful to resolve if you have a big environment with many users.

With this Script, you can determine which of the users Folders are having trouble with their Permissions.

Please note that you must run the Script...
- on a Windows 7 or 2008 R2 machine
- against an UNC Path
- with write Permissions on your Share and Folders

After that, you can enable the -FixErrors Argument and run the script again. It will then fix the errors in the ACLs.

.EXAMPLE
.\Filter-DamagedUserFolderACL.ps1 -FolderName \\fs01\UserFolders

FullName                      Mode                          Result                        FoundErrors
--------                      ----                          ------                        -----------
\\fs01\UserFolders\User1      Read-Only                     Failed                        No-ReadPermissions
\\fs01\UserFolders\User2      Read-Only                     Success                       Wrong-Permissions
\\fs01\UserFolders\User3      Read-Only                     Success                       Wrong-Owner
\\fs01\UserFolders\User4      Read-Only                     Success                       {Wrong-Owner, Wrong-Pe...

Description
-----------
This command retrieves all of the items \\fs01\UserFolders that have an error within their ACLs. This can either 
be that the wrong User is the Owner of the Folder, or that the User doesn't have Full Control Permissions. Please 
note that, at the current state of development, the Script cannot read or fix Folders to which the User running 
the script doesn't have Access tho the Folder.

You probably will see that the Script found several Errors:
- No-ReadPermissions: The Script is unable to read the ACL of this folder. This usually happens when the User 
                      running the Script doesn't have any Permissions on the Folder.
- Wrong-Permissions:  The User for this Folder doesn't have Full Control Permissions on his Folder.
- Wrong-Owner:        The User for this Folder is not it's Owner.

.EXAMPLE
.\Filter-DamagedUserFolderACL.ps1 -FolderName \\fs01\UserFolders -LogToScreen

Invoked on DC01 as CORP\Administrator.
Running in Read-Only Mode.
\\fs01\UserFolders\User1 Error: Cannot check this ACL, probably because we don't have permissions!
\\fs01\UserFolders\User2 ACL Entry Mismatch!
\\fs01\UserFolders\User3 Owner Mismatch!
\\fs01\UserFolders\User4 Owner Mismatch!
\\fs01\UserFolders\User4 ACL Entry Mismatch!
\\fs01\UserFolders\User5 ACL is OK!
\\fs01\UserFolders\User6 ACL is OK!
\\fs01\UserFolders\User7 Error: Couldn't find User User6 in Active Directory!

Description
-----------
Adding the -LogToScreen Parameter gives you verbose Output of what is happening. However, you don't get PS Objects 
as Output. You may use -LogToFile instead.

.EXAMPLE
.\Filter-DamagedUserFolderACL.ps1 -FolderName \\fs01\UserFolders -LogToFile

Description
-----------
Adding the -LogToFile Parameter writes the verbose Output of what is happening to a file. By Default, we will 
create a Folder "Logs" inside the Folder you run the Script in. You max specify a Directory for Log Files with 
the -LogFilePath Argument.

.EXAMPLE
.\Filter-DamagedUserFolderACL.ps1 -FolderName \\fs01\UserFolders -FixErrors

FullName                      Mode                          Result                        FoundErrors
--------                      ----                          ------                        -----------
\\fs01\UserFolders\User1      Fix-Errors                    Failed                        No-ReadPermissions
\\fs01\UserFolders\User2      Fix-Errors                    Success                       Wrong-Permissions
\\fs01\UserFolders\User3      Fix-Errors                    Success                       Wrong-Owner
\\fs01\UserFolders\User4      Fix-Errors                    Success                       {Wrong-Owner, Wrong-Pe...

Description
-----------
This command will fix the Owner and ACL Entry of the Folder if necessary.

.EXAMPLE
.\Filter-DamagedUserFolderACL.ps1 -FolderName \\fs01\UserFolders -BackupACLS

Description
-----------
This command will backup all the ACLs for the Folders into Text Files. Note that they will be saved into the 
Directory specified by the -LogFilePath Argument.

.NOTES
Version
-------
You are using Version 0.1 of the Script.

Copyright
---------
The Script was written by: Uwe Stoppel < uwe/at/stoppel.name > <uwe.stoppel/at/cgi.com> < https://heyfryckles.wordpress.com >.
You may use, modify and redistribute it under the Terms of the GNU GPL.
Contact me if you need Support or further development.

Credits
-------
The Script was inspired (among others) by...
- https://sites.google.com/site/powershellandphp/powershell-1/files-and-folders/set-folders-acl-owner-and-ntfs-rights
- http://www.energizedtech.com/2010/03/powershell-how-to-add-help-to.html
- https://blogs.technet.com/b/heyscriptingguy/archive/2011/05/15/simplify-your-powershell-script-with-parameter-validation.aspx
- https://leftlobed.wordpress.com/2008/06/04/getting-the-current-script-directory-in-powershell/
- http://fixingitpro.com/2011/07/08/set-owner-with-powershell-%E2%80%9Cthe-security-identifier-is-not-allowed-to-be-the-owner-of-this-object%E2%80%9D/
- https://social.technet.microsoft.com/Forums/zh/winserverpowershell/thread/7f67b415-3ce3-4694-86d6-1a23a257d703
- http://stackoverflow.com/questions/5798096/netbios-domain-of-computer-in-powershell
- http://msdn.microsoft.com/de-de/library/system.security.accesscontrol.objectsecurity.setaccessruleprotection.aspx
- https://blogs.msdn.com/b/powershell/archive/2006/09/15/errorlevel-equivalent.aspx
- http://msdn.microsoft.com/en-us/library/windows/desktop/dd878348(v=vs.85).aspx
- https://www.vistax64.com/powershell/91098-there-equivalent-powershell-get-name-script.html

.LINK 
https://heyfryckles.wordpress.com

#>

param(

	[Parameter(Mandatory=$true,  ValueFromPipeline=$true) ] [string]$FolderName,
	[Parameter(Mandatory=$false, ValueFromPipeline=$false)] [string]$LogFilePath,
	[Parameter(Mandatory=$false, ValueFromPipeline=$false)] [switch]$FixErrors = $False,
	[Parameter(Mandatory=$false, ValueFromPipeline=$false)] [switch]$LogToScreen = $False,
	[Parameter(Mandatory=$false, ValueFromPipeline=$false)] [switch]$LogToFile = $False,
	[Parameter(Mandatory=$false, ValueFromPipeline=$false)] [switch]$BackupACLs = $False

	# We could need a verbose Switch so that the OK Messages can be hidden
	# We should think about better Parameter validation

)

begin {

}
 
process {

	# Returns the Folder the Script is running in
    function Get-ScriptDirectory
    {
		$Invocation = (Get-Variable MyInvocation -Scope 1).Value
		Split-Path $Invocation.MyCommand.Path
    }

	# Returns the SID of a Windows User
	function Get-Sid
	{
		param (
			$DSIdentity
		)
		$ErrorActionPreference = "SilentlyContinue"
		$ID = new-object System.Security.Principal.NTAccount($DSIdentity)
		return $ID.Translate([System.Security.Principal.SecurityIdentifier] ).toString()
	}
	
	function Write-Message
	{
	
		param (
			[Parameter(Mandatory=$true) ] [string]$MessageType,
			[Parameter(Mandatory=$true) ] [string]$Message,
			[Parameter(Mandatory=$false)] [bool]$LogToFile = $False,
			[Parameter(Mandatory=$false)] [bool]$LogToScreen = $True
		)
		
		if ($LogToScreen) {
		
			Switch ($MessageType) {
			
				"Success" {	$strForeGroundColor = "Green" }
				"Information" {	$strForeGroundColor = "White" }
				"Warning" { $strForeGroundColor = "Yellow" }
				"Error" { $strForeGroundColor = "Red" }

			}
			Write-Host $Message -ForeGroundColor $strForeGroundColor -BackgroundColor "Black"
			
		}
		
		if ($LogToFile) {
			Write-Output "$(Get-Date -format yyyy-MM-dd_HH-mm): $($Message)" | Out-File $LogFile -Append
		}
	
	}

	# If the FolderName Argument has been set...
	# (we don't necessarily need this check as we have parameter validation)
	if ($FolderName) {
	
		# We check if the specified Folder exists...
		if (Test-Path $FolderName) {
			
			# We ultimately need an UNC Path, otherwise we cannot change the Owner of the Folder
			if ([bool]([System.Uri]$FolderName).IsUnc) {
			
				#
				# We could implement another check: Do we have Permission on the Shared Folder defined?
				#
	
				if ($LogToFile -or $BackupACLs) {
	
					# If the LogFilePath Argument wasnt given, we try to create a Folder under the Script's Directory
					if (!($LogFilePath)) {
						$LogFilePath = "$(Get-ScriptDirectory)\LogFiles"
						$LogFile = "$LogFilePath\$(($MyInvocation.MyCommand).Name)_Log.txt"
					}
					
					# We create the Directory for our Log Files
					if (!(Test-Path $LogFilePath)) {
					
						#
						# We could implement a routine to check for errors
						#
						New-Item "$($LogFilePath)" -ItemType Directory | Out-Null
					}
				
				}
		
				# For the LogToScreen and LogToFile Parameters, we will produce some nice Output here...
				Write-Message -MessageType "Information" -Message "Invoked on $([Environment]::MachineName) as $([Environment]::UserDomainName)\$([Environment]::UserName)." -LogToFile $LogToFile -LogToScreen $LogToScreen
		
				# We Log the current Mode of the Script for better understanding what we are doing...
				if ($FixErrors -eq $True) {
				
					Write-Message -MessageType "Warning" -Message "Warning! Running in Fix-Errors Mode. We will definitely apply changes to your System!" -LogToFile $LogToFile -LogToScreen $LogToScreen
					$objPSOutputMode = @{name="Mode"; expression={"Fix-Errors"}}

				} else {
				
					Write-Message -MessageType "Information" -Message "Running in Read-Only Mode." -LogToFile $LogToFile -LogToScreen $LogToScreen
					$objPSOutputMode = @{name="Mode"; expression={"Read-Only"}}
					
				}
		
				Get-ChildItem $FolderName | Foreach-Object {
		
					$strFolderItem = $_.FullName

					# We get the User Name from the Folder Name
					$strUserName = Split-Path -leaf -path ($strFolderItem)
					
					$strDomainName = [Environment]::UserDomainName
					
					# Just a dumb check if there is a corresponding user in AD: We get the User SID from Active Directory. Don't know if this will work with multiple domains.
					if ($(Get-Sid $strUserName)) {
					
						# These are our two Switches:
						# Do we have the correct Owner? (we assume yes as default)
						$blOwnerIsCorrect = $True
						
						# Did we find our desired ACL Entry for the User (we assume no as default until we find what we want inside the ACL)
						$blACLEntryFound = $False
						
						# Switch if we have to Crack the ACL
						$blCanWriteToACL = $True
						
						# The Array for the Errors we find. It will be starting empty.
						$arrOutputErrors = @()
					
						$objPSOutputName = @{name="FullName"; expression={$strFolderItem}}
					
						# We try to read the Folder's ACL.
						# This may fail if we don't have the right permissions, so we temporarily ignore any errors ;o)
						$ErrorActionPreference = "SilentlyContinue"
						$objoldFolderACL = Get-Acl $strFolderItem
						$ErrorActionPreference = "Continue"
						
						if ($objoldFolderACL) {

							# If we made it this far, we can set a pointer that the ACL can be read
							$blCanReadACL = $True
						
							if ($BackupACLs -eq $True) {
							
								Write-Output "$(Get-Date -format yyyy-MM-dd_HH-mm): Backup of ACL for User $($strUserName):" | Out-File "$($LogFilePath)\$($strUserName)_ACL.txt" -Append
								$objoldFolderACL | Format-List | Out-File "$($LogFilePath)\$($strUserName)_ACL.txt" -Append
							
							}
						
							# We compare the actual owner with the desired one
							if ($($objoldFolderACL.Owner.substring(($objoldFolderACL.Owner.length - $strUserName.length),$strUserName.length)) -ne $strUserName) {
								
								Write-Message -MessageType "Warning" -Message "$($strFolderItem) Owner Mismatch!"  -LogToFile $LogToFile -LogToScreen $LogToScreen
								
								# If there is a mismatch, we flip the switch
								$blOwnerIsCorrect = $False
								
								$arrOutputErrors += "Wrong-Owner"

							}
							
							# We loop through all Entries in the ACL
							$objoldFolderACL.Access | Foreach-Object {
										
								# We search for our desired entry
								if (
									($_.FileSystemRights -eq "FullControl") -and
									($_.AccessControlType -eq "Allow") -and
									($_.IsInherited -eq $False) -and
									($_.IdentityReference.Value.substring(($_.IdentityReference.Value.length - $strUserName.length), $strUserName.length) -eq $strUserName) -and
									($_.InheritanceFlags -eq "ContainerInherit, ObjectInherit") -and
									($_.PropagationFlags -eq "None")
								) {
									# If found, we flip the switch
									$blACLEntryFound = $True
								}

							}
							
							# If the ACL Entry was not found, we want to log this
							if ($blACLEntryFound -ne $True) {
								Write-Message -MessageType "Warning" -Message "$($strFolderItem) ACL Entry Mismatch!" -LogToFile $LogToFile -LogToScreen $LogToScreen
								$arrOutputErrors += "Wrong-Permissions"
							}
							
							#
							# Here, we could need a third check that recursively loops through the Folder and searches for problems with inherited permissions
							#
						
							# Here is our routine for the Fixing Stuff
							if ($FixErrors -eq $True) {

								
								# We start with the old ACL as the new One
								$objnewFolderACL = $objoldFolderACL
								
								if ($blOwnerIsCorrect -ne $True) {
									Write-Message -MessageType "Information" -Message "$($strFolderItem) Setting $($strDomainName)\$($strUserName) as Owner..." -LogToFile $LogToFile -LogToScreen $LogToScreen
									
									# We build the Security Principal for the User (we need it to set the owner)
									$objSecurityPrincipal = New-Object System.Security.Principal.NTAccount($strDomainName, $strUserName)
									
									# We set the Owner of the Folder to the Specified User
									# This Will only work with UNC Paths
									$objnewFolderACL.SetOwner($objSecurityPrincipal)
									
								}
								
								if ($blACLEntryFound -ne $True) {
								
									Write-Message -MessageType "Information" -Message "$($strFolderItem) Giving $($strDomainName)\$($strUserName) Full Control Permissions..." -LogToFile $LogToFile -LogToScreen $LogToScreen
									
									# We specify that we want not to protect the folder from the inheritance of permissions
									$objnewFolderACL.SetAccessRuleProtection($False, $False)
									
									# We give the User Full Control Permissions of the Folder
									$objACLRule = New-Object System.Security.AccessControl.FileSystemAccessRule($strUserName,"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
									$objnewFolderACL.AddAccessRule($objACLRule)
									
								}
								
								#
								# Here, we would fix Inheritance problems
								#
								
								if (($blACLEntryFound -ne $True) -or ($blOwnerIsCorrect -ne $True)) {
								
									# We write the new ACL
									Set-Acl $strFolderItem $objnewFolderACL
									
									# We check if the Set-ACL Command was successful...
									if ($?) {
										$objPSOutputResult = @{name="Result"; expression={"Success"}}
										Write-Message -MessageType "Success" -Message "$($strFolderItem) Setting the new ACL Succeeded!" -LogToFile $LogToFile -LogToScreen $LogToScreen
									} else {
										$objPSOutputResult = @{name="Result"; expression={"Failed"}}
										Write-Message -MessageType "Error" -Message "$($strFolderItem) Setting the new ACL Failed!" -LogToFile $LogToFile -LogToScreen $LogToScreen
									}
								
								}
								
							} else {
							
								# As we didn't do anything, the Result will be a Sccess
								$objPSOutputResult = @{name="Result"; expression={"Success"}}
								
							}
						
						} else {
							
							# As we cannot read the ACL, we are neither Owner nor do we have any read permission
							# We would have to "crack" the folder, that means
							# 1. The user running the Script will have to take ownership
							# 2. Then assign himself write permisssion
							# 3. Then we can set our ACL as we like and remove the permission for ourself
							# Perhaps we may implement this in the future

							$blCanReadACL = $False
							$arrOutputErrors += "No-ReadPermissions"
							$objPSOutputResult = @{name = "Result"; expression={"Failed"}}
							Write-Message -MessageType "Error" -Message "$($strFolderItem) Error: Cannot check this ACL, probably because we don't have permissions!" -LogToFile $LogToFile -LogToScreen $LogToScreen
								
						}

						if (($blACLEntryFound -ne $True) -or ($blOwnerIsCorrect -ne $True) -or ($blCanReadACL -ne $True)) {
						
							if ($LogToScreen -eq $False) {
	
								$objPSOutputErrors = @{name="FoundErrors"; expression={$arrOutputErrors}}
								"" | Select-Object $objPSOutputName, $objPSOutputMode, $objPSOutputResult, $objPSOutputErrors

							}
						
						} else {
						
							Write-Message -MessageType "Success" -Message "$($strFolderItem) ACL is OK!" -LogToFile $LogToFile -LogToScreen $LogToScreen
							
						}
						
					} else {
					
						Write-Message -MessageType "Error" -Message "$($strFolderItem) Error: Couldn't find User $($strUserName) in Active Directory!" -LogToFile $LogToFile -LogToScreen $LogToScreen
						
					}
					
				}
				
			} else {
			
				Write-Message -MessageType "Error" -Message "$($FolderName) Error: You must specify an UNC Path!" -LogToFile $False -LogToScreen $True
				
			}
	
		} else {
		
			Write-Message -MessageType "Error" -Message "$($FolderName) Error: The Specified Directory does not Exist!" -LogToFile $False -LogToScreen $True
		
		}
	
	}
	
}

end {

}

Windows Powershell Script for reporting disk failures via SMTP E-Mail

February 6, 2013 Leave a comment

Below you find a script that sends you an E-Mail Report if any of your local disks or Software RAIDs reports any suspicious Events. Very useful if you use the integrated Software-RAID function of Windows Server.

logcheck.ps1

# Written by: 
# Uwe Stoppel < uwe/at/stoppel.name > < https://heyfryckles.wordpress.com > 

# The SMTP address of the sender
$sSmtpFrom = "operations@mydomain.com"

# The SMTP recipient of the sender
$sSmtpTo = "operations@mydomain.com"

# The SMTP server to use for sending the E-Mail
$sSmtpHost = "mailserver.mydomain.local"

# Days to search for in the Event Log.
$iSearchDays = 1

$oOutputFields = @{ 

	Property = @(
		"TimeGenerated",
		"Source", 
		"EntryType", 
		"Message"
	)

}

$oDataSource = @{

	LogName = "System"

	# Add more Sources here
	Source = @(
		"Disk",
		"atapi",
		"iastor",
		"ftdisk",
		"NTFS"
	)
	EntryType = @(
		"Error",
		"Warning"
	)
	After = $(Get-Date).AddDays(-$iSearchDays)

}

$oOutputFormat = @{

	Width = 60

}

function Send-SmtpMail($sSmtpHost, $sSmtpFrom, $sSmtpTo, $sSmtpSubject, $sSmtpMailBody, $bSmtpMailUrgent)
{
	$oSmtpClient = New-Object System.Net.Mail.SmtpClient
	$oSmtpMessage = New-Object System.Net.Mail.MailMessage

	$oSmtpClient.Host = $sSmtpHost
	$oSmtpMessage.from = $sSmtpFrom
	$oSmtpMessage.To.add($sSmtpTo)
	$oSmtpMessage.Subject = $sSmtpSubject
	$oSmtpMessage.IsBodyHtml = $false
	$oSmtpMessage.Body = $sSmtpMailBody

	If ($bSmtpMailUrgent) {

		$oSmtpMessage.Priority = [System.Net.Mail.MailPriority]::High
	}

	$oSmtpClient.Send($oSmtpMessage)
}

$ErrorActionPreference = "SilentlyContinue"
$sOutputData = Get-EventLog @oDataSource | Format-List @oOutputFields | Out-String @oOutputFormat

If ($sOutputData) {
	$sSmtpSubject = "$(Get-Content env:ComputerName): Critical events found!"
	$sSmtpMailBody = "Here are the mentioned critical events of the last $iSearchDays days"
	$sSmtpMailBody += $sOutputData
	$bSmtpMailUrgent = $true
	
} else {
	$sSmtpSubject = "$(Get-Content env:ComputerName): No critical events found."
	$sSmtpMailBody = "No critical events in the last $iSearchDays days found."
	$bSmtpMailUrgent = $false
}

Send-SmtpMail $sSmtpHost $sSmtpFrom $sSmtpTo $sSmtpSubject $sSmtpMailBody $bSmtpMailUrgent

Batch Script for automatically uninstalling all Mozilla Firefox and Mozilla Thunderbird Instances on a PC

February 6, 2013 3 comments

Below, you’ll find a Little helper script that fully automatically uninstalls all Mozilla Firefox and Mozilla Thunderbird from the targeted machine. This might come in handy if you want to clean up a PC from old Firefox/Thunderbird junk Prior to deploying the most current Version.

  • You must run the Script with Admin rights.
  • The Script works with both x86 and x64 machines.
  • You will Need at least Windows XP. You may can modify it to work with Windows 2000 when you use reg.exe from the Resource Kit and kill.exe from Sysinternals.
  • I wasn’t able to test the Scripts with all FF/TB Versions out there. However, I think the list of the Versions should be complete.
  • Some Firefox Versions include localized Strings inside the Uninstall string, so you must customize these strings into your language. This is the reason because almost all of the Uninstall commands are commented out by Default.

uninstall-ff.bat

:: Bulk Uninstaller for Mozilla Firefox
:: Written by:
:: Uwe Stoppel < uwe/at/stoppel.name > < https://heyfryckles.wordpress.com >

@echo off

goto start

:uninstall_helper

	set SWNAME=%1
	
	:: Remove Quotation Marks
	set SWNAME=###%SWNAME%###
	set SWNAME=%SWNAME:"###=%
	set SWNAME=%SWNAME:###"=%
	set SWNAME=%SWNAME:###=%

	:: Searching the 32-Bit Regkeys for our SWNAME
	set REGKEY=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\%SWNAME%
	@call reg.exe QUERY "%REGKEY%" > nul 2>&1
	if %ERRORLEVEL% == 0 (
		@echo "%SWNAME%" found. Uninstalling...
		call :uninstall
	)
	
	:: Searching the 64-Bit Regkeys for our SWNAME
	set REGKEY=HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\%SWNAME%
	@call reg.exe QUERY "%REGKEY%" > nul 2>&1
	if %ERRORLEVEL% == 0 (
		@echo "%SWNAME%" found. Uninstalling...
		call :uninstall
	)
	
	goto finish

:uninstall

	@echo Killing running processes...
	@call taskkill.exe /F /IM firefox.exe > nul 2>&1

	for /F "tokens=2*" %%a in ('reg.exe QUERY "%REGKEY%" /v InstallLocation ^|findstr InstallLocation') DO SET INSTALLLOCATION=%%b
	for /F "tokens=2*" %%a in ('reg.exe QUERY "%REGKEY%" /v DisplayVersion ^|findstr DisplayVersion') DO SET DISPLAYVERSION=%%b

	@echo %SWNAME% | find "x (0." > nul 2>&1
	if %ERRORLEVEL% == 0 (
		@call "%SYSTEMROOT%\UninstallFirefox.exe" /ms /ua "%DISPLAYVERSION%"
		goto finish
	)

	@echo %SWNAME% | find "x (1." > nul 2>&1
	if %ERRORLEVEL% == 0 (
		@call "%SYSTEMROOT%\UninstallThunderbird.exe" /ms /ua "%DISPLAYVERSION%"
		goto finish
	)	

	@call "%INSTALLLOCATION%\Uninstall\helper.exe" /s
	
goto finish

:start

	:: see https://en.wikipedia.org/wiki/Firefox_release_history

	REM @call :uninstall_helper "Mozilla Firefox (0.8)"
	REM @call :uninstall_helper "Mozilla Firefox (0.9)"
	REM @call :uninstall_helper "Mozilla Firefox (0.9.1)"
	REM @call :uninstall_helper "Mozilla Firefox (0.9.2)"
	REM @call :uninstall_helper "Mozilla Firefox (0.9.3)"
	REM @call :uninstall_helper "Mozilla Firefox (0.10)"
	REM @call :uninstall_helper "Mozilla Firefox (0.10.1)"
	REM @call :uninstall_helper "Mozilla Firefox (1.0)"
	REM @call :uninstall_helper "Mozilla Firefox (1.0.1)"
	REM @call :uninstall_helper "Mozilla Firefox (1.0.2)"
	REM @call :uninstall_helper "Mozilla Firefox (1.0.3)"
	REM @call :uninstall_helper "Mozilla Firefox (1.0.4)"
	REM @call :uninstall_helper "Mozilla Firefox (1.0.5)"
	REM @call :uninstall_helper "Mozilla Firefox (1.0.6)"
	REM @call :uninstall_helper "Mozilla Firefox (1.0.7)"
	REM @call :uninstall_helper "Mozilla Firefox (1.0.8)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.1)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.2)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.3)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.4)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.5)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.6)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.7)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.8)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.9)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.10)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.11)"
	REM @call :uninstall_helper "Mozilla Firefox (1.5.0.12)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.1)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.2)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.3)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.4)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.5)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.6)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.7)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.8)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.9)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.10)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.11)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.12)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.13)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.14)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.15)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.16)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.17)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.18)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.19)"
	REM @call :uninstall_helper "Mozilla Firefox (2.0.0.20)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.1)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.2)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.3)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.4)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.5)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.6)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.7)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.8)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.9)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.10)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.11)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.12)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.13)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.14)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.15)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.16)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.17)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.18)"
	REM @call :uninstall_helper "Mozilla Firefox (3.0.19)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.1)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.2)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.3)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.4)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.5)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.6)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.7)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.6)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.7)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.8)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.9)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.10)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.11)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.12)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.13)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.14)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.15)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.16)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.17)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.18)"
	REM @call :uninstall_helper "Mozilla Firefox (3.5.19)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.2)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.3)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.4)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.6)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.7)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.8)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.9)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.10)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.11)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.12)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.13)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.14)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.15)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.16)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.17)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.18)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.19)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.20)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.21)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.22)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.23)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.24)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.25)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.26)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.27)"
	REM @call :uninstall_helper "Mozilla Firefox (3.6.28)"
	REM @call :uninstall_helper "Mozilla Firefox 4.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 4.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 5.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 5.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 6.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 6.0.2 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 7.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 7.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 8.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 8.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 9.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.2 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.3esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.4esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.5esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.6esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.7esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.8esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.9esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.10esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.11esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 10.0.12esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 11.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 12.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 13.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 13.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 14.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 14.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 15.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 15.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 16.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 16.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 16.0.2 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 17.0 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 17.0.1 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 17.0esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 17.0.1esr (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 17.0.2 (x86 de)"
	REM @call :uninstall_helper "Mozilla Firefox 18.0 (x86 de)"
	@call :uninstall_helper "Mozilla Firefox 18.0.1 (x86 de)"

:finish

uninstall-tb.bat

:: Bulk Uninstaller for Mozilla Thunderbird
:: Written by:
:: Uwe Stoppel < uwe/at/stoppel.name > < https://heyfryckles.wordpress.com >

@echo off

goto start

:uninstall_helper

	set SWNAME=%1
	
	:: Remove Quotation Marks
	set SWNAME=###%SWNAME%###
	set SWNAME=%SWNAME:"###=%
	set SWNAME=%SWNAME:###"=%
	set SWNAME=%SWNAME:###=%

	:: Searching the 32-Bit Regkeys for our SWNAME
	set REGKEY=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\%SWNAME%
	@call reg.exe QUERY "%REGKEY%" > nul 2>&1
	if %ERRORLEVEL% == 0 (
		@echo "%SWNAME%" found. Uninstalling...
		call :uninstall
	)
	
	:: Searching the 64-Bit Regkeys for our SWNAME
	set REGKEY=HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\%SWNAME%
	@call reg.exe QUERY "%REGKEY%" > nul 2>&1
	if %ERRORLEVEL% == 0 (
		@echo "%SWNAME%" found. Uninstalling...
		call :uninstall
	)
	
	goto finish

:uninstall

	@echo Killing running processes...
	@call taskkill.exe /F /IM thunderbird.exe > nul 2>&1

	for /F "tokens=2*" %%a in ('reg.exe QUERY "%REGKEY%" /v InstallLocation ^|findstr InstallLocation') DO SET INSTALLLOCATION=%%b
	for /F "tokens=2*" %%a in ('reg.exe QUERY "%REGKEY%" /v DisplayVersion ^|findstr DisplayVersion') DO SET DISPLAYVERSION=%%b

	@echo %SWNAME% | find "d (0." > nul 2>&1
	if %ERRORLEVEL% == 0 (
		@call "%SYSTEMROOT%\UninstallThunderbird.exe" /ms /ua "%DISPLAYVERSION%"
		goto finish
	)

	@echo %SWNAME% | find "d (1." > nul 2>&1
	if %ERRORLEVEL% == 0 (
		@call "%SYSTEMROOT%\UninstallThunderbird.exe" /ms /ua "%DISPLAYVERSION%"
		goto finish
	)	

	@call "%INSTALLLOCATION%\Uninstall\helper.exe" /s

goto finish

:start

	:: see https://en.wikipedia.org/wiki/History_of_Mozilla_Thunderbird
	
	REM @call :uninstall_helper "Mozilla Thunderbird (0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.2)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.3)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.4)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.5)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.6)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.7)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.7.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.7.2)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.7.3)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.8)"
	REM @call :uninstall_helper "Mozilla Thunderbird (0.9)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.0.2)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.0.6)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.0.7)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.0.8)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.2)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.4)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.5)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.7)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.8)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.9)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.10)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.12)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.13)"
	REM @call :uninstall_helper "Mozilla Thunderbird (1.5.0.14)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.4)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.5)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.6)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.9)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.12)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.14)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.16)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.17)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.18)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.19)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.21)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.22)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.23)"
	REM @call :uninstall_helper "Mozilla Thunderbird (2.0.0.24)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.2)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.3)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.4)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.5)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.6)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.7)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.8)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.9)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.10)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.0.11)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.2)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.3)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.4)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.5)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.6)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.7)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.8)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.9)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.10)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.11)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.12)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.13)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.14)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.15)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.16)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.17)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.18)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.19)"
	REM @call :uninstall_helper "Mozilla Thunderbird (3.1.20)"
	REM @call :uninstall_helper "Mozilla Thunderbird (5.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (6.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (6.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (6.0.2)"
	REM @call :uninstall_helper "Mozilla Thunderbird (7.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (7.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (8.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (9.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (9.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (10.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (10.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (10.0.2)"
	REM @call :uninstall_helper "Mozilla Thunderbird (10.0.3)"
	REM @call :uninstall_helper "Mozilla Thunderbird (10.0.4esr)"
	REM @call :uninstall_helper "Mozilla Thunderbird (10.0.5esr)"
	REM @call :uninstall_helper "Mozilla Thunderbird (10.0.6esr)"
	REM @call :uninstall_helper "Mozilla Thunderbird (10.0.7esr)"
	REM @call :uninstall_helper "Mozilla Thunderbird (11.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (11.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (12.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (12.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (13.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (13.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (14.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (15.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (15.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (16.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (16.0.1)"
	REM @call :uninstall_helper "Mozilla Thunderbird (17.0)"
	REM @call :uninstall_helper "Mozilla Thunderbird (17.0.1)"
	@call :uninstall_helper "Mozilla Thunderbird 17.0.2 (x86 de)"

:finish

Windows PowerShell Script for querying and managing Windows DHCP Service in Windows Server 2003 and 2008

February 5, 2013 Leave a comment

We all know that Windows Powershell didn’t have any CMDlets for Managing the Windows DHCP Services from the beginning. I think it came with Powershell 3.0. But what if you want to manage a machine that doesn’t have this capability?

Four years ago, I wrote These three scripts that makes use of netsh.exe. Perhaps it can be of any use for somebody.

  • Get-DHCPClients.ps1 queries the DHCP Server and ouputs object taht can be used by the other two Scripts.
  • Set-DHCPReservation.ps1 takes an Object and converts a DHCP lease into a DHCP Reservation.
  • Wakeup.ps1 takes an object and sends a Wake on LAN (WOL) Magic Packet to it.
    • Please note that

      • As it is, it will only work with Windows Server 2003 and Windows Server 2008 in the English language version.
      • You must run the script directly on the DHCP Server machine.
      • You must run the script as an Admin from an elevated prompt.
      • Set-DHCPReservation.ps1 and Wakeup.ps1 have to be used with Get-DHCPClients.ps1. They cannot be used directly.

      Get-DHCPClients.ps1

      
      # Written by: 
      # Uwe Stoppel < uwe/at/stoppel.name > < https://heyfryckles.wordpress.com > 
      
      begin
      { 
      
      }
      
      process
      {
      
      	# We get all Scopes from our DHCP Server
      	$objDHCPScopes = netsh dhcp server show scope
      
      	# We need administrative rights in Windows 2008 and onwards, otherwise, we get stopped by the UAC
      	if ($objDHCPScopes -eq "The requested operation requires elevation.")
      	{
      		write-host $objDHCPScopes
      	}
      	else
      	{
      		# netsh outputs 6 lines before and 4 lines below our output
      		$objDHCPScopes[5..($objDHCPScopes.length-4)] | foreach {	
       
      			$objRow1 = $_.split(" ",[StringSplitOptions]::RemoveEmptyEntries) 
      
      			$objDHCPScope = $objRow1[0]
      
      			# We get all leases from out DHCP server
      			$objDHCPLeases = netsh dhcp server scope $objDHCPScope show clientsv5 1
      
      			$objDHCPScope = @{name="Scope";expression={$row[0]}}
      
      			# netsh outputs 9 lines before and 5 lines below our output
      			if ($objDHCPLeases.length -gt 12) {
      
      				$objDHCPLeases[8..($dhcpleases.length-5)] | foreach {
      
      					$objRow2 = $_
      				
      					# We must correct the output for DHCP reservations, as there is no space between the MACn address and the reservation
      					# Because the position of the dash is always the same, we input a space by ourself. We need the space so we can build an array.
      					if ($objRow2.substring(34,1) -ne " ") {
      						$objRow2 = $objRow2.substring(0,34) + " " + $objRow2.substring(34,$objRow2.length-34)
      					}
      
      					# If the lease has no hostname, we invent one.
      					if ($objRow2.length -le 84) {
      						$objRow2 = $objRow2.substring(0,84) + "_no-hostname_"
      					}
      
      					# We filter out Leases for RAS Clients. These have a seventh Block "-XY" instead of a space.
      					if ($objRow2.substring(52,1) -eq " ") {
      
      						$objRow2 = $objRow2.split("  ",[StringSplitOptions]::RemoveEmptyEntries)
      
      						$objIPAddress = @{name="IP"; expression={$objRow2[0].trim()}} 
      						$objMACAddress = @{name="MAC"; expression={$objRow2[4].trim().replace("-",":").toUpper()}} 
      						$strHostName = $objRow2[-1].trim()
      
      						# We check if we have a FQDN, and if so, we extract the hostname
      						if ($strHostName -match "[.]")
      						{
      							$objHostName = @{name="Name"; expression={$strHostName.substring(0,$strHostName.indexOf(".")).toUpper()}}
      						}
      						else
      						{
      							$objHostName = @{name="Name"; expression={$strHostName.toUpper()}}
      						}
      
      						# We output our results as PS Objects
      						"" | select $objIPAddress, $objMACAddress, $objHostName, $objDHCPScope
      
      					}
      				}
      			}
      		}
      	}
      }
      end
      {
      
      }
      

      The Script Outputs PS Objects that can be piped into other commands.
      For example, we could convert the Leases into Reservations with Set-DHCPReservation.ps1.

      .\Get-DHCPClients.ps1 | .\Set-DHCPReservation.ps1

      Set-DHCPReservation.ps1

      # Written by: 
      # Uwe Stoppel < uwe/at/stoppel.name > < https://heyfryckles.wordpress.com > 
      
      begin
      { 
      
      }
      
      process
      {
      
      	$objPipeData = $_
      	$objFields = ($_ | gm -MemberType NoteProperty) 
      
      	foreach($objItem in $objFields) {
      
      		if ($objItem.name -eq "IP")
      		{
      			$strIP = $objPipeData.($objItem.name)
      		}
      
      		if ($objItem.name -eq "MAC")
      		{
      			$strMAC = $objPipeData.($objItem.name).replace(":","")
      		}
      
      		if ($objItem.name -eq "Name")
      		{
      			$strName = $objPipeData.($objItem.name)
      		}
      
      		if ($objItem.name -eq "Scope")
      		{
      			$strScope = $objPipeData.($objItem.name)
      		}
      
      	}
      
      	if ($IP -and $MAC -and $Name -and $Scope)
      	{
      		$objCommand = netsh dhcp server scope $strScope add reservedip $strIP $strMAC $strName
      		write-host $objCommand
      	}
      
      }
      
      end
      {
      
      }
      

      We also could send a Wake on LAN (WOL) Command to them.

      .\Get-DHCPClients | .\Wakeup.ps1

      Wakeup.ps1

      # Written by: 
      # Uwe Stoppel < uwe/at/stoppel.name > < https://heyfryckles.wordpress.com > 
      
      begin
      { 
      
      }
      
      process
      {
      
      	$objUDPClient = new-Object System.Net.Sockets.UdpClient
      
      	$objUDPClient.Connect(([System.Net.IPAddress]::Broadcast),4000)
      
      	$objPipeData = $_
      	$objFields = ($_ | gm -MemberType NoteProperty) 
      
      	foreach($objItem in $objFields) {
      
      		if ($objItem.name -eq "MAC")
      		{
      
      		# The Magic Packet [...] will be sent as a broadcast.
      		# It contains 6x the hexadecimal Value FF, and then 16x the MAC-Address
      
      		$strMacAddress = $objPipeData.($objItem.name).split(':') | %{ [byte]('0x' + $_) }
      
      		$objPacket = [byte[]](,0xFF * 6)
      
      		$objPacket += $strMacAddress * 16
      
      		write-debug ([bitconverter]::tostring($objPacket))
      
      		[void] $objUDPClient.Send($objPacket, $objPacket.Length)
      
      		write-host "Wake-On-Lan magic packet of length $($objPacket.Length) sent to $($objPipeData.($objItem.name))"
      
      		}
      
      	}
      
      }
      
      end
      {
      
      }
      

Batch Script for automatically uninstalling all Java Runtime Environment (JRE) Instances on a PC

February 5, 2013 4 comments

Below, you’ll find a Little helper script that fully automatically uninstalls all Java Runtime Environment (JRE) Instances from JRE 1.4 up to JRE 1.7 from the targeted machine. This might come in handy if you want to clean up a PC from old JRE junk Prior to deploying the most current Version.

remove-jre

  • You must run the Script with Admin rights.
  • The Script works with both x86 and x64 machines.
  • It recognizes the x86 and x64 Versions of the JRE up to JRE 1.6 Update 39 and JRE 1.7 Update 13.
  • You will Need at least Windows XP. You may can modify it to work with Windows 2000 when you use reg.exe from the Resource Kit and kill.exe from Sysinternals.

uninstall-jre.bat

:: Bulk JRE Uninstaller
:: Written by:
:: Uwe Stoppel < uwe/at/stoppel.name > < https://heyfryckles.wordpress.com >

@echo off

goto start

:uninstall_helper

	set SWUUID=%1

	:: Remove Quotation Marks
	set SWUUID=###%SWUUID%###
	set SWUUID=%SWUUID:"###=%
	set SWUUID=%SWUUID:###"=%
	set SWUUID=%SWUUID:###=%

	:: Searching the 32-Bit Regkeys for our UUID
	set REGKEY=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\%SWUUID%	
	@call reg.exe QUERY "%REGKEY%" > nul 2>&1
	if %ERRORLEVEL% == 0 (
		goto uninstall
	)
	
	:: Searching the 64-Bit Regkeys for our UUID
	set REGKEY=HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\%SWUUID%
	@call reg.exe QUERY "%REGKEY%" > nul 2>&1
	if %ERRORLEVEL% == 0 (
		goto uninstall
	)
	
	goto finish

:uninstall

	set SERVICES=HKLM\SYSTEM\CurrentControlSet\Services

	:: If the Java Quick Starter Service is present, we stop it
	@call reg.exe QUERY "%SERVICES%\JavaQuickStarterService" > nul 2>&1
	if %ERRORLEVEL% == 0 (
		@echo Stopping Service Java Quick Starter...
		@call net.exe stop JavaQuickStarterService > nul 2>&1
		@call taskkill.exe /F /IM jqs.exe
	)

	:: Killing all remaining Java processes
	@call taskkill.exe /F /IM javaw.exe > nul 2>&1
	@call taskkill.exe /F /IM javaws.exe > nul 2>&1

	:: Killing all OpenOffice processes...
	@call taskkill.exe /F /IM soffice.bin.exe > nul 2>&1
	@call taskkill.exe /F /IM soffice.exe > nul 2>&1
	@call taskkill.exe /F /IM swriter.exe > nul 2>&1
	@call taskkill.exe /F /IM scalc.exe > nul 2>&1
	@call taskkill.exe /F /IM sdraw.exe > nul 2>&1
	@call taskkill.exe /F /IM simpress.exe > nul 2>&1
	@call taskkill.exe /F /IM smath.exe > nul 2>&1
	@call taskkill.exe /F /IM sweb.exe > nul 2>&1

	for /F "tokens=2*" %%a in ('reg.exe QUERY "%REGKEY%" /v DisplayName ^|findstr DisplayName') DO SET SWNAME=%%b
	
	@echo Uninstalling %SWNAME%...
	@call MsiExec.exe /qn /norestart /x %SWUUID%

goto finish

:start

	@echo Searching for installed JRE instances...

	:: Java Runtime Environment 1.7 (x64)
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417013FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417012FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417011FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417010FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417009FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417008FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417007FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417006FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417005FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417004FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417003FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417002FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417001FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86417000FF}"

	:: Java Runtime Environment 1.7 (x86)
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217013FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217011FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217011FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217010FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217009FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217008FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217007FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217006FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217005FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217004FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217003FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217002FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217001FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83217000FF}"

	:: Java Runtime Environment 1.6 (x64)
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416039FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416039F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416038FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416038F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416037FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416037F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416036FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416036F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416035FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416035F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416034FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416034F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416033FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416033F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416032FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416032F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416031FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416031F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416030FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416030F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416029FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416029F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416028FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416028F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416027FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416027F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416026FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416026F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416025FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416025F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416024FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416024F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416023FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F86416023F0}"

	:: Java Runtime Environment 1.6 (x86)
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216039FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216039F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216038FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216038F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216037FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216037F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216036FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216036F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216035FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216035F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216034FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216034F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216033FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216033F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216032FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216032F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216031FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216031F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216030FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216030F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216029FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216029F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216028FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216028F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216027FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216027F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216026FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216026F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216025FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216025F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216024FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216024F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216023FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216023F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216022FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216022F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216021FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216021F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216020FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216020F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216019FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216019F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216018FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216018F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216017FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216017F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216016FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216016F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216015FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216015F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216014FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216014F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216013FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216013F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216012FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216012F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216011FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216011F0}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216011FF}"
	@call :uninstall_helper "{26A24AE4-039D-4CA4-87B4-2F83216010F0}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0160070}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0160060}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0160050}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0160040}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0160030}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0160020}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0160010}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0160000}"

	:: Java Runtime Environment 1.5
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150220}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150210}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150200}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150190}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150180}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150170}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150160}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150150}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150140}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150130}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150120}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150110}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150100}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150090}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150080}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150070}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150060}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150050}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150040}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150030}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150020}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150010}"
	@call :uninstall_helper "{3248F0A8-6813-11D6-A77B-00B0D0150000}"

	:: Java Runtime Environment 1.4
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142190}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142180}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142170}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142160}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142150}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142140}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142130}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142120}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142110}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142100}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142090}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142080}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142070}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142060}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142050}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142040}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142030}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142020}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142010}"
	@call :uninstall_helper "{7148F0A8-6813-11D6-A77B-00B0D0142000}"

	:: Java Auto Updater
	@call :uninstall_helper "{4A03706F-666A-4037-7777-5F2748764D10}"

:finish