Pages

Wednesday, 23 July 2025

test


   
   $reboot = Get-PendingReboot
Write-Log -Message "Checking for pending reboot status..."

if ($reboot.IsSystemRebootPending -or
    $reboot.IsCBServicingRebootPending -or
    $reboot.IsWindowsUpdateRebootPending -or
    $reboot.IsSCCMClientRebootPending) {

    # Launch background script to enforce 5 PM restart
    $helperScript = Join-Path -Path $PSScriptRoot -ChildPath "ForceRestartAt5PM.ps1"
    Start-Process -FilePath "powershell.exe" -ArgumentList "-ExecutionPolicy Bypass -NoProfile -WindowStyle Hidden -File `"$helperScript`""
    Write-Log -Message "Launched background script to enforce 5 PM forced restart."
     

    Write-Log -Message "Pending reboot detected. Starting scheduled prompts..."

    $currentTime = Get-Date
    $todayDate = [datetime]::Today
    $schedule = @(
        $todayDate.AddHours(12),   # 12:00 PM
        $todayDate.AddHours(14),   # 2:00 PM
        $todayDate.AddHours(16)    # 4:00 PM
    )

    # Add 15-minute intervals from 4:00 PM to 5:00 PM
    for ($i = 0; $i -le 4; $i++) {
        $schedule += $todayDate.AddHours(16).AddMinutes($i * 15)
    }

    $deferralCount = 0

    foreach ($promptTime in $schedule) {
        $now = Get-Date
        $waitTime = ($promptTime - $now).TotalSeconds
        Write-Log -Message "Next scheduled prompt at $($promptTime.ToString("hh:mm tt")). Current time: $($now.ToString("hh:mm tt"))."

        if ($waitTime -gt 0) {
            Write-Log -Message "Sleeping for $waitTime seconds until next prompt..."
            Start-Sleep -Seconds $waitTime
            Write-Log -Message "Woke up from sleep. Proceeding with prompt..."
        } else {
            Write-Log -Message "Scheduled time $($promptTime.ToString("hh:mm tt")) already passed. Skipping..."
            continue
        }

        if ($promptTime -eq $todayDate.AddHours(17)) {
            Write-Log -Message "Final scheduled time reached (5:00 PM). Initiating forced restart."
            Restart-Computer -Force
            break
        }

        $deferralCount++
        $message = @"
Your machine requires a reboot which will take place at 5PM. You will receive an additional reminder at 4PM and additional reminders every 15-minutes thereafter. Your machine will reboot automatically at 5PM if you do not initiate the reboot prior to that. Please save your work and click 'RestartNow' to reboot immediately or 'RestartLater' to defer.
"@

        Write-Log -Message "Displaying prompt #$deferralCount to user."
        $proceed = Show-InstallationPrompt -Title 'Scheduled Restart' -Message $message -ButtonRightText 'RestartNow' -ButtonLeftText 'RestartLater'
        Write-Log -Message "User selected '$proceed' during deferral attempt #$deferralCount."

        if ($proceed -eq 'RestartNow') {
            Write-Log -Message "User chose to restart now. Initiating reboot..."
            Restart-Computer -Force
            break
        } else {
            Write-Log -Message "User deferred the restart. Continuing to next scheduled prompt..."
        }
    }
     # Final check: If reboot is still pending and current time is past 5 PM
    $finalCheckTime = Get-Date
    if ($finalCheckTime -gt $todayDate.AddHours(17)) {
        Write-Log -Message "Current time is past 5 PM. Checking if reboot is still pending..."

        # Re-check reboot status in case it changed during the day
        $reboot = Get-PendingReboot
        if ($reboot.IsSystemRebootPending -or
            $reboot.IsCBServicingRebootPending -or
            $reboot.IsWindowsUpdateRebootPending -or
            $reboot.IsSCCMClientRebootPending) {

            Write-Log -Message "Reboot still pending after 5 PM. Initiating forced restart..."
            Restart-Computer -Force
        } else {
            Write-Log -Message "Reboot no longer pending after 5 PM. No action needed."
        }
    }  
}
else {
    Write-Log -Message "No pending reboot was detected on this device; skipping restart process."
}

Monday, 24 June 2024

User based detection

function getloggedindetails() {
    ##Find logged in username
    $user = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" |
      ForEach-Object { $_.GetOwner() } |
      Select-Object -Unique -Expand User
   
        $path= "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*"
        $sid = (Get-ItemProperty -Path $path | Where-Object { $_.ProfileImagePath -like "*$user" }).PSChildName

    $return = $sid, $user
   
    return $return
    }
    $loggedinuser = getloggedindetails
    $username = $loggedinuser[1]
   $File = "C:\users\$username\AppData\Local\Microsoft\Teams.jpg"
   if (Test-Path $File) {
    write-output "Teams Update detected, exiting"
    exit 0
    }
   else {
    exit 1
    }



    #####Registry
        $loggedinuser = getloggedindetails
        ##Set key

        $sid = $loggedinuser[0]
        $Path = "Registry::HKU\$sid\SOFTWARE\7-Zip"
        $Name = "Path"
        $Type = "STRING"
        $Value = "C:\Program Files\7-Zip\"

        Try {
            $Registry = Get-ItemProperty -Path $Path -Name $Name -ErrorAction Stop | Select-Object -ExpandProperty $Name
            If ($Registry -eq $Value){
                Write-Output "Detected"
               Exit 0
            }
            Exit 1
        }
        Catch {
            Exit 1
                write-host "not detected"
            write-host $path
        }

Monday, 17 June 2024

User registry through PS

 New-PSDrive HKU Registry HKEY_USERS | Out-Null

$user = Get-WmiObject -Class Win32_ComputerSystem | Select-Object -ExpandProperty Username
$sid = (New-Object System.Security.Principal.NTAccount($user)).Translate([System.Security.Principal.SecurityIdentifier]).Value
$key = "HKU:\$sid\Software\Test"
$reg = Get-Item -Path $key -ErrorAction SilentlyContinue

if (-not $reg) {
    Write-Host "Registry key didn't exist, creating it now"
    New-Item -Path "HKU:\$sid\Software" -Name "Test" -Force | Out-Null
}

if (-not $reg) {
    Write-Host "Registry key didn't exist, creating it now"
    New-ItemProperty -Path "HKU:\$sid\Software\Test" -Name "Testing" -Value "working" -PropertyType String | Out-Null
} else {
    Write-Host "Registry key changed to 1"
    Set-ItemProperty -Path "HKU:\$sid\Software\Test" -Name "Testing" -Value "working" | Out-Null
}

Sunday, 14 January 2024

Intune win32 app Create,Upload and deployment 1.0

 


#==================================================================================================================
#Dont change anything until new version of module released
# Install IntuneWin32App module from PowerShellGallery
# - Required modules:
# -- MSAL.PS (installed automatically)
$moduleName = "IntuneWin32App"
$moduleVersion = "1.4.3"  # Replace this with the version you want
$installedModule = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue

if (!$installedModule) {
    Write-Host "Installing $moduleName module..."
    Install-Module -Name $moduleName -RequiredVersion $moduleVersion -Force -Confirm:$false
    Write-Host "$moduleName module installed successfully."
} elseif ($installedModule.Version -lt $moduleVersion) {
    Write-Host "Updating $moduleName module to version $moduleVersion..."
    Update-Module -Name $moduleName -RequiredVersion $moduleVersion -Force
    Write-Host "$moduleName module updated successfully to version $moduleVersion."
} else {
    Write-Host "$moduleName module already installed and up-to-date."
}
Get-Command -Module "IntuneWin32App"
#==================================================================================================================
#.Intunewinfile will create Automatically if we give source location, Inatsll command and output folder

# Package MSI as .intunewin file
$SourceFolder = "C:\Temp\Notepad++ org\Notepad++\7.89\SourceFile"
$SetupFile = "Deploy-Application.exe"
$OutputFolder = "C:\Temp\Notepad++ org\Notepad++\7.89\IntuneFile"
$IntuneWinAppUtilPath = "C:\Temp\IntuneWinAppUtil.exe"

# Check if IntuneWinAppUtil.exe exists
if (Test-Path $IntuneWinAppUtilPath -PathType Leaf) {
    # Create the IntuneWin package
    & $IntuneWinAppUtilPath -c $SourceFolder -s $SetupFile -o $OutputFolder -q
    Write-Host "IntuneWin package created successfully."
} else {
    Write-Host "Error: IntuneWinAppUtil.exe not found at $IntuneWinAppUtilPath."
}
#New-IntuneWin32AppPackage -SourceFolder $SourceFolder -SetupFile $SetupFile -OutputFolder $OutputFolder -Verbose

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

#This function will get the App Information automatically from the folder
function Get-AppInfoFromFolder {
    param (
        [string]$IntuneFile
    )

    if ($IntuneFile -match '\\([^\\]+)\\([^\\]+)\\(\d+\.\d+)[\\]IntuneFile\\Deploy-Application\.intunewin') {
        $PublisherName = $matches[1]
         $appName = $matches[2]
        $appVersion = $matches[3]
        # Use the folder name as the application name
        return [PSCustomObject]@{
            PublisherName = $PublisherName
            ApplicationName = $appName
            Version = $appVersion
        }
    } else {
        return $null
    }
}

# Explore the module


Connect-MSIntuneGraph -TenantID "pavantechie.onmicrosoft.com" -Verbose

############################################################################
#$Category are as per my tennent Test Applications,Pavan test,Other Apps,Books & Reference,Data Management,Productivity,Business,Development & Design,Photos & Media,Collaboration & Social,Computer Management
####################################################
# Sample Win32 Application
####################################################
# Please create the folder name as below
# "\\networkshre\**\**\VendorName\ApplicationName\AppVersion\IntuneFile\Deploy-Application.intunewin"
$IntuneFile = Get-ChildItem -Path $OutputFolder -Filter "*.intunewin" | Select-Object -ExpandProperty FullName
#$IntuneFile = "C:\Temp\Notepad++ org\Notepad++\7.89\IntuneFile\Deploy-Application.intunewin"
$Category = "Development & Design"
$owner = "Pavan Kalyan"  #Change as per your requirement
$url = "https://notepad-plus-plus.org/downloads/"
$installcommandline = "Deploy-Application.exe"  #Change as per your Command Line
$uninstallcommandline = "Deploy-Application.exe -Deploymenttype Uninstall" #Change as per your Command Line
$ImageFile = "C:\Temp\Notepad++ org\Notepad++\7.89\Icon\Notepad_plus_plus.png"  ## Change as per your logo location
$DetectionScriptFile = "C:\Temp\Notepad++ org\Notepad++\7.89\DetectionRule\DetectionRule.ps1"  # Change your detection script location
$RequirementRule = New-IntuneWin32AppRequirementRule -Architecture x64 -MinimumSupportedWindowsRelease W10_20H2  # CHange as per your requirement
$GroupID = "682d3c05-0247-4ab4-be52-f523cfeb5f3e" #Please put ObjectID of the group
#####################################################################



$appInfo = Get-AppInfoFromFolder -IntuneFile $IntuneFile

$displayName = $($appInfo.ApplicationName)
$publisherName = $($appInfo.PublisherName)
$appversion = $($appInfo.Version)
$appname = "${publisherName}_${displayName}_${appversion}"
$Description = "Latest version of '$appname' is available and ready for deploy"

$Icon = New-IntuneWin32AppIcon -FilePath $ImageFile

# Create PowerShell script detection rule

$DetectionRule = New-IntuneWin32AppDetectionRuleScript -ScriptFile $DetectionScriptFile -EnforceSignatureCheck $false -RunAs32Bit $false

Add-IntuneWin32app -FilePath "$IntuneFile" -DisplayName "$appname" -Description "$Description" -Publisher "$publisherName" -AppVersion "$appversion" -Developer "$publisherName" -Owner "$owner" -Notes "Not Available" -InformationURL "$url" -PrivacyURL "$url" -InstallCommandLine "$installcommandline" -UninstallCommandLine "$uninstallcommandline" -InstallExperience "system" -RestartBehavior "suppress" -MaximumInstallationTimeInMinutes "60" -DetectionRule $DetectionRule -RequirementRule $RequirementRule -Icon $icon -CategoryName "$Category" -Verbose


# Get a specific Win32 app by it's display name
$Win32App = Get-IntuneWin32App -DisplayName "$appname" -Verbose

# Add an include assignment for a specific Azure AD group
Add-IntuneWin32AppAssignmentGroup -Include -ID $Win32App.id -GroupID "$GroupID" -Intent "available" -Notification "showAll" -Verbose

Friday, 12 January 2024

PowerShell script to Auto upgrade the applications through winget

 $apps = @(

    "7zip.7zip",
    "Notepad++.Notepad++",
    "Google.Chrome",
    "WiresharkFoundation.Wireshark",
    "VideoLAN.VLC",
    "PuTTY.PuTTY",
    "Microsoft.PowerToys",
    "Zoom.Zoom",
    "Apple.iTunes",
    "Autodesk.AutodeskAccess"
)
$logPath = "C:\Windows\Logs\Software\WingetList"  # Log files folder
$logFile = Join-Path $logPath "Updates.txt"    ## Upgrade required applications will be stored here
$str_LogFile = Join-Path $logPath "WInget_Install.log"  ##This is for Winget application Install

# Ensure the log directory exists
if (!(Test-Path $logPath)) {
    New-Item -Path $logPath -ItemType Directory
}
If (test-path $logFile){
Remove-Item $logFile -Force
}

    #Check Winget Install
    Write-Host "Checking if Winget is installed" -ForegroundColor Yellow
    $TestWinget = Get-AppxProvisionedPackage -Online | Where-Object {$_.DisplayName -eq "Microsoft.DesktopAppInstaller"}
    If ([Version]$TestWinGet. Version -gt "2022.506.16.0")
    {
        Write-Host "WinGet is Installed" -ForegroundColor Green

  #  Add-Content $str_LogFile "WinGet is Installed"
    }Else
        {

        #temp folder
        $InstallerFolder = $(Join-Path $env:ProgramData WIngetInstall)
        if (!(Test-Path $InstallerFolder))
        {
        New-Item -Path $InstallerFolder -ItemType Directory -Force -Confirm:$false
        }

        #Download WinGet MSIXBundle

        Add-Content $str_LogFile "Not installed. Downloading WinGet..."
        Write-Host "Not installed. Downloading WinGet..."
        $WinGetURL = "https://aka.ms/getwinget"
        (New-Object System.Net.WebClient).DownloadFile($WinGetURL, "$InstallerFolder\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle")
        #Install WinGet MSIXBundle
        Try     {
             Add-Content $str_LogFile "Installing MSIXBundle for App Installer..."
           
            Add-AppxProvisionedPackage -Online -PackagePath "$InstallerFolder\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -SkipLicense
            Write-Host "Installed MSIXBundle for App Installer" -ForegroundColor Green
              Add-Content $str_LogFile "Installed MSIXBundle for App Installer"
            }
        Catch {
            Write-Host "Failed to install MSIXBundle for App Installer..." -ForegroundColor Red

             Add-Content $str_LogFile "Failed to install MSIXBundle for App Installer..."
            }
   
        Start-Sleep -Seconds 30
       
        #Remove WinGet MSIXBundle
        Remove-Item -Path "$InstallerFolder\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -Force -ErrorAction Continue
        }



$ResolveWingetPath = Resolve-Path "C:\Program Files\WindowsApps\Microsoft.DesktopAppInstaller_*_x64__8wekyb3d8bbwe"

if ($ResolveWingetPath) {
    $WingetPath = $ResolveWingetPath[-1].Path

    # Set location to the resolved Winget path
    Set-Location $WingetPath

    $appsToUpdate = @()

    foreach ($app in $apps) {
        $lines = .\winget.exe list --Id $app
        if ($lines -match '\bVersion\s+Available\b') {
            $appsToUpdate += $app
        }
    }

    if ($appsToUpdate.Count -gt 0) {
        # Log the apps with available updates to the file
        $appsToUpdate | Out-File -Append -FilePath $logFile

        Write-Host "Updates available for the following apps:"
        $appsToUpdate | ForEach-Object { Write-Host "- $_" }
        exit 1

    } else {
        Write-Host "No updates available for the specified apps."

        exit 0
    }
} else {
    Write-Error "Winget path not resolved. Ensure that the path is correct and the application is installed."
}

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


Remediation Script :


#####################################################################################################################################
##Constants
$logPath = "C:\Windows\Logs\Software\WingetLogs"
$input = "C:\Windows\Logs\Software\WingetList\Updates.txt"  # App install list input file
$logFile = Join-Path $logPath "wingetLog_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"

#####################################################################################################################################
$apps = get-content $input  #We are getting the apps from the Updates.txt file


foreach ($app in $apps) {
    # Check if the application is Notepad++ and kill its process if it's running
    if ($app -eq 'Notepad++.Notepad++') {
        $notepadProcesses = Get-Process -Name 'notepad++' -ErrorAction SilentlyContinue
        if ($notepadProcesses) {
            Write-Host "Killing Notepad++ processes..."
            Stop-Process -Name 'notepad++' -Force
        }
    }

    }

# Ensure the log directory exists
if (!(Test-Path $logPath)) {
    New-Item -Path $logPath -ItemType Directory
   
}

# Cleanup old log files (older than a week)
$oldLogs = Get-ChildItem -Path $logPath -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) }
foreach ($oldLog in $oldLogs) {
    Remove-Item $oldLog.FullName -Force
}

$ResolveWingetPath = Resolve-Path "C:\Program Files\WindowsApps\Microsoft.DesktopAppInstaller_*_x64__8wekyb3d8bbwe"

if ($ResolveWingetPath) {
    $WingetPath = $ResolveWingetPath[-1].Path

    # Set location to the resolved Winget path
    Set-Location $WingetPath

    foreach ($app in $apps) {
        $lines = .\winget.exe list --Id $app
        if ($lines -match '\bVersion\s+Available\b') {
            $verInstalled, $verAvailable = (-split $lines[-1])[-3,-2]
            $upgradeCommand = ".\winget.exe upgrade --exact --id $app --silent --accept-package-agreements --accept-source-agreements --scope machine"

            $logEntry = [PSCustomObject]@{
                Time = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
                Name = $app
                InstalledVersion = [version]$verInstalled
                AvailableVersion = [version]$verAvailable
                UpgradeCommand = $upgradeCommand
            }

            # Log the version information to a file
            $logEntry | Out-File -Append -FilePath $logFile

            # Output log entry to console
            $logEntry | Format-Table -AutoSize

            # Run the upgrade command
            Invoke-Expression $upgradeCommand
        }
        elseif ($lines -match '\bVersion\b'){
         $verInstalled = (-split $lines[-1])[-2]

            $noUpgradeInfo = "Latest version of $app $verInstalled already installed on the machine."
            Write-Verbose -Verbose $noUpgradeInfo

            # Log the information about no available upgrade to a file
            $noUpgradeInfo | Out-File -Append -FilePath $logFile
        }
    }

    Write-Host "Log file created: $logFile"
} else {
    Write-Error "Winget path not resolved. Ensure that the path is correct and the application is installed."
}

Sunday, 19 November 2023

MSIX Codesigning Certificate

 $pass = ConvertTo-SecureString -String "12345" -Force -AsPlainText

$thumbprint = (New-SelfSignedCertificate -Type Custom -Subject "CN=Microsoft Corporation" -KeyUsage DigitalSignature -FriendlyName “VLC Applicaton Certificate" -CertStoreLocation "Cert:\CurrentUser\My" -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3", "2.5.29.19={text}")).Thumbprint

Export-PfxCertificate -Cert Cert:\CurrentUser\My\$thumbprint -FilePath "c:\temp\VLCmediaplayer.pfx" -Password $pass

Import-PfxCertificate -CertStoreLocation Cert:\LocalMachine\Root -FilePath "c:\temp\VLCmediaplayer.pfx" -Password $pass

Monday, 5 June 2023

Import TASK scheduler from xml file

 $taskname = "Remove MSTeams (Public version)"

$taskxmlpath = "Path of the xml file"

$taskusername = "SYSTEM"

$taskexists = Get-ScheduledTask -TaskName $taskname -ErrorAction SilentlyContinue

If ($taskexists.TaskName -eq "$taskname") {

Write-host "$taskname -already exists"

}

Else {


Register-ScheduledTask -xml (Get-Content "$taskxmlpath" | Out-String) -TaskName "$taskname" -User $taskusername -Force


write-host "$tasname -registered"

}


PASADT to create form restart requirement

 $proceed = 'RestartLater'

$noClickCounter = 0


while ($noClickCounter -lt 3) {

$noClickCounter++


$proceed = Show-InstallationPrompt -Title 'Restart Prompt' -Message "OHS Application Installation Completed. Click 'RestartNow' To Reboot the Machine.Click 'RestartLater' to Snooze the Restart for 1 hour. Deferral $noClickCounter" -ButtonRightText 'Restartnow' -ButtonLeftText 'RestartLater'


if ($proceed -eq 'RestartNow') {

Restart-Computer -Force

break

}


if ($noClickCounter -eq 3) {

$proceed = Show-InstallationPrompt -Title 'Restart Prompt' -Message 'OHS Application Installation Completed. Maximum Restart Diferrals Completed.Restart your Machine Now' -ButtonMiddleText 'Restart'

 Restart-Computer -Force

}

else {

Sleep -Seconds 3600

}

}

Thursday, 25 May 2023

PSADT to create Form sample

    $proceed = 'No'

   $noClickCounter = 0


    while ($proceed -ne 'Yes') {

    $proceed = Show-DialogBox -Title 'Installation Notice' -Text 'Application is Installed, would you like to restart the machine?' -Buttons $([System.Windows.Forms.MessageBoxButtons]::YesNo) -DefaultButton 'First' -Icon 'Exclamation' -Topmost $true


    if ($proceed -eq 'No') {

        $noClickCounter++


        if ($noClickCounter -eq 3) {

            $proceed = Show-DialogBox -Title 'Installation Notice' -Text 'Application is Installed, would you like to restart the machine?' -Buttons $([System.Windows.Forms.MessageBoxButtons]::OK) -DefaultButton 'First' -Icon 'Exclamation' -Topmost $true

        Restart-Computer -Force

        }

        else {

            Sleep -Seconds 30

        }

    }

    elseif ($proceed -eq 'Yes') {

        Restart-Computer -Force

    }

}


Tuesday, 7 March 2023

Wallpaer PS script

function Set-Wallpaper {
    param (

        [string]$Path,

        [ValidateSet('Tile', 'Center', 'Stretch', 'Fill', 'Fit', 'Span')]

        [string]$Style = 'Fill'

    )
    begin {
        try {
            Add-Type @"
                using System;
                using System.Runtime.InteropServices;
                using Microsoft.Win32;
                namespace Wallpaper
                {  public enum Style : int
                    {  Tile, Center, Stretch, Fill, Fit, Span, NoChange

                    }
                    public class Setter

                    {
                        public const int SetDesktopWallpaper = 20;

                        public const int UpdateIniFile = 0x01;

                        public const int SendWinIniChange = 0x02;

                        [DllImport( "user32.dll", SetLastError = true, CharSet = CharSet.Auto )]

                        private static extern int SystemParametersInfo ( int uAction, int uParam, string lpvParam, int fuWinIni );

                        public static void SetWallpaper ( string path, Wallpaper.Style style )

                        {

                            SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );

                            RegistryKey key = Registry.CurrentUser.OpenSubKey( "Control Panel\\Desktop", true );

                            switch( style )

                            {

                                case Style.Tile :

                                key.SetValue( @"WallpaperStyle", "0" ) ;

                                key.SetValue( @"TileWallpaper", "1" ) ;

                                break;

                                case Style.Center :

                                key.SetValue( @"WallpaperStyle", "0" ) ;

                                key.SetValue( @"TileWallpaper", "0" ) ;

                                break;

                                case Style.Stretch :

                                key.SetValue( @"WallpaperStyle", "2" ) ;

                                key.SetValue( @"TileWallpaper", "0" ) ;

                                break;

                                case Style.Fill :

                                key.SetValue( @"WallpaperStyle", "10" ) ;

                                key.SetValue( @"TileWallpaper", "0" ) ;

                                break;

                                case Style.Fit :

                                key.SetValue( @"WallpaperStyle", "6" ) ;

                                key.SetValue( @"TileWallpaper", "0" ) ;

                                break;

                                case Style.Span :

                                key.SetValue( @"WallpaperStyle", "22" ) ;

                                key.SetValue( @"TileWallpaper", "0" ) ;

                                break;

                                case Style.NoChange :

                                break;

                            }

                            key.Close();

                        }

                    }

                }

"@

        } catch {}



        $StyleNum = @{

            Tile = 0

            Center = 1

            Stretch = 2

            Fill = 3

            Fit = 4

            Span = 5

        }

    }
    process {

        [Wallpaper.Setter]::SetWallpaper($Path, $StyleNum[$Style])
        sleep -s 5

        [Wallpaper.Setter]::SetWallpaper($Path, $StyleNum[$Style])

    }

}
#App Details

$str_App = 'INWPC000001ENGC1 - Inspire Wallpaper Update'

$str_PackageCode = 'INWPC000001ENGC1'

#Create Log folder

$Str_ProgramData = $env:ProgramData

$Str_LogFolder = "$Str_ProgramData\IntuneWin32Apps"

if(!(Test-Path -Path $Str_LogFolder )){

  New-Item -ItemType directory -Path $Str_LogFolder

}

$str_LogFile = "$Str_LogFolder\IntuneWin32Apps.log"

#Write App

$str_LogEntry = "$(Get-Date) ; $str_App"

Add-Content $str_LogFile $str_LogEntry



#Write Version

$str_LogEntry = "$(Get-Date) ; Version 1"

Add-Content $str_LogFile $str_LogEntry





#Write Start to Log File

$str_LogEntry = "$(Get-Date) ; Install Starting"

Add-Content $str_LogFile $str_LogEntry



# Setting up Wallaper

$StrLAppdata = $env:LOCALAPPDATA

$str_folder = split-path $script:MyInvocation.MyCommand.Path

$Str_Wallpaper = "$StrLAppdata\Unilever"

if(!(Test-Path -Path $Str_Wallpaper )){

  New-Item -ItemType directory -Path $Str_Wallpaper

}

$Source_path=Join-Path -Path $str_folder -ChildPath "\C19"

$Des_Path=Join-path -Path $StrLAppdata -ChildPath "\Unilever\"

Copy-item $Source_Path -Destination $Des_Path -Force -Recurse -Verbose

#Checking the screen resolution

Add-Type -AssemblyName System.Windows.Forms

$Resolution= "{0}x{1}" -f [System.Windows.Forms.SystemInformation]::PrimaryMonitorSize.Width,[System.Windows.Forms.SystemInformation]::PrimaryMonitorSize.Height

write-host $Resolution

#Write Log

$str_LogEntry = "$(Get-Date) ; ScreenResolution is: $Resolution"

Add-Content $str_LogFile $str_LogEntry

#Setting wallpaper based on screen resolution

if ($Resolution  -eq '1920x1080')

{ start-process (Set-WallPaper -Path "$StrLAppdata\Unilever\C19\Wallpaper1.jpg" -Style Fill)

  $str_LogEntry = "$(Get-Date) ; Wallpaper Set: $StrLAppdata\Unilever\C19\Wallpaper1.jpg"

  Add-Content $str_LogFile $str_LogEntry

}



elseif ($Resolution  -eq '2133x1600')

{ start-process (Set-WallPaper -Path "$StrLAppdata\Unilever\C19\Wallpaper2.jpg" -Style Fill)

  $str_LogEntry = "$(Get-Date) ; Wallpaper Set: $StrLAppdata\Unilever\C19\Wallpaper2.jpg"

  Add-Content $str_LogFile $str_LogEntry

}



elseif ($Resolution  -eq '4000x2250')

{ start-process (Set-WallPaper -Path "$StrLAppdata\Unilever\C19\Wallpaper3.jpg" -Style Fill)

  $str_LogEntry = "$(Get-Date) ; Wallpaper Set: $StrLAppdata\Unilever\C19\Wallpaper3.jpg"

  Add-Content $str_LogFile $str_LogEntry

}



else

{ start-process (Set-WallPaper -Path "$StrLAppdata\Unilever\C19\Wallpaper2.jpg" -Style Fill)

  $str_LogEntry = "$(Get-Date) ; Default Wallpaper Set: $StrLAppdata\Unilever\C19\Wallpaper2.jpg"

  Add-Content $str_LogFile $str_LogEntry

}

if (!(Test-Path -Path "HKCU:\SOFTWARE\Unilever\Packages")){

New-Item -Path "HKCU:\SOFTWARE\Unilever\Packages" -Force

}
New-ItemProperty "HKCU:\SOFTWARE\Unilever\Packages" -Name "INWPC000001ENGC1_Installed" -Value "Intune_WP_Installed" -PropertyType "String" -Force | Out-Null

#Close Log File

$str_LogEntry = "-----------------------"

Add-Content $str_LogFile $str_LogEntry 

test

        $reboot = Get-PendingReboot Write-Log - Message "Checking for pending reboot status..." if ( $reboot .IsSystemRebootPe...

Search This Blog