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.

Monday 5 March 2018

PowerShell: Script to Uninstall MSI with Application Name.

We do face issues like multiple versions of same application got installed on the machine(e.g: Java,Visual C++). Created an Universal Uninstaller script, which is used to uninstall an MSI application with use of application name.

Script:
$Global:LogDir = $env:windir+"\logs"
$Global:gLogPath = $LogDir + "\" + "MSI Universal Uninstaller_Overview.log"
If (Test-Path -path $LogDir)
    {}
Else {
    #This system is not having logs folder. Hence creating it'
    New-Item -path $LogDir  -ItemType directory
    New-Item -path $LogPath -ItemType File
     }
Function Write-Log {
    Param(
        [string]$Message,
        [string]$Path,
        [string]$Level = "info"
    )

    if (-not $(Test-Path $path))
    {
        New-Item $path -Type File -ErrorAction SilentlyContinue >> $Log
    }
   
    if(Test-Path $path)
    {
        Switch -wildcard ($level) {
            'info'
            {
                Write-Output "[$level] : $(Get-Date) ----> $Message" | Format-Table -AutoSize | Out-File -FilePath $Path -Append
               
            }
            'warning'
            {
                Write-Output "[$level] : $(Get-Date) ----> $Message" | Format-Table -AutoSize | Out-File -FilePath $Path -Append
               
            }
            'error'
            {
                Write-Output "[$level] : $(Get-Date) ----> $Message" | Format-Table -AutoSize | Out-File -FilePath $Path -Append
               
            }
            default {}
        }
    }
}

$Log = $gLogPath
Write-Log -Path $Log -level "info" -message $("==============================================")

Function ReadMSI{
    Param($MSIName)
     
    If([string]::IsNullOrEmpty($MSIName))
    {
        Write-Log -Path $Log -level "info" -message $("Enter valid Application Name")
    }
    Else
    {
        uninst_MSI($MSIName)
    }
}

Function uninst_MSI($Ename)
{
Write-Log -Path $Log -level "info" -message $("Entered Application Name:$Ename")
$msi = Get-WmiObject -Class win32_product | ? {$_.Name -like "*$EName*"} | Select-Object Name,IdentifyingNumber,Version
$msi_search = $msi | Sort-Object Name | Out-GridView -Title "MSI Applications on $Env:COMPUTERNAME" -PassThru
If($msi)
{
    If($msi_search)
        {  
            Write-Log -Path $Log -level "info" -message $("Applications selected: ")
            $return = $msi_search | Select-Object Name,Version | Format-Table -HideTableHeaders -AutoSize | Out-String
            Write-Log -Path $Log -level "info" -message $("$return")
            $title = "Uninstall the following apps from $($ENV:computername)"
            $message = "You've selected the below apps for removal, do you wish to continue?:$return"
            $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Removes application(s) from $env:computername."
            $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Returns to application listing."
            $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
            $result = $host.ui.PromptForChoice($title, $message, $options, 0)

    If ($result -eq 0)
    {
    $msi_search|ForEach-Object{
    $Name=$_.Name
    $GUID=$_.IdentifyingNumber
    $Ver=$_.Version
    $Product1 = $Name+" "+$Ver
         
        $UNInstarguments = $LogDir + "\" + $Product1 + "_UNINST.log"
        $Global:arguments = " /x " + """$GUID""" + " /qb! REBOOT=ReallySuppress MSIRESTARTMANAGERCONTROL=Disable /L*V " + """$UNInstarguments"""
        Write-Log -Path $Log -level "info" -message $("Uninstalling the MSI..($Product1)..")
        $process = Start-Process -FilePath msiexec.exe -ArgumentList $arguments -Wait -PassThru
       
        if ($process.ExitCode -eq 0){
        Write-Log -Path $Log -level "info" -message $("($Product1)has been successfully uninstalled with ExitCode: $($process.ExitCode)")
        }
        elseif($process.ExitCode -eq 3010){
        Write-Log -Path $Log -level "info" -message $("($Product1)has been successfully uninstalled(REBOOT_REQUIRED) with ExitCode: $($process.ExitCode)")
        }
        else{
        Write-Log -Path $Log -level "info" -message $("($Product1)Uninstallation failed with ExitCode: $($process.ExitCode)")
        }
     }
     }
     Else{Write-Log -Path $Log -level "info" -message $("You have cancelled the uninstallation")}
     }
     Else
     {
     Write-Log -Path $Log -level "info" -message $("You have not selected any apps to unistall")
     }
     }
    Else
   {
   Write-Log -Path $Log -level "info" -message $("Application named like ($Ename)is not installed in the machine")
   }
}
  
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$MSIName = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Package Name", "MSI:Universal Remover", "")

ReadMSI $MSIName

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. Will get list of installed applications like below.

5. Select the application you want to uninstall from above list and Click OK(For Multiple applications use Ctrl to select and proceed).
6. Will get confirmation to uninstall,Click on Yes.

7. Selected application is getting uninstalling(Alter the parameters in script to do silently).

8. Logs files get created under "C:\Windows\Logs"

9. Open the Overview log file to get the details of Exit code.