Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the twentyseventeen domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/html/wp-includes/functions.php on line 6121
WinPE – SCCMOG – Deployment Blog

Windows 10 Inject Start Menu Layout Offline – MDT SCCM OSD Powershell

In this blog I will show you how to inject your Windows 10 start menu offline so that on first boot its already configured in your reference image or even your deployment task sequence whether that be MDT of ConfigMgr (SCCM).

GITHUB: Action-OSD_InjectStartMenu_Offline.ps1

Note: If you have links for icons pinned on  the taskbar and the software is not already installed it ill not break and they will show as the applications are installed 😉

Important: Make sure you have added the PowerShell component to your boot image. Click a link to find out how: MDT or SCCM

MDT Setup

  • First download the script and save it into you deployment share “Scripts” folder:
J:\<YOUR_DEPLOYMENT_SHARE>\Scripts\Action-OSD_InjectStartMenu_Offline.ps1
    • Your welcome to also download the DefaultStart.xml and or just rename your default start menu XML to “DefaultStart.xml” and add it also to the deployment share “Scripts” folder.
J:\<YOUR_DEPLOYMENT_SHARE>\Scripts\DefaultStart.xml
  • Then open up your chosen Task Sequence in MDT and just before the “Inject Drivers” step under the “Post Install Group” and a new “Run Commmand Line Step”.
  • Name it for example:  Inject Start Menu Offline
    Then use the following command line:
Powershell.exe -ExecutionPolicy Bypass -File "%SCRIPTROOT%\Action-OSD_InjectStartMenu_Offline.ps1"

Example:

Windows-10-Inject-Start-menu-offline
Windows-10-Inject-Start-menu-offline

SCCM Setup

  • For SCCM you must be using the MDT integration (if you’re not… Start now!), you can make it work without it but I will not cover that here.
  • Find your current MDT Toolkit Package that is associated with the Task Sequence you would like to configure power settings in.
  • Open the “Source” location of your toolkit package, then open the scripts folder.

  • Once inside the scripts folder copy the “Action-OSD_InjectStartMenu_Offline.ps1” into it.  And then your welcome to also download the DefaultStart.xml or just rename your default start menu XML to “DefaultStart.xml” and add it also to the ToolKit Package “Scripts” foldera also.
  • Now, update the Package in ConfigMgr.
  • Next we need to add the step to the task sequence. It must go after a “Use Toolkit Package” step and before your Driver injection step in the task sequence. (If you have a reboot remember to add another use “Toolkit package”.)

Create a new “Run Command Line Step” and the below command.

Powershell.exe -ExecutionPolicy Bypass -File "%DEPLOYROOT%\Action-OSD_InjectStartMenu_Offline.ps1"

And that is it. Your ConfigMgr or MDT Task sequence is now setup to inject the default start menu before the machine boots!

Anyway as always, script is provided as is and if you do mod it, there is a line to add your name.

Windows 10 Configure User Experience Offline – MDT SCCM OSD -VBScript

So currently I am working on an Government Education site comprising of just under 40 schools. There was a requirement to remove/hide Microsoft’s Edge browser from the image being rolled out to the users. The reasoning behind this is down to a monitoring tool used by the education department that does not support Edge and therefor policies would be broken…

Anyway I hunted around on our favourite resource for a solution that would not break the image entirely by removing one of it core features.

Eventually I found these 4 registry keys that did the trick:

KEY: HKEY_LOCAL_MACHINE\NewOS\Microsoft\Windows\CurrentVersion\Explorer
Name: DisableEdgeDesktopShortcutCreation 
Value: 1
KEY: HKEY_LOCAL_MACHINE\NewOS\Policies\Microsoft\MicrosoftEdge\Main
Name: PreventFirstRunPage
Value: 1
KEY: HKEY_LOCAL_MACHINE\NewOS\Policies\Microsoft\MicrosoftEdge\Main
Name: AllowPrelaunch 
Value: 0
KEY: HKEY_LOCAL_MACHINE\NewOS\Policies\Microsoft\MicrosoftEdge\TabPreloader\AllowTabPreloading
Name: AllowTabPreloading 
Value: 0

Next was to figure out how to inject these into my reference image before  it was laid onto the VM for automated customisation. So I remembered a great script by Johan Arwidmark I use all the time for turning off Appx package updates during a reference image capture task  sequence (can break sysprep if allowed).

