Friday, 11 May 2018

VB Script: Check for pending REBOOT operations in Machine

Sometimes we face scenario like application needs restart before starting the installation as a prerequisite.
Means it checks for pending reboot operations in machine and will restart automatically if detects any. so we can have script to check for any pending reboot operations and proceed with installation only if there is no pending reboot operations.

Script:
    Dim strComputer,strKeyPath1,strKeyPath2,strKeyPath3,strValueName1
Dim strKeyName2,strKeyName3,strValue,SubKey,arrValues1,arrSubKeys2,arrSubKeys3
        Dim strReturn,oReg
        Const HKEY_LOCAL_MACHINE = &H80000002
        Const REG_MULTI_SZ = 7
        strComputer = "."
        strReturn = ""
        Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
       
        strKeyPath1 = "SYSTEM\CurrentControlSet\Control\Session Manager"
        strValueName1 = "PendingFileRenameOperations"
       
        strKeyPath2 = "SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update"
        strKeyName2 = "RebootRequired"
       
        strKeyPath3 = "SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing"
        strKeyName3 = "RebootPending"
       
        If oReg.EnumKey (HKEY_LOCAL_MACHINE,strKeyPath2,arrSubKeys2) = 0 Then
         For Each Subkey in arrSubKeys2
          If StrComp(Subkey,strKeyName2) = 0 Then
           strReturn = strReturn & " " & Subkey
          End If
         Next
        End If
       
        oReg.GetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath1,strValueName1,arrValues1
        If Not IsNull(arrValues1) Then
            strReturn = strReturn & " " & strValueName1
        End If
       
        If oReg.EnumKey (HKEY_LOCAL_MACHINE,strKeyPath3,arrSubKeys3) = 0 Then
         For Each Subkey in arrSubKeys3
          If StrComp(Subkey,strKeyName3) = 0 Then
           strReturn = strReturn & " " & Subkey
          End If
         Next
        End If
       
        If StrComp(strReturn,"") = 0  Then
         Msgbox "No Pending Reboot operations detected!!!"
         'Do your task here
        Else
         Msgbox "Pending Reboot operations detected!!!, Kindly Restart"
        End If
Steps to DO:
1. Copy code and save the script as XXX.vbs
2. Run the script as Administrator.
Will get the below message box if detecting any pending Reboot.


Will get the below message box if not finding any pending Reboot.

Thursday, 26 April 2018

VB Script: UnZip a compressed folder using script.

Have faced issues on deploying an application through SCCM, Install source has many sub-directories within it and getting long file path name error while copying to Distribution point from file-share.
so zipped the whole source and written a script to unzip the install file,Directories before starting the installation using script.

Below are the sample script to UnZip a zipped folder.

