:::: MENU ::::

Powershell Script for All ADUsers


                PROCESS #This is where the script executes 
{ 
    $path = "C:\temp\" 
    $pathexist = Test-Path -Path $path 
    If ($pathexist -eq $false) 
    {New-Item -type directory -Path $path} 
     
    $reportdate = Get-Date -Format ssddmmyyyy 
 
    $csvreportfile = $path + "\ALLADUsers_$reportdate.csv" 
     
    #import the ActiveDirectory Module 
    Import-Module ActiveDirectory 
     
    #Perform AD search. The quotes "" used in $SearchLoc is essential 
    #Without it, Export-ADUsers returuned error 
                  Get-ADUser -Properties * -Filter * |  
                  Select-Object @{Label = "First Name";Expression = {$_.GivenName}},  
                  @{Label = "Last Name";Expression = {$_.Surname}}, 
                  @{Label = "Display Name";Expression = {$_.DisplayName}}, 
                  @{Label = "Logon Name";Expression = {$_.sAMAccountName}}, 
                  @{Label = "Full address";Expression = {$_.StreetAddress}}, 
                  @{Label = "City";Expression = {$_.City}}, 
                  @{Label = "State";Expression = {$_.st}}, 
                  @{Label = "Post Code";Expression = {$_.PostalCode}}, 
                  @{Label = "Country/Region";Expression = {if (($_.Country -eq 'GB')  ) {'United Kingdom'} Else {''}}}, 
                  @{Label = "Job Title";Expression = {$_.Title}}, 
                  @{Label = "Company";Expression = {$_.Company}}, 
                  @{Label = "Description";Expression = {$_.Description}}, 
                  @{Label = "Department";Expression = {$_.Department}}, 
                  @{Label = "Office";Expression = {$_.OfficeName}}, 
                  @{Label = "Phone";Expression = {$_.telephoneNumber}}, 
                  @{Label = "Email";Expression = {$_.Mail}}, 
                  @{Label = "Manager";Expression = {%{(Get-AdUser $_.Manager -Properties DisplayName).DisplayName}}}, 
                  @{Label = "Account Status";Expression = {if (($_.Enabled -eq 'TRUE')  ) {'Enabled'} Else {'Disabled'}}}, # the 'if statement# replaces $_.Enabled 
                  @{Label = "Last LogOn Date";Expression = {$_.lastlogondate}} |  
                   
                  #Export CSV report 
                  Export-Csv -Path $csvreportfile -NoTypeInformation     
} 





Turn off Bluetooth if no Device is connected actively

Get the Exe file from the following website -

https://www.nirsoft.net/utils/bluetooth_viewer.html

create the following power shell script

$LogFile = "C:\Windows\MSSCCM\Logs\Toggle_Bluetooth_OFF.log"
Function LogWrite
{
Param ([string]$logstring)
$logcontent = "$date $logstring"
Add-Content $Logfile -Value $logcontent
}

New-Item -ItemType Directory -Path "C:\Windows\MSSCCM\Scripts\Bluetooth" -Force -ErrorAction SilentlyContinue

$date=Get-Date -Format g
$PREDirectory = Split-Path -Parent $MyInvocation.MyCommand.Definition
$InstDir = Split-Path -parent $MyInvocation.MyCommand.Definition

LogWrite "START $date*********************************************"

$Parameters = '/sxml "C:\Windows\MSSCCM\Scripts\bluetooth\bluetooth.xml"'
$Commandtorun = "btView.exe"
$process= Start-Process $CommandToRun $Parameters -PassThru -wait -workingdirectory $InstDir
$ExtVal = $process.ExitCode
logwrite "created the XML file with code:$ExtVal"