Anyway after a bit of modification to load the Software registry hive offline instead this is what I came up with. There is also some commented out portions here that may come in handy:

Github: Config-Win10-Offline-UE.wsf

MDT Setup

  • First download the script and save it into you deployment share “Scripts” folder:
J:\<YOUR_DEPLOYMENT_SHARE>\Scripts\Config-Win10-Offline-UE.wsf
  • Then Open up your chosen Task Sequence in MDT and just before the “Inject Drivers” step under the “Post Install Group” and a new “Run Commmand Line Step”.
  • Name it for example:  Configure User Experience
    Then use the following command line:
cscript.exe "%SCRIPTROOT%\Config-Win10-Offline-UE.wsf"

Example:

Configure-User-Environment-Offline-VBscript-Example
Configure-User-Environment-Offline-VBscript-Example

SCCM Setup

  • For SCCM you must be using the MDT integration (if you’re not… Start now!), you can make it work without it but I will not cover that here.
  • Find your current MDT Toolkit Package that is associated with the Task Sequence you would like to configure power settings in.
  • Open the “Source” location of your toolkit package, then open the scripts folder.

  • Once inside the scripts folder copy the “Config-Win10-Offline-UE.wsf” into it. Now, update the Package in ConfigMgr.
  • Next we need to add the step to the task sequence. It must go after a “Use Toolkit Package” step and before your Driver injection step in the task sequence. (If you have a reboot remember to add another use “Toolkit package”.)

Create a new “Run Command Line Step” and add the below command.

cscript.exe "%deployroot%\scripts\Config-Win10-Offline-UE.wsf"

And that is it. Your ConfigMgr or MDT Task sequence is now setup to configure the user environment before the machine boots!

Anyway as always, script is provided as is and if you do mod it, there is a line to add your name.

PowerShell add DaRT Remote Control to SCCM Boot Image Early V2

Ok so I’m sure like a lot of people out there we all love those scripts that Johan Arwidmark, Mikael Nystrom, Peter Löfgren and all the other MVPs write that make our lives easier!

Any way Johan recently released an awesome PowerShell script to inject DaRT into a ConfigMgr boot image and configure remote control from the MDT Monitoring node using a  launching script written by Alexey Semibratov.
Adding DaRT to ConfigMgr Boot Images – And starting it earlier than early

The beauty of adding this to your boot image is the point at which you are then able to remote control a task sequence, you can literally remote control the machine being built before the DP password has been entered, allowing the ConfigMgr Admin(s) to easily troubleshoot an issue.

I want to make it clear that the original script was created by Johan and without his work I would not have come up with this. What I have done (having a spare Saturday) is tweak it a little to take parameters and configure it all. This means you do not have to open any files to change any information 🙂 I even update the XML for you, install Dart, the works!

Anyway head over to here to download the script: Add-DartToBootImageV2

The steps for configuration are as follows:

  • Create a folder to drop the Add-DartToBooImageV2 files into. E.g “E:\Setup\Scripts\Add-DartToBooImageV2” Note: no spaces please 🙂
Folder structure for Add-DarttobootimageV2
  • Copy all script files downloaded from above and your version of the MSDaRT100.MSI (DaRT 10 x64) installer into that folder as well.
  • Next head over to you MDT deployment share and grab the monitoring service address.
MDT Deployment Share Monitoring Host Address
  • Now head over to ConfigMgr and grab the Name of the boot image you would like to enable DaRT remote control on.
  • Once you have collected that information open a command prompt as Administrator on your site server.
  • Now navigate (cd) to E:\Setup\Scripts\Add-DartToBooImageV2
  • Ensure the drive you choose has enough space to mount the boot image as the script will create and clean up for you.
  • And run the script with the following command line:
.\Add-DartToBootImageV2.ps1 -EventServiceLocation http://your-cm-01.yourdomain.local:9800 -BootImageName 'MDT 8450 x64' -MountDrive J -SiteServer your-cm-01.yourdomain.local -SiteCode P01

Running the script:

Add-DartToBootImageV2.ps1 Running
Add-DartToBootImageV2.ps1 Running 2

Reaping the rewards:

PXE boot with DaRT 10 SCCM MDT

The script:

