Thursday, February 21, 2019

How to check windows machine are x64-bit and x86 (32-bit ) architecture


Logic to detect system architecture for windows machine are 32-bit or x64-bit from power-shell. This is very small function but admin and script-er use a lot in day to day task .I am sharing one function which will deduct bitness of windows machine.We can check OS architecture from remote machine also. 



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

Function GetArchOS($sArchOS)

{
    $sArchOS = (Get-WmiObject Win32_OperatingSystem).OSArchitecture
    If($sArchOS -eq '64-bit' )
    {
        $Script:sArchOS = "x64"
        Write-Host $sArchOS
    }
    Elseif($sArchOS -eq '32-bit')
    {
        $Script:sArchOS = "x86"
        Write-Host $sArchOS
    }
    
}

GetArchOS


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

################################## Remote Machine ################################

$sComputerName='CRP-APPTESTW64'

$sOSArch = (Get-WmiObject Win32_OperatingSystem -computername $sComputerName).OSArchitecture

Write-host $sOSArch

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


################################  Win-32_Processor #################################


$sComputerName='CRP-APPTESTW64'

$sOSArch = Get-WmiObject -Class Win32_Processor -ComputerName $sComputerName| Select-Object AddressWidth

Write-host $sOSArch


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

Note:- Please test script in your test environment before running in production directly.

Wednesday, February 20, 2019

Check process is running or not on windows machine from Power-Shell


Some of the scripter wanted to check process  is running or not in particular windows machine and if process is running so admin can perform required task on system for example kill process, execute any installation file. I tried to create the Power-Shell function to get those process is running on the machine. This function could help somewhere. I have added the array logic so you can pass multiple process as a argument in the function.




################################ Check in local machine #############################

Function CheckProcess($sEnterProccessNameHere)

{

    # Calling Aarray
    @($sEnterProccessNameHere) | `    
    Foreach-Object `
    {
        If (Get-Process $_ -ErrorAction SilentlyContinue)
        { 
        Write-Output "$_ is running" 
        }
        else 
        { 
        Write-Output "$_ is not running" 
        }
    }

}

$sEnterProccessNameHere = @("Services","Outlook","Word","SMSS")  # Pass the process agreement here

CheckProcess $sEnterProccessNameHere      # Calling function 


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

Note:- Not able to pass multiple value in below code but single parameter its working fine.Still searching solution for multiple parameter value

########################### Check process on remote machine ##########################

Function CheckProcess([String[]]$sEnterComputerNameHere,[String[]]$sEnterProccessNameHere)
{
    #Write-host " $sEnterComputerNameHere hello"

        @($sEnterComputerNameHere) | ` 
    Foreach-Object `
    {
        # Calling Aarray
        @($sEnterProccessNameHere) | ` 
        Foreach-Object `
        {
             
            If (get-process -computername $sEnterComputerNameHere | where {$_.ProcessName -eq $sEnterProccessNameHere})
            {
            Write-Output "$_ is running"
            }
            else
            {
            Write-Output "$_ is not running"
            }
        }
    }
}

$Script:sEnterProccessNameHere = @("VPNUI")  # Pass the process agreement here
$Script:sEnterComputerNameHere = @("CRP-APPTESTW64")  # Pass the process agreement here

CheckProcess $sEnterComputerNameHere $sEnterProccessNameHere     # Calling function


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

############################### Calling multiple process on multiple machine ############

Function CheckProcess([String[]]$sEnterComputerNameHere,[String[]]$sEnterProccessNameHere) 
{ #Write-host " $sEnterComputerNameHere"

    @($sEnterComputerNameHere) | Foreach-Object {
        $computer = $_
        Write-Host $computer        
        @($sEnterProccessNameHere) | Foreach-Object {
            $process = $_
            Write-Host $process
            try{
                $x = get-process -computername $computer #Save all processes in a variable
                If ($x.ProcessName -contains $process) #use contains instead of equals
                {
                    Write-Output "$process is running"
                }
                else
                {
                    Write-Output "$process is not running"
                }
            }
            catch
            {
                Write-Host "Computer $computer not found" -ForegroundColor Yellow
            }
        }
    }
}

$script:sEnterProccessNameHere = @("VPNUI","Notepad++","SMSS") 
$script:sEnterComputerNameHere = @("remotecomputer1","remotecomputer2") 

CheckProcess -sEnterComputerNameHere $sEnterComputerNameHere -sEnterProccessNameHere $sEnterProccessNameHere

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


Note:- Please test script in your test environment before running in production directly.

Monday, February 18, 2019

Popup Message Box From Power-Shell..