if(Test-Path "C:\Windows\MSSCCM\Scripts\bluetooth\bluetooth.xml")
{

logwrite "Searching for any connected devices"

$IS_device_connected = Select-String -Path "C:\Windows\MSSCCM\Scripts\bluetooth\bluetooth.xml" -Pattern "<connected>Yes</connected>" -SimpleMatch -Quiet


if(!$IS_device_connected)
{

logwrite "NO Devices are connected, so toggling the bluetooth setting OFF"

################################################################
#*********TURN OFF BLUETOOTH AS NO DEVICE IS CONNECTED*********#
################################################################
 Function Bluetooth {
 [CmdletBinding()] 
 Param (
 [Parameter(Mandatory=$true)][ValidateSet('Off', 'On')][string]$BluetoothStatus
 )
 
 If ((Get-Service bthserv).Status -eq 'Stopped') { Start-Service bthserv }
 Add-Type -AssemblyName System.Runtime.WindowsRuntime
 $asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
 
 Function Await($WinRtTask, $ResultType) {
 $asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
 $netTask = $asTask.Invoke($null, @($WinRtTask))
 $netTask.Wait(-1) | Out-Null
 $netTask.Result
 }
 
 [Windows.Devices.Radios.Radio,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
 [Windows.Devices.Radios.RadioAccessStatus,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
 Await ([Windows.Devices.Radios.Radio]::RequestAccessAsync()) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
 $radios = Await ([Windows.Devices.Radios.Radio]::GetRadiosAsync()) ([System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]])
 $bluetooth = $radios | ? { $_.Kind -eq 'Bluetooth' }
 [Windows.Devices.Radios.RadioState,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
 Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
}
 


Bluetooth -Verbose -BluetoothStatus Off


LogWrite "Turned OFF the bluetooth on the machine"

####################################################################
####################################################################

}
else
{

LogWrite "Exiting the Script as there are Bluetooth devices connected to the machine "

}


}
else
{

LogWrite "There was an error running the tool to create the XML file"

}

LogWrite "END $date******************************************************"
LogWrite ""


CCM repair

#Stop and remove ccm service
& sc stop ccmsetup
& sc delete ccmsetup

#Remove ccm certs
Remove-Item ‘HKLM:\SOFTWARE\Microsoft\SystemCertificates\SMS\Certificates\*’ -Force

#Remove ccm files
Remove-Item -Path $env:windir\ccm -Recurse -Force
Remove-Item -Path $env:windir\system32\ccm -Recurse -Force
Remove-Item -Path $env:windir\ccmcache -Recurse -Force
Remove-Item -Path $env:windir\ccmsetup -Recurse -Force
Remove-Item -Path $env:windir\system32\ccmsetup -Recurse -Force
Remove-Item -Path $env:windir\smscfg.ini -Force
Remove-Item -Path $env:windir\sms*.mif -Force

#Remove ccm registry keys
$RegRoot = “HKLM:\Software\Microsoft”
Remove-Item -Path “$RegRoot\ccm” -Recurse -Force
Remove-Item -Path “$RegRoot\ccmsetup” -Recurse -Force
Remove-Item -Path “$RegRoot\sms” -Recurse -Force

#Remove ccm wmi namespaces
Get-WmiObject -Query “SELECT * FROM __Namespace WHERE Name=’CCM'” -Namespace “root” | Remove-WmiObject
Get-WmiObject -Query “SELECT * FROM __Namespace WHERE Name=’SMS'” -Namespace “root\cimv2” | Remove-WmiObject

#Repair WMI
$Path = ‘C:\Windows\System32\wbem’
Stop-Service -Name Winmgmt -Force
Remove-Item “$Path\repository” -Recurse -Force
& wmiprvse /regserver
Start-Service -Name Winmgmt
Get-ChildItem $Path -Filter *.dll | ForEach-Object { & regsvr32.exe /s $_.FullName } | Out-Null
Get-ChildItem $Path -Filter *.mof | ForEach-Object { & mofcomp.exe $_.FullName } | Out-Null
Get-ChildItem $Path -Filter *.mfl | ForEach-Object { & mofcomp.exe $_.FullName } | Out-Null
& mofcomp.exe ‘C:\Program Files\Microsoft Policy Platform\ExtendedStatus.mof’ | Out-Null


%Microsoft Visio Professional%


&nbsp;

Select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceId = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.DisplayName = "%Microsoft Visio Professional%"

&nbsp;


Get the details of all files and folders using power-shell

Change the path variable for your requests-


$path = "C:\temp\"

Get-ChildItem -Path $path |Select-Object *|Export-Csv -Path "C:\temp\Folder_details.csv" -Force

 

if you want just the path and name of the files/folders –

 


$path = "C:\temp\"

Get-ChildItem |Select-Object name,fullname |Export-Csv -Path "C:\temp\Folder_details.csv" -Force

 


%Office% SQL


SELECT DISTINCT  
  SYS.Name0
  ,ARP.DisplayName0 As 'Software Name'
  ,ARP.Version0 As 'Version'
  ,ARP.InstallDate0 As 'Installed Date'
 FROM 
  dbo.v_R_System As SYS
  INNER JOIN dbo.v_FullCollectionMembership FCM On FCM.ResourceID = SYS.ResourceID 
  INNER JOIN dbo.v_Add_REMOVE_PROGRAMS As ARP On SYS.ResourceID = ARP.ResourceID 
 WHERE   
 (ARP.DisplayName0 LIKE '%Microsoft % Standard%'
 OR ARP.DisplayName0 LIKE 'Microsoft % Professional%'
 OR ARP.DisplayName0 LIKE 'Microsoft % Enterprise %')
 ORDER BY Name0 ASC


Office Uninstallation

Get off-scrub scripts from the following location and save them with appropriate names –

https://blogs.technet.microsoft.com/odsupport/2011/04/08/how-to-obtain-and-use-offscrub-to-automate-the-uninstallation-of-office-products/

Here in the below, the script I used has following names –

Office2007remove.vbs

OffScrub10.vbs

OffScrubc2r.vbs

OffScrub_O15msi.vbs

These are from Microsoft, please accept the license and use it

It is recommended to pop-up a notification to the user, before we close all office applications to uninstall the products.

http://blog.ctglobalservices.com/configuration-manager-sccm/kea/new-version-of-the-coretech-shutdown-tool/

 

Files needed to do an uninstall –

  1. App shutdown tool
  2. office (download the latest bits)
  3. vb scripts downloaded (i would recommend doing the same way I followed below to remove all known and unknown office from the machine)
  4. get the appropriate XML files which suit your environment.
  5. PSLoggedon.exe from Microsoft to find the logged-on user

Typical XML file would look like – ( OfficeSuite365.xml)


<Configuration>
<Add OfficeClientEdition="64" >
<Product ID="O365ProPlusRetail">
<Language ID="en-us" />
<ExcludeApp ID="Lync" />
</Product>
<Product ID="SPDRetail">
<Language ID="en-us" />
</Product>
<Product ID="VisioProRetail">
<Language ID="en-us" />
</Product>
<Product ID="ProjectProRetail">
<Language ID="en-us" />
</Product>
</Add>
<Updates Enabled="FALSE" />
<Display Level="Full" AcceptEULA="TRUE" />
<Logging Level="Standard" Path="C:\Windows\OFFICE\Logs" />
<Property Name="FORCEAPPSHUTDOWN" Value="TRUE"/>
<Property Name="AUTOACTIVATE" Value="1" />
</Configuration>

Office_Prevalidator.ps1

Command to run in command prompt from the folder where all the files are located is –

“C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe” -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -File “%~dp0PreValidator.ps1”

 


$logFile = "C:\Windows\Logs\Microsoft_Office_C2R_X64_Prevalidator.log"
$Component = "Installation"

Function LogWrite {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
$sLogMsg
)
PROCESS {
# Populate the variables to log

$sTime = (Get-Date -Format HH:mm:ss) + ".000+000"
$sDate = Get-Date -Format MM-dd-yyyy
$sTempMsg = "&amp;amp;amp;lt;![LOG[$sLogMsg]LOG]!&amp;amp;amp;gt;&amp;amp;amp;lt;time=""$sTime"" date=""$sDate"" component=""$Component"" context="""" type="""" thread="""" file=""$Component""&amp;amp;amp;gt;"
# Create the component log entry

Write-Output $sTempMsg | Out-File -FilePath $logFile -Encoding "Default" -Append

}
} # End of Create-LogEntry function

Function Check-IfUserloggedon
{
$Computer = $env:COMPUTERNAME
[object[]]$sessions = Invoke-Expression ("$InstDir\PsLoggedon.exe -accepteula -x -l \\$Computer 2&amp;amp;amp;gt; null") |
Where-Object {$_ -match '^\s{2,}((?&amp;amp;amp;lt;domain&amp;amp;amp;gt;\w+)\\(?&amp;amp;amp;lt;user&amp;amp;amp;gt;\S+))'} |
Select-Object @{
Name='Computer'
Expression={$Computer}
},
@{
Name='Domain'
Expression={$matches.Domain}
},
@{
Name='User'
Expression={$Matches.User}
}
IF ($Sessions.count -ge 1)
{
Write-Host ("{0} Users Logged into {1}" –f $Sessions.count,
$Computer) -ForegroundColor 'Red'
Return $true
}
Else
{
Write-Host ("{0} can be rebooted!" -f $Computer) `
-ForegroundColor 'Green'
Return $false
}

}
Function KillProcess
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
$PSName
)
$CMDLine="C:\Windows\system32\taskkill.exe"
$CMDArgs=" /F /IM $PSName"
LogWrite "$CMDLine $CMDArgs"
LogWrite "Running Command: $CMDLine $CMDArgs"
$process= Start-Process $CMDLine $CMDArgs -WindowStyle Hidden -PassThru -wait -workingdirectory $Instdir
$RetVal = $process.ExitCode
LogWrite "ExitCode $RetVal"
}

$Chklogon = Check-IfUserloggedon

If ($Chklogon -eq $true)
{
LogWrite "An active User Session exists Will display Application Shutdown Prompt"
}

If ($Chklogon -eq $false)

{
LogWrite "No User is logged on to this machine. Hence skipping the Application Shutdown Prompt"
KillProcess -PSName 'OfficeClicktorun.exe'
Start-Sleep 2
KillProcess -PSName 'OfficeClicktorun.exe'
Start-Sleep 5
KillProcess -PSName 'OfficeClicktorun.exe'
KillProcess -PSName 'SPDESIGN.exe'
KillProcess -PSName 'VISIO.exe'
KillProcess -PSName 'WINPROJ.exe'
}
$AppShutdir = "$InstDir\AppShutdown"
$CMDLine="C:\Windows\system32\cmd.exe"
$CMDArgs=' /c Notify.bat'
LogWrite "$CMDLine $CMDArgs"
LogWrite "Running Command: $CMDLine $CMDArgs"
$process= Start-Process $CMDLine $CMDArgs -WindowStyle Hidden -PassThru -wait -workingdirectory $AppShutdir
$RetVal = $process.ExitCode
$RetVal
LogWrite "ExitCode $RetVal"
if ($RetVal -eq 0)
{
#=======================================================================================================================================================================#
#Setting up stage for Office C2R 64Bit Installation
#=======================================================================================================================================================================#

#=======================================================================================================================================================================#
#Functions
#=======================================================================================================================================================================#

Function LogWrite {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
$sLogMsg
)
PROCESS {
# Populate the variables to log

$sTime = (Get-Date -Format HH:mm:ss) + ".000+000"
$sDate = Get-Date -Format MM-dd-yyyy
$sTempMsg = "&amp;amp;amp;lt;![LOG[$sLogMsg]LOG]!&amp;amp;amp;gt;&amp;amp;amp;lt;time=""$sTime"" date=""$sDate"" component=""$Component"" context="""" type="""" thread="""" file=""$Component""&amp;amp;amp;gt;"
# Create the component log entry

Write-Output $sTempMsg | Out-File -FilePath $logFile -Encoding "Default" -Append

}
} # End of Create-LogEntry function

#=================================================== Check if User Logged in ============================================================================#

Function Check-IfUserloggedon
{
$Computer = $env:COMPUTERNAME
[object[]]$sessions = Invoke-Expression ("$InstDir\PsLoggedon.exe -accepteula -x -l \\$Computer 2&amp;amp;amp;gt; null") |
Where-Object {$_ -match '^\s{2,}((?&amp;amp;amp;lt;domain&amp;amp;amp;gt;\w+)\\(?&amp;amp;amp;lt;user&amp;amp;amp;gt;\S+))'} |
Select-Object @{
Name='Computer'
Expression={$Computer}
},
@{
Name='Domain'
Expression={$matches.Domain}
},
@{
Name='User'
Expression={$Matches.User}
}
IF ($Sessions.count -ge 1)
{
Write-Host ("{0} Users Logged into {1}" –f $Sessions.count,
$Computer) -ForegroundColor 'Red'
Return $true
}
Else
{
Write-Host ("{0} can be rebooted!" -f $Computer) `
-ForegroundColor 'Green'
Return $false
}

}
################################################Functions to get ADDREMOVEPROGRAMS ###########################################################

function Get-Uninstall
{
# paths: x86 and x64 registry keys are different
if ([IntPtr]::Size -eq 4) {
$path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
}
else {
$path = @(
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
}

# get all data
Get-ItemProperty $path |
# use only with name and unistall information
.{process{ if ($_.DisplayName -and $_.UninstallString) { $_ } }} |
# select more or less common subset of properties
Select-Object DisplayName, Publisher, InstallDate, DisplayVersion, HelpLink, UninstallString |
# and finally sort by name
Sort-Object DisplayName
}

function isOfficeMSI_Installed
{
Param ([string] $OffVer)

$OfficeMSI_Paths = @("$env:CommonProgramFiles\microsoft Shared\$OffVer\mso.dll","${env:CommonProgramFiles(x86)}\microsoft Shared\$OffVer\mso.dll")
foreach($OfficeMSI_Path in $OfficeMSI_Paths)
{
if(Test-Path $OfficeMSI_Path)
{
return $true
}
}

return $false
}

function isOfficeC2R_Installed
{
Param ([string] $OffVer)

switch ($OffVer)
{
"Office16"
{
$Office16C2R_Paths = @("$env:ProgramFiles\Microsoft Office\root\Office16\c2r32.dll","$env:ProgramFiles\Microsoft Office\root\Office16\c2r64.dll")
foreach($Office16C2R_Path in $Office16C2R_Paths)
{
if(Test-Path $Office16C2R_Path)
{
return $true
}
}
return $false
}
"Office15"
{
$Office15C2R_Paths = @("$env:ProgramFiles\Microsoft Office 15\root\Office15\c2r32.dll","$env:ProgramFiles\Microsoft Office 15\root\Office15\c2r64.dll")
foreach($Office15C2R_Path in $Office15C2R_Paths)
{
if(Test-Path $Office15C2R_Path)
{
return $true
}
}
return $false
}
"Office14"
{
$Office14C2R_Paths = @("$env:ProgramFiles\Common Files\microsoft shared\Virtualization Handler\CVH.EXE","${env:CommonProgramFiles(x86)}\Common Files\microsoft shared\Virtualization Handler\CVH.EXE")
foreach($Office14C2R_Path in $Office14C2R_Paths)
{
if(Test-Path $Office14C2R_Path)
{
return $true
}
}
return $false
}
}
}
function OfficeC2R-Arch()
{
$officearchitecture = "HKLM:\SOFTWARE\Microsoft\Office\15.0\ClickToRun\Configuration" #For O15 SP1
$officearchitecture1 = "HKLM:\SOFTWARE\Microsoft\Office\15.0\ClickToRun\propertyBag" #For O15
if(Test-Path $officearchitecture)
{
$Key = Get-Item -path $officearchitecture

if(($Key.GetValue("platform")) -ne $null)
{
$platform = Get-ItemProperty -Path $officearchitecture -Name Platform |%{$_.Platform}

}
}
elseif(Test-Path $officearchitecture1)
{
$Key1 = Get-Item -path $officearchitecture1

if(($Key1.GetValue("platform")) -ne $null)
{
$platform = Get-ItemProperty -Path $officearchitecture1 -Name Platform |%{$_.Platform}

}
}

if(($platform -eq "x86")) #-or ($platform -eq $null))
{
$platform = "32bit"
}
elseif($platform -eq "x64")
{
$platform = "64bit"
}

return $platform
}
#Declarations
$InstDir = Split-Path -parent $MyInvocation.MyCommand.Definition #Getting Current directory for the script
$c2r15_path = join-path $env:SystemDrive "Program Files\Microsoft Office 15\"
$c2r16_path = join-path $env:SystemDrive "Program Files\Microsoft Office\"
$itemc2r16= "HKLM:\Software\Microsoft\Office\16.0\ClickToRun\PropertyBag\"
$itemc2r15="HKLM:\Software\Microsoft\Office\15.0\ClickToRun\PropertyBag\"
$item= "hklm:\Software\Microsoft\Office\ClickToRun\PropertyBag\"

#Running the Detection Process
If (!(Test-Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R"))
{
New-Item -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Force
}
#Check if Click to run is installed
$offc2r15 =isOfficeC2R_Installed -OffVer Office15
$offc2r16 =isOfficeC2R_Installed -OffVer Office16

$offc2r15
If ($offc2r15 -eq 'True' -or $offc2r16 -eq 'True')
{
LogWrite "Office C2R version is installed on this machine"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "OfficeC2R_Installed" -Value "TRUE" -PropertyType String -Force
}

Else
{
LogWrite "Office C2R 2013/2016 is not installed"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "OfficeC2R_Installed" -Value "FALSE" -PropertyType String -Force
}

#Verifying Office Version
if(test-path $itemc2r16)
{
$itemc2r16=get-itemproperty -path "HKLM:\Software\Microsoft\Office\16.0\ClickToRun\PropertyBag\" -Name version
$stringvaluec2r16=$itemc2r16.Version
#$reg16path = $stringvaluec2r16.Contains("16")
LogWrite "Office C2R version installed on this machine is $stringvaluec2r16"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "OfficeC2R_Version" -Value "$stringvaluec2r16" -PropertyType String -Force

}
if(test-path $itemc2r15)
{
$itemc2r15=get-itemproperty -path "HKLM:\Software\Microsoft\Office\15.0\ClickToRun\PropertyBag\" -Name version
$stringvaluec2r15=$itemc2r15.Version
#$reg15path = $stringvaluec2r15.Contains("15")
LogWrite "Office C2R version installed on this machine is $stringvaluec2r15"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "OfficeC2R_Version" -Value "$stringvaluec2r15" -PropertyType String -Force
}

# Verifiying Office C2R Architecture
$C2RArch = OfficeC2R-Arch

If ($C2RArch -eq '64bit')
{
LogWrite "Office C2R installed on this machine is 64-bit"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "OfficeC2R_Architecture" -Value "64bit" -PropertyType String -Force

}

If ($C2RArch -eq '32bit')
{
LogWrite "Office C2R installed on this machine is 32-bit"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "OfficeC2R_Architecture" -Value "32bit" -PropertyType String -Force

}

&amp;amp;amp;lt;#
#Stopping C2R Processes

Stop-Process -Name AppVShNotify -Force
Stop-Process -Name officeclicktorun -Force
Stop-Process -Name officeclicktorun -Force
Stop-Process -Name AppVShNotify -Force
#&amp;amp;amp;gt;
# Copying 64bit source media to C:\Windows\Software folder
If (!(Test-Path "C:\Windows\OFFICE\Software\Office_C2R_X64"))
{
New-Item -Path "C:\Windows\OFFICE\Software\Office_C2R_X64" -ItemType Directory -Force| Out-Null
}
Else
{
Remove-Item -Path C:\Windows\OFFICE\Software\Office_C2R_X64\* -Force -Recurse | Out-Null
}

# +----------------------------------------------------------------------------
# ********************************************************************************
# |
# | PLease MNAUALLY COPY the 64-bits "DATA" folder to get the latest version of 64-bit office installed
# | At the time when i was writing the script i had 15.0.5015.1000 version of office ---&gt; Nikhil
# |
# +----------------------------------------------------------------------------
# ********************************************************************************

Write-Host "Upgrading Office 365 Clicktorun.exe to latest version of 64bit of office"
Copy-Item -Path "$InstDir\*" -Destination "C:\Windows\OFFICE\Software\Office_C2R_X64" -Recurse -Force | Out-Null

#Verifying Office 2013 MSI versions (Sharepoint Designer,Visio &amp;amp;amp;amp; Project)
LogWrite "Verifying Office 2013 MSI versions (Sharepoint Designer,Visio &amp;amp;amp;amp; Project)"
$Visio2013 = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft Visio Professional 2013"} |Where-Object {$_.Displayversion -eq "15.0.4569.1506"}
$Project2013 = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft Project Professional 2013"} |Where-Object {$_.Displayversion -eq "15.0.4569.1506"}
$SPD2013 = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft SharePoint Designer 2013"} |Where-Object {$_.Displayversion -eq "15.0.4420.1017"}

#SPD2013 Check
If(!$SPD2013)
{

LogWrite "Microsoft SharePoint Designer 2013 is not installed so skipping the Uninstallation...."
$sharePointDesigner2013 = 'FALSE'
}

Else

{
$sharePointDesigner2013 = 'TRUE'
LogWrite "Microsoft SharePoint Designer 2013 is installed on this machine.So uninstalling it"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "Office2013SPDInstalled" -Value "True" -PropertyType String -Force
}

#Visio2013

If(!$Visio2013)
{
$MSFTVISIO2013 = 'FALSE'
LogWrite "Microsoft Visio 2013 is not installed so skipping the Uninstallation...."

}

Else

{
$MSFTVISIO2013 = 'TRUE'
LogWrite "Microsoft Visio 2013 is installed on this machine.So uninstalling it"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "Office2013VISIOInstalled" -Value "True" -PropertyType String -Force
}

#Project Check

If(!$Project2013)
{
$MSFTPROJ2013 = 'FALSE'
LogWrite "Microsoft Project 2013 is not installed so skipping the Uninstallation...."

}

Else

{
$MSFTPROJ2013 = 'TRUE'
LogWrite "Microsoft Project 2013 is installed on this machine.So uninstalling it"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "Office2013ProjectInstalled" -Value "True" -PropertyType String -Force
}

#OFFICE 365 Versions check
$VSD2013C2R = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft Visio Professional 2013 - en-us"}
$PROJ2013C2R = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft Project Professional 2013 - en-us"}

If ($PROJ2013C2R)
{
LogWrite "Project 2013 O365 version is installed on this machine"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "Office2013ProjectInstalled" -Value "True" -PropertyType String -Force
}

If ($VSD2013C2R)
{
LogWrite "Visio 2013 O365 version is installed on this machine"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "Office2013VISIOInstalled" -Value "True" -PropertyType String -Force
}
# Uninstalling C2R 32 bit
IF (($offc2r15 -eq 'True')-and ($C2RArch -eq '32bit'))
{
LogWrite "Office C2R 15 32 bit version is installed on the machine. So uninstalling it........"
#$UninstOffx86 = "$InstDir\15.0.4727.1002"
$Parameters = ' /Configure Uninstall.xml'
$Commandtorun = "Setup.exe"
LogWrite "$CommandToRun $Parameters"
LogWrite "Running Command: $CommandToRun $Parameters"
$process= Start-Process $CommandToRun $Parameters -PassThru -wait -workingdirectory $InstDir
$RetVal = $process.ExitCode
LogWrite $RetVal
If ($RetVal -eq '0')
{
Write-Host "Uninstall completed successfully"
LogWrite "Office C2R 32bit Uninstall completed sucessfully"
#===========================================================================================================================================================================#

}
If ($RetVal -eq '4')
{
Write-Host "User cancelled the installation" -ForegroundColor DarkRed
}
}
#Start-Sleep -s 30
Start-Sleep -s 10

If (($sharePointDesigner2013 -eq 'TRUE') -or ($MSFTVISIO2013 -eq 'TRUE') -or ($MSFTPROJ2013 -eq 'TRUE'))
{
Stop-Process -Name ONENOTE -Force
Stop-Process -Name ONENOTEM -Force
Stop-Process -Name OUTLOOK -Force
Stop-Process -Name MSACCESS -Force
Stop-Process -Name SPDESIGN -Force
Stop-Process -Name WINWORD -Force
Stop-Process -Name POWERPNT -Force
Stop-Process -Name MSPUB -Force
Stop-Process -Name VISIO -Force
Stop-Process -Name WINPROJ -Force

$Parameters = ' OffScrub_O15msi.vbs /ALL /Q /S /NOREBOOT /NoCancel'
$Commandtorun = "C:\Windows\System32\cscript.exe"
LogWrite "$CommandToRun $Parameters"
LogWrite "Running Command: $CommandToRun $Parameters"
$process= Start-Process $CommandToRun $Parameters -PassThru -wait -workingdirectory $InstDir
$ExtVal = $process.ExitCode
LogWrite $ExtVal
}

#Verifying Office 2010 MSI versions (Visio, Project &amp;amp;amp;amp; Access database engine )

$Visio2010 = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft Visio Premium 2010"} |Where-Object {$_.Displayversion -eq "14.0.6029.1000"}
$Project2010 = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft Project Premium 2010"} |Where-Object {$_.Displayversion -eq "14.0.6029.1000"}
$Ade2010 = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft Access database engine 2010 (English)"} #|Where-Object {$_.Displayversion -eq "14.0.4763.1000"}

#Project 2010 check
If(!$Project2010)
{

LogWrite "Microsoft Project 2010 is not installed so skipping the Uninstallation...."
$MSFTPROJ2010 = 'FALSE'
}

Else

{
LogWrite "Microsoft Project Premium 2010 is installed on this machine.So uninstalling it"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "Office2010ProjectInstalled" -Value "True" -PropertyType String -Force
$MSFTPROJ2010 = 'TRUE'
}

#Visio2010 Check

If(!$Visio2010)
{

LogWrite "Microsoft Visio 2010 is not installed so skipping the Uninstallation...."
$MSFTVISIO2010 = 'FALSE'
}

Else

{
LogWrite "Microsoft Visio Premium 2010 is installed on this machine.So uninstalling it"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "Office2010VISIOInstalled" -Value "True" -PropertyType String -Force
$MSFTVISIO2010 = 'TRUE'
}

If(!$Ade2010)
{

LogWrite "Access Database Engine 2010 is not installed so skipping the Uninstallation...."
$AccessDBA2010 = 'FALSE'
}

Else

{
LogWrite "Access Database Engine 2010 is installed on this machine.So uninstalling it"
$AccessDBA2010 = 'TRUE'
}

If (($MSFTPROJ2010 -eq 'TRUE') -or ($MSFTVISIO2010 -eq 'TRUE') -or ($AccessDBA2010 -eq 'TRUE'))
{
Stop-Process -Name ONENOTE -Force
Stop-Process -Name ONENOTEM -Force
Stop-Process -Name OUTLOOK -Force
Stop-Process -Name MSACCESS -Force
Stop-Process -Name SPDESIGN -Force
Stop-Process -Name WINWORD -Force
Stop-Process -Name POWERPNT -Force
Stop-Process -Name MSPUB -Force
Stop-Process -Name VISIO -Force
Stop-Process -Name WINPROJ -Force

$Parameters = ' OffScrub10.vbs ALL /Q /S /NOREBOOT /NoCancel /Log C:\Windows\Temp\OFFICE_InstallInstalls\Project2010_Uninstall'
$Commandtorun = "C:\Windows\System32\cscript.exe"
LogWrite "$CommandToRun $Parameters"
LogWrite "Running Command: $CommandToRun $Parameters"
$process= Start-Process $CommandToRun $Parameters -PassThru -wait -workingdirectory $InstDir
$ExtVal = $process.ExitCode
LogWrite $ExtVal
}

#Verifying Office 2007 MSI versions (Visio, Project &amp;amp;amp;amp; Access database engine )
$Project2007 = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft Office Project Professional 2007"}
$Ade2007 = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft Office Access database engine 2007 (English)"} #|Where-Object {$_.Displayversion -eq "14.0.4763.1000"}

#Project2007 Check
If(!$Project2007)
{

LogWrite "Microsoft Project 2007 is not installed so skipping the Uninstallation...."
$MSFTPROJ2007 = 'FALSE'
}

Else

{
$MSFTPROJ2007 = 'TRUE'
LogWrite "Microsoft Project Premium 2007 is installed on this machine.So uninstalling it"
New-ItemProperty -Path "HKLM:\SOFTWARE\OFFICE_Install\OFFICE_C2R" -Name "Office2007ProjectInstalled" -Value "True" -PropertyType String -Force
}

If(!$Ade2007)
{

LogWrite "Access Database Engine 2007 is not installed so skipping the Uninstallation...."
$AccessDBA2007 = 'FALSE'
}

Else

{
LogWrite "Access Database Engine 2007 is installed on this machine.So uninstalling it"
$AccessDBA2007 = 'TRUE'
}

If(($MSFTPROJ2007 -eq 'TRUE') -or ($AccessDBA2007 -eq 'TRUE'))
{

Stop-Process -Name ONENOTE -Force
Stop-Process -Name ONENOTEM -Force
Stop-Process -Name OUTLOOK -Force
Stop-Process -Name MSACCESS -Force
Stop-Process -Name SPDESIGN -Force
Stop-Process -Name WINWORD -Force
Stop-Process -Name POWERPNT -Force
Stop-Process -Name MSPUB -Force
Stop-Process -Name VISIO -Force
Stop-Process -Name WINPROJ -Force

$Parameters = ' Office2007remove.vbs ALL /Q /S /NOREBOOT /NoCancel /Log C:\Windows\Temp\OFFICE_InstallInstalls\Office2007_Uninstall'
$Commandtorun = "C:\Windows\System32\cscript.exe"
LogWrite "$CommandToRun $Parameters"
LogWrite "Running Command: $CommandToRun $Parameters"
$process= Start-Process $CommandToRun $Parameters -PassThru -wait -workingdirectory $InstDir
$ExtVal = $process.ExitCode
LogWrite $ExtVal

}

Stop-Process -Name ONENOTE -Force
Stop-Process -Name ONENOTEM -Force
Stop-Process -Name OUTLOOK -Force
Stop-Process -Name MSACCESS -Force
Stop-Process -Name SPDESIGN -Force
Stop-Process -Name WINWORD -Force
Stop-Process -Name POWERPNT -Force
Stop-Process -Name MSPUB -Force
Stop-Process -Name VISIO -Force
Stop-Process -Name WINPROJ -Force

$Parameters = ' Office2007remove.vbs ALL /Q /S /NOREBOOT /NoCancel /Log C:\Windows\Temp\OFFICE_InstallInstalls\Office2007_Uninstall'
$Commandtorun = "C:\Windows\System32\cscript.exe"
LogWrite "$CommandToRun $Parameters"
LogWrite "Running Command: $CommandToRun $Parameters"
$process= Start-Process $CommandToRun $Parameters -PassThru -wait -workingdirectory $InstDir
$ExtVal = $process.ExitCode
LogWrite $ExtVal

#Uninstalling Appv Versions of Office2007
$APPVO2007 = Get-Uninstall| Select-Object DisplayName, DisplayVersion | Where-Object {$_.DisplayName -eq "Microsoft-Office-2007-App-V"}
If ($APPVO2007)
{
Stop-service -name AppVClient -Force
LogWrite "Uninstalling Appv Versions of Office2007"
$Parameters = ' /x "{B1E28E83-ACEA-4B3D-9F42-B02CD5D8ECD3}" /qn'
$Commandtorun = "C:\Windows\System32\MSIEXEC.exe"
LogWrite "$CommandToRun $Parameters"
LogWrite "Running Command: $CommandToRun $Parameters"
$process= Start-Process $CommandToRun $Parameters -PassThru -wait -workingdirectory 'C:\Windows\OFFICE\Software\Office_C2R_X64'
$ExtVal = $process.ExitCode
LogWrite $ExtVal
}
}

#===========================================================================================================================================================================#

# | Removing the Tasks schedulers for Office |

#===========================================================================================================================================================================#

#Remove Office Updates AtLogon scheduled task if it exists
Unregister-ScheduledTask -TaskName "Office Updates AtLogon" -Confirm:$false
#Remove Office Updates Nightly scheduled task if it exists
Unregister-ScheduledTask -TaskName "Office Updates Nightly" -Confirm:$false

 


						

Logging function in powershell


Function LogWrite {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
$sLogMsg
)
PROCESS {
# Populate the variables to log

$sTime = (Get-Date -Format HH:mm:ss) + ".000+000"
$sDate = Get-Date -Format MM-dd-yyyy
$sTempMsg = "<![LOG[$sLogMsg]LOG]!><time=""$sTime"" date=""$sDate"" component=""$Component"" context="""" type="""" thread="""" file=""$Component"">"

# Create the component log entry

Write-Output $sTempMsg | Out-File -FilePath $logFile -Encoding "Default" -Append

}
} # End of Create-LogEntry function