##################################################################################################################
#
#  Original Author: Johan Arwidmark  
#  Updated By: Richie Schuster - C5 Alliance - SCCMOG.com
#  Date:   28/07/2018
#          03/08/2018 - Changed Folder search to get volume and select on data drives only as found issue on VMware VMs
#                       Added default paths for installs MDT and Dart to speed up script for multiple Images.
#                       
#  Script: Add-DartToBootImageV2.ps1
#  Usage: Powershell.exe -ExecutionPolicy Bypass -File .\Add-DartToBootImageV2.ps1 -EventServiceLocation http://roary-cm-01.roary.local:9800 -BootImageName 'MDT 8450 x64' -MountDrive J -SiteServer ROARY-CM-01.ROARY.LOCAL -SiteCode ROR
#
##################################################################################################################

param(
    [parameter(Mandatory=$true, HelpMessage="Please enter the FQDN and PortNumber of the Server that host the MDT Monitoring Service. E.g http://roary-cm-01.roary.local:9800")]
    [ValidateNotNullOrEmpty()]
    [string]$EventServiceLocation,
    [parameter(Mandatory=$true, HelpMessage="Please enter the name of the bootimage you would like to inject DaRT into.")]
    [ValidateNotNullOrEmpty()]
    [string]$BootImageName,
    [parameter(Mandatory=$true, HelpMessage="Please select the Mount Drive i.e ")]
    [ValidateNotNullOrEmpty()]
    [string]$MountDrive,
    [parameter(Mandatory=$true, HelpMessage="Please enter the FQDN of your Site Server")]
    [ValidateNotNullOrEmpty()]
    [string]$SiteServer,
    [parameter(Mandatory=$true, HelpMessage="Please enter you Site Code.")]
    [ValidateNotNullOrEmpty()]
    [string]$SiteCode
)

# Check for elevation
Write-Host "Checking for elevation"

If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Warning "Oupps, you need to run this script from an elevated PowerShell prompt!`nPlease start the PowerShell prompt as an Administrator and re-run the script."
    Write-Warning "Aborting script..."
    Break
}

# Connect to ConfigMgr
if((Get-Module ConfigurationManager) -eq $null) {
    Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
}
if((Get-PSDrive -Name $SiteCode -PSProvider CMSite -ErrorAction SilentlyContinue) -eq $null) {
    New-PSDrive -Name $SiteCode -PSProvider CMSite -Root $SiteServer 
}
Set-Location "$($SiteCode):\" 

# Get Boot image from ConfigMgr
$BootImage = Get-CMBootImage -Name $BootImageName
$BootImagePath = $BootImage.ImagePath
$XMLPath = "$PSScriptRoot\Unattend.xml"
$EnableDart = "$PSScriptRoot\EnableDart.wsf"
$SampleFiles = "$PSScriptroot"
$MountPath = "$($MountDrive):\DartMount"
$MDTDefaultPath = "C:\Program Files\Microsoft Deployment Toolkit\Templates"
$MDTFolderName = "Microsoft Deployment Toolkit\Templates"
$REGUninstall = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
$DartDefaultPath = "C:\Program Files\Microsoft DaRT"
$DartDispName = 'Microsoft Dart 10'
$DartFolderName = "Microsoft DaRT"
$DartMSI = "$PSScriptroot\MSDaRT100.msi"

#Function to find folders
Function FindFolder($FolderName){
    #$Drives = Get-PSDrive -p FileSystem | Select-Object -ExpandProperty Name
    $Drives =  Get-Volume | Where-Object { ($_.FileSystemLabel -ne "System Reserved") -and ( $_.DriveType -like "Fixed") -and ( $_.FileSystem -like "NTFS")} | Select-Object -ExpandProperty DriveLetter | Sort-Object
    $InstallPath = $null
    :findfolder Foreach ($drive in $Drives) {
        If ($InstallPath -eq $null) {
            $Counter++
            Write-host "Searching drive $($drive):\ for folder: '$($FolderName)' Drive count is $($Counter) out of $($Drives.Count)" -ForegroundColor Yellow
            $InstallPath = Get-ChildItem -Recurse -Force "$($drive):\" -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $true) -and ( $_.FullName -like "*$FolderName") } | Select-Object -ExpandProperty FullName
        }
        Else {
                Write-Host "Found folder at: $($InstallPath)" -ForegroundColor Green
                return $InstallPath
                break findfolder
        }
    }
    #Write-Warning "Could not find the install Folder $Foldername exiting";break
    $InstallPath = "NotFound"
    return $InstallPath
}