Every Admin, Developer, Scripter need good customized pop box message box to their user PC screen and creating a message box in power shell is pretty simple command ([System.Windows.MessageBox]::Show('Hello')) we have but sometime you want to show customize box where you can pass message box Title and some pretty good color and that message box appear on user windows for some limited time and close automatic and popup message closing time you can pass as an arguments. You can customize window size as well. I found the very good function which help to popup pretty neat popup message box. May be this can help you.


1. [System.Windows.MessageBox]::Show('Hello')

2. [System.Windows.MessageBox]::Show('Do you want to do coding?','My Test Box','YesNoCancel','Error')

3. Customize popup message box power shell code.

################################### Pop-Up Message ###############################

Function PopupWindow([string]$message,[int]$seconds,[string]$title)
{
     Function ClearAndClose()
     {
        $Timer.Stop();
        $Form.close();
        $Form.Dispose();
        $Timer.Dispose();
        $Label.Dispose();
        $Script:CountDown=$seconds
     }

     Function Button_Click()
     {
        ClearAndClose
     }

     Function Timer_Tick()
     {

        $Label.Text = "$message $Script:CountDown seconds.$title"
             --$Script:CountDown
             if ($Script:CountDown -lt 0)
             {
                ClearAndClose
             }
     }

     Add-Type -AssemblyName System.Windows.Forms
     Add-Type -AssemblyName System.Drawing
     $Form = New-Object system.Windows.Forms.Form
     $Form.Text = "customized Box..."                                         #Display title here
     $Form.Size = New-Object System.Drawing.Size(550,100)   #change the popbox Size
     $Form.StartPosition = "CenterScreen"
     $Form.MinimizeBox = $False
     $Form.MaximizeBox = $False
     $Form.Topmost = $True
     $Form.BackColor = "black"

     $Label = New-Object System.Windows.Forms.Label
     $Label.AutoSize = $true
     $Label.Location = New-Object System.Drawing.Size(30,30)
     # $Label.Font = 'Segoe UI, 8.75pt, style=normal, Italic'
     $label.ForeColor = "Yellow"              # Change the message text color

     $Timer = New-Object System.Windows.Forms.Timer
     $Timer.Interval = 1000

     $Form.Controls.Add($Label)

     $Script:CountDown = 6
     $Timer.Add_Tick({ Timer_Tick})

     $Timer.Start()
     $Form.ShowDialog()


}

PopupWindow("Hello",10,"My customized Box")   #Calling Function here....



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

Note:- Please test script in your test environment before running in production directly.

Sunday, February 17, 2019

Read a .INI File Value from Power shell...


How we can read value from .INI configuration file and assign into the power shell variable ? This task is quite interesting because reading and particular value from a file and use into the power shell can solve many manual effort some time. I have created one function or and you can call it subroutine which reads a value from the file and assign to respective variable. May be this will help you same where .





############################Read Value From .INI file ###############################


Function ReadIniFileValues                                                   
 {
      #$sIniFilePath = Split-Path $sScriptFolder -Parent
      $sIniFilePath = "C:\Temp\Example.ini"          # Mension .ini the file path here
      $sReadIniFileData = [IO.File]::ReadAllText("$sIniFilePath")

      $sConvertIniFileData =  ConvertFrom-StringData -StringData $sReadIniFileData

      # Reading Apptitle infomation from Example.ini file directly

      $Script:sAppTitle =$sConvertIniFileData.APPNAME
      $Script:sAppVer = $sConvertIniFileData.APPVERSION
      $Script:sUnInstallAppName = $sConvertIniFileData.UNINSTALLAPPNAME
      $Script:sUnInstallAppType = $sConvertIniFileData.UNINSTALLAPPTYPE
 }


ReadIniFileValues ""


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



Note:- Please test script in your test environment before running in production directly.

Thursday, February 14, 2019

Uninstall Application From Remote Machine Using Power Shell


Admins has to uninstall some application from users machines remotely and some time they has to do this task remotely without informing user may be those application is unlicensed app or unwanted app.



I found the very power shell simple command to remove those applications. 

################################ For Single Apps ###################################

$sAplicationUnInstallation = Get-WmiObject Win32_Product -ComputerName "Host-Name" | where { $_.name -eq "AppName" }
$sAplicationUnInstallation.Uninstall()


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

################################ For Multiple Apps #################################


$UnInstallApplication = @(“ORCA”, “ClickShare Launcher”)
foreach($UnInstallApplication1 in $UnInstallApplication){
$app = Get-WmiObject -Class Win32_Product -ComputerName "CRP-GDE-W7SCCM"  | Where-Object {
$_.Name -match “$UnInstallApplication1”
}
Write-Host $app
if ($app -ne $Null) {

$app.Uninstall()
}
}

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