Script:
Option Explicit
Dim input,oshell,scriptpath
Dim intOptions, objShell, objSource, objTarget
Set oShell = WScript.CreateObject("WScript.Shell")
ScriptPath = Left(WScript.ScriptFullName, InstrRev(WScript.ScriptFullName, "\"))
oShell.CurrentDirectory = ScriptPath

Input = InputBox("Enter your Zip file name","UnZipping Folder!!!")
Extract Scriptpath & input &".zip", scriptpath

Sub Extract( ByVal myZipFile, ByVal myTargetDir )
    Set objShell = CreateObject( "Shell.Application" )
    Set objSource = objShell.NameSpace( myZipFile ).Items( )
    Set objTarget = objShell.NameSpace( myTargetDir )
    intOptions = 20
    objTarget.CopyHere objSource, intOptions
   
    Set objSource = Nothing
    Set objTarget = Nothing
    Set objShell  = Nothing

End Sub

Steps to DO:
1. Copy code and save the script as XXX.vbs
2. Run the script as Administrator.
3. Enter the Zip file Name without extension.

4. Click Ok, it will UnZip the folder on your script directory.

Note: Keep the Zipped folder along with your script to run without errors.

VB Script: Kill multiple processes

Sometimes we may need to kill the running process to proceed for uninstallation of an application without any issues.

Script:
Option Explicit
'On Error Resume Next
Dim objShell, X, strProcesses

Set objShell = CreateObject("WScript.Shell")

strProcesses = Array(_
"notepad.exe",_
"calc.exe",_
"winword.exe",_
"excel.exe")

For X = 0 to Ubound(strProcesses)
objShell.Run "%COMSPEC% /c TASKKILL.EXE /F /IM """ & strProcesses(X) & """ /T ", 0, True
Next

Set objShell = Nothing


NOTE: For examples, used Notepad,Calculator,Word and Excel process. replace the process name as per your needs in the array.

VB Script: Apply permission for folder using ICACLS

For some cases we need to give full control permission for Users to the INSTALLDIR to make the application work without any issues.

NOTE: Initially tried with CACLS but this not applying permission when executing in system context, but the same worked when running the script as normal administrator. so used ICACLS in below script to apply permission to users through system context.

Script:
Option Explicit
Dim strHomeFolder,WshShell,SysRoot,HomeFolder
Dim intRunError,objFSO,win,exepath,file

Set WshShell = CreateObject("Wscript.Shell")
SysRoot = WshShell.ExpandEnvironmentStrings("%SystemDrive%")
win = WshShell.ExpandEnvironmentStrings("%windir%")
Set objFSO = CreateObject("Scripting.FileSystemObject")

HomeFolder = WshShell.ExpandEnvironmentStrings("%ProgramFiles(x86)%")

strHomeFolder = Chr(34) & HomeFolder & "\Java" & Chr(34)

exepath=win & "\system32\icacls.exe"
file= chr(34) & exepath & chr(34) & Chr(32) & strHomeFolder & " /Q /C /T /grant Users:(OI)(CI)F"
intRunError = WshShell.Run(file,0,True)
MsgBox "Exit code:" & intRunError


Before Applying permission


After applied permission using script.

Thursday, 15 March 2018

Batch Script: Run powershell using Batch file(.bat)

We do face difficulties for running a Power Shell script and its not just like VB script,Batch script(just double click,it will run). here is the easy way to run a power shell script using single click.

Steps to do:
Open Notepad and Create a batch script with below lines.

@ECHO OFF
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '%~dpn0.ps1'"

Now save the Batch file with the same name of PowerShell script.





Right click on batch file and click on "Run as Administrator".





PowerShell script will get executed successfully.

Note: Both scripts need to be in the same directory to get it worked.

Tuesday, 6 March 2018

PowerShell: Script to run client cycle Actions that are configured in Configuration Manager

Created a script to run the below cycle actions.


Script:

$WMIPath = "\\" + $env:COMPUTERNAME + "\root\ccm:SMS_Client"
$SMSwmi = [wmiclass] $WMIPath
[Void]$SMSwmi.TriggerSchedule("{00000000-0000-0000-0000-000000000121}")
[Void]$SMSwmi.TriggerSchedule("{00000000-0000-0000-0000-000000000003}")
[Void]$SMSwmi.TriggerSchedule("{00000000-0000-0000-0000-000000000021}")
[Void]$SMSwmi.TriggerSchedule("{00000000-0000-0000-0000-000000000001}")
[Void]$SMSwmi.TriggerSchedule("{00000000-0000-0000-0000-000000000002}")
[Void]$SMSwmi.TriggerSchedule("{00000000-0000-0000-0000-000000000031}")
[Void]$SMSwmi.TriggerSchedule("{00000000-0000-0000-0000-000000000108}")
[Void]$SMSwmi.TriggerSchedule("{00000000-0000-0000-0000-000000000113}")
[Void]$SMSwmi.TriggerSchedule("{00000000-0000-0000-0000-000000000032}")



<#
Application Deployment Evaluation Cycle: {00000000-0000-0000-0000-000000000121}
Discovery Data Collection Cycle: {00000000-0000-0000-0000-000000000003}
Hardware Inventory Cycle: {00000000-0000-0000-0000-000000000001}
Machine Policy Retrieval and Evaluation Cycle: {00000000-0000-0000-0000-000000000021}
Software Inventory Cycle: {00000000-0000-0000-0000-000000000002}
Software Metering Usage Report Cycle: {00000000-0000-0000-0000-000000000031}
Software Updates Deployment Evaluation Cycle: {00000000-0000-0000-0000-000000000108}
Software Updates Scan Cycle: {00000000-0000-0000-0000-000000000113}
Windows Installer Source List Update Cycle: {00000000-0000-0000-0000-000000000032}
#>

Steps To DO:
1. Copy code and save the script as XXX.PS1
2. Set the execution policy to run the script.
3. Execute the script and it will run the above cycle actions.

PowerShell: Script to remove AppV application with name.

Created an Universal remover script for AppV, which is used to remove an AppV application with use of application name.

Script:

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$Name = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Package Name", "APPV:Universal Remover", "")
$logfile="C:\Windows\Logs\"+$Name+".log"
Import-Module AppvClient
$package=Get-AppvClientPackage -All|?{ $_.Name -like "*$Name*"}
if($package)
{
$package|ForEach-Object{
    $Name1=$_.Name
    $a = new-object -comobject wscript.shell
    $intAnswer = $a.popup("Do you want to remove $Name1 application?", 0,"Uninstall",4)
    If ($intAnswer -eq 6) {  
    Stop-AppvClientPackage "$Name1"|Unpublish-AppvClientPackage -Global|Remove-AppvClientPackage | Out-File -Append -FilePath $logfile
    }
    }
}
else{
    Write-Host "Package named like($Name) is not published in the machine"
    }

Steps To DO:
1. Copy code and save the script as XXX.PS1
2. Set the execution policy to run the script.
3. Execute the script and you will get popup for application name. Enter the application name to uninstall and click OK.

4. Click Yes.
 
5.Application will get removed form system.(if you have multiple applications with related to given  name, you will get all the applications one after other to proceed for removing)

Note: Application will get removed successfully for all users, if any error occurs kindly check the event viewer logs for more details.