# Check for PRE Reqs
Set-Location C:
if (!(Test-Path -Path "$XMLPath")) {Write-Warning "Could not find Unattend.xml path, check it is in script root and retry. aborting...";Break}
if (!(Test-Path -Path "$BootImagePath")) {Write-Warning "Could not find boot image, aborting...";Break}
if (!(Test-Path -Path "$DartMSI")) {Write-Warning "Could not DaRT MSI, Please place MSDaRT100.msi in script root folder, aborting...";Break}
if (!(Test-Path -Path "$MountPath")) {
    Write-Warning "Could not find mount path, Creating..."
    try {
        New-item -Path "$MountPath" -ItemType Directory -ErrorAction SilentlyContinue -Force
        Write-Host "Successfully Created Mount Path at:  $($MountPath)" -ForegroundColor Green
    }
    catch [System.Exception]{
        Write-Host "Failed to create Mount Path at:  $($MountPath) Error Message:  $($_.Exception.Message)";Break
    }
    }
#Check if dart is installed - If not install it.
$DaRT10 = Get-ItemProperty "$REGUninstall\*" | Where-Object DisplayName -Like $DartDispName
if($DaRT10.VersionMajor -eq “10”){
    Write-Host "Dart is installed searching for CAB file location"
    If (Test-Path -Path $DartDefaultPath){
        $DartInstallPath = $DartDefaultPath
    }
    Else {
        $DartInstallPath = FindFolder($DartFolderName)
    }
    $DartCab = $DartInstallPath + "\v10\Toolsx64.cab"
    if (Test-Path -Path "$DartCab"){
        Write-Host "Found DaRT x64 CAB at: $($DartCab)" -ForegroundColor Green
    } 
    else {
        Write-Warning "Could not find DaRT 10 Toolsx64.cab, Please remove older version of DaRT and retry. aborting...";
        Break
    }
}
else{
    Write-Warning "Could not find any DaRT version installed. Installing DaRT MSI in root of folder."
    $DartArgs = "/i $DartMSI /qb /norestart /L*v $env:windir\temp\MSDaRT100_Install.Log"
    $process = Start-Process -FilePath "msiexec.exe" -ArgumentList $DartArgs -Wait -NoNewWindow -PassThru
    If ($process.ExitCode -ne 0) {
        Write-Warning "Failed to install DaRT 10 please check the log at $($env:windir)\temp\MSDaRT100_Install.Log Install EXITCODE: $process.ExitCode";break
    }
    Else {
        Write-Host "DaRT 10 installed at: $ENV:ProgramFiles\$DartFolderName" -ForegroundColor Green

    }
    $DartCab = "$ENV:ProgramFiles\$DartFolderName" + "\v10\Toolsx64.cab"
    if (!(Test-Path -Path "$DartCab")) {Write-Warning "Could not find DaRT Toolsx64.cab, aborting...";Break}
}
If (Test-Path -Path $MDTDefaultPath){
    $MDTInstallationPath = $MDTDefaultPath
    }
Else {
 $MDTInstallationPath = FindFolder($MDTFolderName)
}
if (!(Test-Path -Path "$MDTInstallationPath" -ErrorAction SilentlyContinue)) {
    Write-Warning "Could not find MDT, please install MDT and re run script, aborting...";Break
    }
Else {
    Write-Host "Found MDT at: $($MDTInstallationPath)" -ForegroundColor Green 
}
if (!(Test-Path -Path "$EnableDart")) {Write-Warning "Could not find EnableDart.wsf, aborting...";Break}
if (!(Test-Path -Path "$XMLPath")) {Write-Warning "Could not find Unattend.xml, aborting...";Break}

Write-Host "##################################################################################" -ForegroundColor Green
Write-Host "All Pre Reqs found starting continuing..." -ForegroundColor Green
Write-Host "##################################################################################" -ForegroundColor Green