Imp Note:-

This WMI and power shell query will remove application from remote machine . One drawback I found in this command .The application uninstallation  string compulsory follow the guide line .it means if you uninstallation MSI  based
Installer so uninstallation string must be “MsiExec.exe /X{41EAEB83-2C73-4187-AE15-28B317B4E44C}”   if uninstallation string will be “MsiExec.exe /I{41EAEB83-2C73-4187-AE15-28B317B4E44C}” then this command will repair and reinstall the msi It will not uninstall the application. One more info if any application need mandatory reboot so machine will reboot after uninstallation in some case you cannot stop the reboot. Please try on test machines before running on production.

Note:- Please test script in your test environment before running in production directly.

Wednesday, February 13, 2019

Get Hot-fix(Microsoft Hotfix or KB Patch) Info from users machine.


Now days everybody talking about patch vulnerability in the organization and admin has to take care there job very seriously .Every users machine need to fully patch with security patches and sometime admin need to check some critical patches are installed on the users machine or not.
This small logic will help you to get info from users machines for particular KB is installed or not.
You just has to pass machine name C:\temp\PCNameList.txt.




####################### Get All Patch Installed On  Remote Machine ##################

$ServerName = Get-Content "C:\temp\PCNameList.txt"  
  
foreach ($Server in $ServerName) 
{  
  
        if (test-Connection -ComputerName $Server -Count 2 -Quiet ) 
        {   
                         
            "$Server is Pinging"
             Get-hotfix -computername $server | select-object -property Description,HotFixID,InstalledBy,InstalledOn | export-csv c:\temp\$server.csv
        }

        Else

            {
                    "$Server not pinging"
              
            }      
          
         }

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




###################Get single Patch Installed On  Remote Machine####################

$ServerName = Get-Content "C:\temp\PCNameList.txt"  
  
foreach ($Server in $ServerName) 
{  
  
        if (test-Connection -ComputerName $Server -Count 2 -Quiet ) 
        {   
                         
            "$Server is Pinging"
             Get-hotfix -computername $server | select-object -property Description,HotFixID,InstalledBy,InstalledOn | where {$_.hotfixid -match 'KB4012212'} | export-csv c:\temp\$server.csv
        }

        Else

            {
                    "$Server not pinging"
              
            }      
          
         } 
  
#############################################################################

Note:- Please test script in your test environment before running in production directly.

Tuesday, February 12, 2019

Get Remote Machine Folder Size From Power Shell..


In some of the  administrator task scenario admin need to know the particular folder size from user machine’s and sometime remote sever storage folder admin’s has to monitor without login into the server or machine’s
.Here power shell help you get folder size in GB OR MB from remote machine .I made changes into script as my requirement into this script.
This scrip use psexec.exe to enter PS session on remote machine in same network. You have to copy this Script.ps1 and psexec.exe into Same folder(like C:\Temp).You can run this script on multiple machine and server at a time
just you have to pass machine name “C:\Temp\CBSLogSizeCompList.txt” and it will create the log in to “C:\temp\CBSLogSize.txt




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

#  Get Folder Size from Remote machine

Function Class-Size($size)
{
IF($size -ge 1GB)
{
"{0:n2}" -f  ($size / 1GB) + " GB"
}
ELSEIF($size -ge 1MB)
{
"{0:n2}" -f  ($size / 1MB) + " MB"
}
ELSE
{
"{0:n2}" -f  ($size / 1KB) + " KB"
}
}

function Get-FolderSize
{
Param(
$Path, [Array]$Computers
)
$Array = @()
Foreach($Computer in $Computers)
    {
    $ErrorActionPreference = "SilentlyContinue"

$Length = Invoke-Command -ComputerName $Computer -ScriptBlock {
 (Get-ChildItem $args[0] -Recurse | Measure-Object -Property Length -Sum).Sum

} -ArgumentList $Path

$Result = "" | Select Computer,Folder,Length
$Result.Computer = $Computer
$Result.Folder = $Path
Write-Host $length
$Result.Length = Class-Size $length
$array += $Result
$Result | Add-Content c:\Temp\CBSLogSize.txt
}

return $array
}

$sComputerName = Get-Content 'C:\SWKSoftware\CBSLogSizeCompList.txt'

foreach ($sComputerName1 in $sComputerName)
{

        if (test-Connection -ComputerName $sComputerName1 -Count 2 -Quiet )
        { 
                       
            #"$sComputerName1 is Pinging"

            C:\SWKSoftware\PSEXEC.exe "\\$sComputerName1" -s -h -d powershell.exe "enable-psremoting" -force | Out-Null
         
             #"$sComputerName1 is Pinging" | Add-Content c:\Temp\CBSLogSize.txt

             Get-FolderSize -Computers $sComputerName1 -Path "C:\Windows\Logs\CBS"

             #Get-FolderSize -Computers $sComputerName1 -Path $Path

             " " | Add-Content c:\Temp\CBSLogSize.txt
         
        }

        Else

            {
                    "$sComputerName1 not pinging"
           
            }   
       
 }

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


Note:- Please test script in your test environment before running in production directly.

Monday, February 11, 2019

Get registry value info from PowerShell on Remote machines


In many scenario as an administrator task you want to know the registry value from remote machine users in same network. Power Shell gave you many way to get that value  without disturbing to users.
I like this logic to get that registry value from multiple machine. And you can print those value in log file.
So here is the power shell script logic.
Please declare the remote machine name in this text file "C:\Temp\RegInfo.txt" 

"C:\Temp\PS-Ping\Registry.log " file will give you all the remote machine registry info.



##################################Save Script As .PS1 ##############################

$ServerName = Get-Content "C:\Temp\RegInfo.txt"

foreach ($Server in $ServerName)

        if (test-Connection -ComputerName $Server -Count 2 -Quiet )
        { 
            "$Server is Pinging"

             $SregistryInfo = Invoke-command -computer $Server {Get-ItemProperty -Path "HKLM:\HARDWARE\DESCRIPTION\System\BIOS\" | select SystemVersion} | Add-Content "C:\Temp\PS-Ping\Registry.log"

             Write-host $SregistryInfo

             Write-host $Server

             #Invoke-command -computer BLR-P-CMSS01 {Get-ItemProperty HKLM:\Software\1E\NomadBranch\ | select SpecialNetShare,SigsFolder}

        }
        Else

            {

                    "$Server not pinging"

            }     

         } 

 ################################################################################# 
Note:- Please test script in your test environment before running in production directly.

Sunday, February 10, 2019

Windows File Association From Powershell..


This power shell script will solve the file association issue in windows environment. If you want to open .log file from Notepad ++ or you want to open all the PDF and doc file from Adobe Reader .This power shell scrip will play very good role to change those Association in windows environment. I have tested this in my testing environment  and it works form me very nicely.





Basically these power shell commands make changes in registry key under "HKLM\SOFTWARE\Classes\.jpeg".This is one of the way to change file association but i found this script do its job very easily.

#################################################################################
#Just save this file .PS1 Extension and run as a admin.

$sFileExts=@("txt","log","csproj","sql","xml","flobble")
echo "## setting up file associations"
foreach ($sFileExts1 in $sFileExts){
    $extfile2=$sFileExts1+"file"
    $dotext="." + $sFileExts1
    cmd /c assoc $dotext=$extfile2
    cmd /c "ftype $extfile2=""C:\Program Files (x86)\Notepad++\notepad++.exe"" %1"
    echo ""
}

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


Note:- Please test script in your test environment before running in production directly.

Enable Power Shell Session on Remote machine..

As a admin if you want to run some Power shell commands on  user remote machine then and want to know some  machine info silently  so one of the way is psexec.exe power shell remote session.Many Engineers will not prefer execute psexec.exe on remote machine because of security beach issue.Some cases you don,t have any option to know the machine status .
here is the Basic Steps.

1. Download the psexec.exe on your machines.
2. Open Power shell Editor as admin in your machine.


3.Navigate to psexec.exe in PS console  Execute below command

        psexec.exe \\hostname -s -h -d powershell.exe "enable-psremoting" -force


4. After that Run below command to Enable PS Enable.

     Enable-PSRemoting -Force


5. Final command to enter in PS remote session.
   
    Enter-PSSession -ComputerName HostName


Note:- For running above command you must have Admin Access. 
Note:- Please test script in your test environment before running in production directly.

Saturday, February 9, 2019

kill multiple process from Power Shell.

We face many time issue when we need to kill running multiple process on the windows environment.This power shell function will help you kill multiple process which you want to kill.

Function KillProcess($sProcessNameStr) 
{ 
    $sStringArray = $sProcessNameStr -split ","                                                              
    $sProcessName1 = @($sStringArray) 
    Foreach($sProcessName in $sProcessName1) 
        {  
            $sProcessName1 = [System.IO.Path]::GetFileNameWithoutExtension($sProcessName) 
            $sProcessName = Get-Process $sProcessName1 -ErrorAction SilentlyContinue 
            if($sProcessName -ne $null) 
              {  
                Stop-Process -ProcessName $sProcessName1 -ErrorAction SilentlyContinue 
              } 
         } 
} 
 
# E.g 
KillProcess "notepad.exe","iexplore.exe"
Note:-Please test script in your test environment before running in production directly.