Write-Host "Updating Unattend.XML with new Event Service Location: $($EventServiceLocation)..." -ForegroundColor Green
#Update Unattend.xml with new event service location.
#Get the XML
[xml]$XML = (Get-Content $XMLPath)
#Set the base new command
$UpdateCMD = 'wscript.exe X:\Deploy\Scripts\EnableDart.wsf ','/EventService:',' /_SMSTSCurrentActionName:"Booted into WinPE"'
Write-Host "New CMD will be: $($UpdateCMD[0])$($UpdateCMD[1])$($EventServiceLocation)$($UpdateCMD[2])" -ForegroundColor Yellow
$CMD = $XML.unattend.settings.component.RunSynchronous.RunSynchronousCommand
$CMD.Path = $UpdateCMD[0] + $UpdateCMD[1] + $EventServiceLocation + $UpdateCMD[2]
try {
    $XML.Save($XMLPath)
    Write-Host "Successfully Saved new command line to XML: $($UpdateCMD[0])$($UpdateCMD[1])$($EventServiceLocation)$($UpdateCMD[2])"-ForegroundColor Green
}
Catch [System.Exception]{
    Write-Warning "Failed to Save new command line: '$($UpdateCMD[0])$($UpdateCMD[1])$($EventServiceLocation)$($UpdateCMD[2])' Error Message: '$($_.Exception.Message)' aborting..."
    Break;
}

# Mount the boot image
Mount-WindowsImage -ImagePath $BootImagePath -Index 1 -Path $MountPath  

# Add the needed files to the boot image
expand.exe $DartCab -F:* $MountPath
Remove-Item $MountPath\etfsboot.com -Force
Copy-Item $MDTInstallationPath\DartConfig8.dat $MountPath\Windows\System32\DartConfig.dat


if (!(Test-Path -Path "$MountPath\Deploy\Scripts")) {New-Item -ItemType directory $MountPath\Deploy\Scripts}
if (!(Test-Path -Path "$MountPath\Deploy\Scripts\x64")) {New-Item -ItemType directory $MountPath\Deploy\Scripts\x64}
Copy-Item $EnableDart $MountPath\Deploy\Scripts
Copy-Item $XMLPath $MountPath
Copy-Item "$MDTInstallationPath\Distribution\Scripts\ZTIDataAccess.vbs" $MountPath\Deploy\Scripts
Copy-Item "$MDTInstallationPath\Distribution\Scripts\ZTIUtility.vbs" $MountPath\Deploy\Scripts
Copy-Item "$MDTInstallationPath\Distribution\Scripts\ZTIGather.wsf" $MountPath\Deploy\Scripts
Copy-Item "$MDTInstallationPath\Distribution\Scripts\ZTIGather.xml" $MountPath\Deploy\Scripts
Copy-Item "$MDTInstallationPath\Distribution\Scripts\ztiRunCommandHidden.wsf" $MountPath\Deploy\Scripts
Copy-Item "$MDTInstallationPath\Distribution\Scripts\ZTIDiskUtility.vbs" $MountPath\Deploy\Scripts
Copy-Item "$MDTInstallationPath\Distribution\Tools\x64\Microsoft.BDD.Utility.dll" $MountPath\Deploy\Scripts\x64

# Save changes to the boot image
Dismount-WindowsImage -Path $MountPath -Save
Start-Sleep -Seconds 2
#Cleanup Mount folder
Remove-Item -Path $MountPath -ErrorAction SilentlyContinue -Force

# Update the boot image in ConfigMgr
Set-Location "$($SiteCode):\" 
$GetDistributionStatus = $BootImage | Get-CMDistributionStatus
$OriginalUpdateDate = $GetDistributionStatus.LastUpdateDate
Write-Host "Updating distribution points for the boot image..." -ForegroundColor Yellow
Write-Host "Last update date was: $OriginalUpdateDate" -ForegroundColor Yellow
$BootImage | Update-CMDistributionPoint

# Wait until distribution is done
Write-Output ""
Write-Output "Waiting for distribution status to update..."

Do { 
$GetDistributionStatus = $BootImage | Get-CMDistributionStatus
$NewUpdateDate = $GetDistributionStatus.LastUpdateDate
 if ($NewUpdateDate -gt $OriginalUpdateDate) {
  Write-Output ""
  Write-Host "Yay, boot image distribution status updated. New update date is: $NewUpdateDate" -ForegroundColor Green
  Write-Host "Happy Deployment!" -ForegroundColor Green
 } else {
  Write-Host "Boot image distribution status not yet updated, waiting 10 more seconds"  -ForegroundColor Cyan
 }
 Start-Sleep -Seconds 10
}
Until ($NewUpdateDate -gt $OriginalUpdateDate)
############################################################# Done :)

 

OSD Task Seqeunce High Performance – Native PowerCFG – VBS – MDT -SCCM

So like a lot of ConfigMgr Admins out there I strive to produce the fastest and most robust task sequences I can. This obviously led me down the path of configuring the Power Settings on the OS during deployment and capture phases.

The issue that I found is probably like many of you have and that is that it requires exporting the native “PowerCFG.exe” from each version of the OS that you would like to dynamically change the power configuration during Operating System Deployment.

So Jack and I were discussing why… in short… do we not use the “PowerCFG.exe” that is is already in the OS that we are configuring. Anyway after a little persuasion we came up with this little beauty of a script. This script will also create a CMTrace “Log”  using its name in the Log folder that is currently in use in the Task sequence.

Setup is simple:

MDT Setup
  • For MDT just place it into the Scripts folder of you “Deployment Share”.”
    "<YourDeploymentShareDrive>:\<DeploymentShareRoot>\Scripts\Set-PowerCFG.wsf"
  • You can then call this during any stage of you Reference image capture i.e. WinPE or full OS phase to set the power cfg with these below Command Lines:
    "%ScriptRoot%\Set-PowerCFG.wsf" /High
    "%ScriptRoot%\Set-PowerCFG.wsf" /Bal
SCCM Setup
  • For SCCM you must be using the MDT integration (if you’re not… Start now!), you can make it work without it but I will not cover that here.
  • Find your current MDT Toolkit Package that is associated with the Task Sequence you would like to configure power settings in.
  • Open the “Source” location of your toolkit package, then open the scripts folder.

  • Once inside the scripts folder copy the “Set-PowerCFG.wsf” into it.

    • Now, update the Package in ConfigMgr.
    • Next we need to add the step to the task sequence. It must go after the “Use Toolkit Package” step in the task sequence. (If you have a reboot and remember to add another use “Toolkit package”.)
    • Create a new “Run Command Line Step” and add one of the below commands.
cscript.exe "%deployroot%\scripts\Set-PowerCFG.wsf" /High
cscript.exe "%deployroot%\scripts\Set-PowerCFG.wsf" /Bal

And that is it. Your Task sequence will now set the Power Configuration Profile using the current OS’s native “Powercfg.exe”

Anyway as always, script is provided as is and if you do mod it, there is a line to add your name.

The Script:

<job id="Set-PowerCFG">
<script language="VBScript" src="ZTIUtility.vbs"/>
<script language="VBScript">
 
' //***************************************************************************
' // ***** Script Header *****
' //
' // Solution: Solution Accelerator for Microsoft Deployment
' // File: Set-PowerCFG.wsf
' // Requirements: ZTIUtility.vbs Must be located in the same folder id running from ConfigMGR.
' // Author: SCCMOG Richie Schuster - SCCMOG.com
' // Moddedby: YOURNAMEHERE
' // Date: 21/03/2018
' // Purpose:  Script sets power profile during OS deployment - Can be run in WinPE or full OS.
' //
' // Usage: cscript Set-PowerConfig.wsf [/High] - Sets high performance | [/Bal] - Sets balanced performance. [/debug:true] 
' //
' // Customer Build Version: 1.0.0
' // Customer Script Version: 1.0.0
' // Customer History:
' //
' // ***** End Header *****
' //***************************************************************************
 
'//----------------------------------------------------------------------------
'//
'// Global constant and variable declarations
'//
'//----------------------------------------------------------------------------
 
'Option Explicit
Dim strPwrBalanced	: strPwrBalanced	= "381b4222-f694-41f0-9685-ff5bb260df2e"
Dim strPwrHighPerf	: strPwrHighPerf	= "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"
Dim strPwrCFGexe	: strPwrCFGexe		= "powercfg.exe"
Dim strPwrCFGswitch : strPwrCFGswitch	= " /S "
Dim strPwrCFGFolder : strPwrCFGFolder	= "PowerCFG"
Dim strWmessage		: strWmessage		= "Please enter one or more arguments 'E.G : /High for High Performance Profile' or '/Bal for Balanced Profile'"
Dim strWindir		: strWindir			= oShell.ExpandEnvironmentStrings("%Windir%")
Dim strSysWow64		: strSysWow64		= "SysWOW64"
Dim strSystem32		: strSystem32		= "System32"

Dim  PowerCFG, strPwrProfile, strPwrProfileLog, ostrCMD, iRetVal
 
'//----------------------------------------------------------------------------
'// End declarations
'//----------------------------------------------------------------------------

'//----------------------------------------------------------------------------
'// Main routine
'//----------------------------------------------------------------------------
'Begin
oLogging.CreateEntry "Beginning Set-PowerCFG 1.0.0", LogTypeInfo
oLogging.CreateEntry "Active Log Path: " & oUtility.LogPath, LogTypeInfo

'Take Script Args
oLogging.CreateEntry "Getting set Arguments...", LogTypeInfo
If Not WScript.Arguments.Count >= 1 Then
	oLogging.ReportFailure strWmessage, iError
End If 
If WScript.Arguments.Named.Exists("High") Then 
	strPwrProfile = strPwrHighPerf
	strPwrProfileLog = "High"
	oLogging.CreateEntry "Power Profile requested to be set: " & strPwrProfileLog, LogTypeInfo
ElseIf WScript.Arguments.Named.Exists("Bal") Then 
	strPwrProfile = strPwrBalanced
	strPwrProfileLog = "Balanced"
	oLogging.CreateEntry "Power Profile requested to be set: " & strPwrProfileLog, LogTypeInfo
Else
	oLogging.ReportFailure strWmessage, iError
End If

'OS Info for Log
oLogging.CreateEntry "Getting information on Operating System", LogTypeInfo
oLogging.CreateEntry "OS Name: " & oEnvironment.Item("OSVERSION"), LogTypeInfo
oLogging.CreateEntry "OS Version: " & oEnvironment.Item("OSCURRENTVERSION"), LogTypeInfo
oLogging.CreateEntry "OS Architecture: " & oEnvironment.Item("Architecture"), LogTypeInfo

'Get OS Arch and set folder to run powerCFG from.
If oEnvironment.Item("Architecture") = "X86" Or oEnvironment.Item("_SMSTSInWinPE") = "true" Or oEnvironment.Item("OSVERSION") = "WinPE" Then
	strPwrCFGFolder = strSystem32
	oLogging.CreateEntry "Using PowerCFG.exe from: " & strPwrCFGFolder & " Folder.", LogTypeInfo
Elseif oEnvironment.Item("Architecture") = "X64" Then
	strPwrCFGFolder = strSysWow64
	oLogging.CreateEntry "Using PowerCFG.exe from: " & strPwrCFGFolder & " Folder.", LogTypeInfo
Else
	oLogging.ReportFailure "Machine Architecture not supported.", iError
End If

'Setting PowerCFG Location
strCMD = strWindir &  "\" & strPwrCFGFolder & "\" & strPwrCFGexe

'Logging Command
oLogging.CreateEntry "PowerCFG Location set to: " & strCMD, LogTypeInfo
oLogging.CreateEntry "Testing Location Available..." & strCMD, LogTypeInfo
iRetVal = oFso.FileExists(strPath)

If iRetVal = Success Then
	oLogging.CreateEntry "Found PowerCFG.exe at Location: " & strCMD, LogTypeInfo
	strCMD =  Chr(34) & strCMD &  Chr(34)
	oLogging.CreateEntry "Building Command to be run", LogTypeInfo
	strCMD = strCMD & strPwrCFGswitch & strPwrProfile
	oLogging.CreateEntry "Final Command to be run: " & strCMD, LogTypeInfo
	'Run PowerCFG
	iRetVal = oUtility.RunWithHeartbeat(strCMD)
	If iRetVal = Success Then
		oLogging.CreateEntry "Successfully set " & strPwrProfileLog & " Performance profile.", LogTypeInfo
		oLogging.CreateEntry "Set-PowerCFG 1.0.0 Complete...", LogTypeInfo
	Else
		oLogging.ReportFailure "Failed to set " & strPwrProfileLog & " Performance profile.", iError
	End If
Else
	oLogging.ReportFailure "Failed to find path: " & strCMD, iError
End If

	</script>
</job>

Cheers,

SCCMOG

Copyright 2016 SCCMOG | All Rights Reserved