Saturday, May 30, 2020

If Elif example in KornShell

#!/bin/ksh

#clear the screeen
clear
print -n "Enter Number Grade"
read gradenum
if ( ((gradenum>=90)) ) ;then
grade="A"
elif ( ((gradenum>>70)) );then
grade="B"
elif( ((gradenum>>50 )) );then
grade="C"
else
grade="F"
fi

print "Your grade is $grade"

If Else in KornShell

#!/bin/ksh
#prompt the user to enter an input
print -n "enter the number of children you have :"
read numberofchildren
if ( (( numberofchildren>0 )) &&((numberofchildren<=1)) ); then #the space after the ( and before the ) is important

print "you have one children"
else
print "you have more than one children"

fi

If statement compound condition matching

#!/bin/ksh
#prompt the user to enter a number
print -n "Enter your age: "
read age
print
print -n "enter the number of children you have :"
read numberofchildren
if ( (( age < 30 )) && (( numberofchildren==0 )) ); then #the space after the ( and before the ) is important

print "Single and loving it"
fi
if (  ((age > 30)) || ((numberofchildren!=0)) ); then
print "things could be worse"
fi
#operators are &&,||

If statement in Kornshell

#!/bin/ksh
#prompt the user to enter a number
print -n "Enter your age: "
read age
if ((age >= 18))
then
print "Vote"
fi
#operators are ==,!=,>,<,>=,<=

To run a script with full admin privileges On UAC-enabled systems using Powershell

On UAC-enabled systems, to make sure a script is running with full admin privileges, add this code at the beginning of your script

param([switch]$Elevated)

function Test-Admin {
  $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
  $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
    if ($elevated)
    {
        # tried to elevate, did not work, aborting
    }
    else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}

exit
}

'running with full privileges'


Source:https://superuser.com/questions/108207/how-to-run-a-powershell-script-as-administrator

Sunday, May 24, 2020

Starting VMware Services and starting and shutting down the guest operating system using Powershell for VMware Workstation

Start-Service "VMware Authorization Service"
Start-Service "VMware DHCP Service"
Start-Service "VMware NAT Service"
Start-Service "VMware USB Arbitration Service"
start-service "VMware Workstation Server"

#to stop the service which has dependent processes without confirmation

#stop-service "VMware Authorization Service" -Force

#to stop the service which has dependent processes with confirmation

#stop-service "VMware Authorization Service" -Force -confirm

#Now we will try to use vmrun executable to start our virtual machine

#the location of this variable is in C:\Program Files (x86)\VMware\VMware Workstation location

#let us add this path temporarily to our path variable

$env:Path += ";C:\Program Files (x86)\VMware\VMware Workstation"

#we should now access the vmrun command,let us see if vmrun command is working or not by trying #to start our virtual machine

vmrun -T ws start "D:\oracle virtual\DeveloperDaysVM2019-05-31_20.vmx"

#ok the virtual machine starts and I am able to access it remotely using putty

#so let us shutdown the guest softly

#vmrun -T ws stop "D:\oracle virtual\DeveloperDaysVM2019-05-31_20.vmx" soft

#for hard shutdown

#so let us shutdown the guest softly

#vmrun -T ws stop "D:\oracle virtual\DeveloperDaysVM2019-05-31_20.vmx" hard

Starting and stopping vmware services using powershell with and without confirmation

Start-Service "VMware Authorization Service"
Start-Service "VMware DHCP Service"
Start-Service "VMware NAT Service"
Start-Service "VMware USB Arbitration Service"
start-service "VMware Workstation Server"

#to stop the service which has dependent processes without confirmation

#stop-service "VMware Authorization Service" -Force

#to stop the service which has dependent processes with confirmation

#stop-service "VMware Authorization Service" -Force -confirm

Saturday, May 23, 2020

Basic Mathematical Operations in Kornshell

#!/bin/ksh
x=5;print "x is : $x"
y=10;print "y is : $y"
z=15;print "z is : $z"
((Result=x+y))
print "The sum of $x and $y is $Result"
((Subtraction=z-y))
print "The subtraction of $y from $z is $Subtraction"
((Division=x/y))
print "The division of $x by $y is $Division"
Position=1
color[$Position]="Red"
((Position=Position+1))
color[$Position]="Orange"
print "the contents of the \"Color\" array are ${color[*]}"
#to print something preceding with a minus symbol
print -R  "-5" 
#to see if my korn shell supoorts decimal
((result=1.9+1.9))
print "In my version of kornshell 1.9 + 1.9 is $result"

Array Example in Korn Shell

#!/bin/ksh -x
arr[0]="Hello"
arr[1]="World"
print "${arr[0]} ${arr[1]}"
#to print the array using index
index=1
print -n '${arr[index]}='
print  "${arr[index]}"
#to print the whole array
print "The whole array is ${arr[*]}"

Monday, May 4, 2020

Get unique values from an array and store them in another dynamically expanding array in VBA ,VBA Teacher Sourav,Kolkata 8910141720

Option Explicit

Sub uniquearray()
Dim arrdata() As String
Dim workingrange, cell As Range
Dim length As Integer
length = 0
Sheets("conditionalformattingvba").Select
Set workingrange = Range("I2").CurrentRegion
For Each cell In workingrange
length = length + 1
ReDim Preserve arrdata(length) As String
arrdata(length) = cell.Value

Next cell

'For length = 1 To UBound(arrdata)
'Debug.Print (arrdata(length))
'Next length

'MsgBox (arrdata(0))
Dim uniquearray() As String

Dim i As Integer


ReDim uniquearray(1) As String
For length = 1 To UBound(arrdata)
For i = 1 To UBound(uniquearray)

'Debug.Print tempstr1 & " and " & tempstr2
If arrdata(length) = uniquearray(i) Then

Exit For
End If




Next i
If i > UBound(uniquearray) Then
uniquearray(UBound(uniquearray)) = arrdata(length)
ReDim Preserve uniquearray(UBound(uniquearray) + 1) As String

End If


Next length
ReDim Preserve uniquearray(UBound(uniquearray) - 1) As String
For length = 1 To UBound(uniquearray)
Debug.Print (uniquearray(length))
Next length




End Sub

Sunday, May 3, 2020

Dictionary in VBA using example

Option Explicit

Sub dictionaryexample()

Sheets("conditionalformattingvba").Select
Dim dict As Object 'Declare a generic Object reference
Set dict = CreateObject("Scripting.Dictionary") 'Late Binding of the Dictionary
Range("T2").Select
While ActiveCell.Value <> ""
Dim key, val
key = ActiveCell.Value: val = ActiveCell.Offset(0, 1).Address
'Add item to VBA Dictionary
If Not dict.Exists(key) Then
    dict.Add key, val
End If
ActiveCell.Offset(1, 0).Select


Wend

Debug.Print dict.Count 'Result: 1

For Each key In dict.Keys
   Debug.Print key
Next key

'Print all items
For Each val In dict.Items
   Debug.Print val
Next val


'copy format of cells to different location
Dim tempaddress As String
Range("V2").Select
tempaddress = Selection.Address
For Each val In dict.Items

Range(val).Select
Selection.Copy
Range(tempaddress).PasteSpecial Paste:=xlPasteFormats
tempaddress = ActiveCell.Offset(1, 0).Address

Next val
Application.CutCopyMode = False


'Dispose of VBA Dictionary
Set dict = Nothing
End Sub

Conditional formatting using VBA where the conditions and the respective formatting is given,VBA Teacher Kolkata,Sourav Bhattacharya








If you zoom in the picture on the right side there are conditions and the formatting 

after running the macro the formatting based on the given conditions will be applied on the data 


The source code :


Option Explicit

Sub conditionsuperfinal()
Sheets("conditionalformattingvba").Select
Dim dict As Object 'Declare a generic Object reference
Set dict = CreateObject("Scripting.Dictionary") 'Late Binding of the Dictionary
Range("T2").Select
While ActiveCell.Value <> ""
Dim key, val
key = ActiveCell.Value: val = ActiveCell.Offset(0, 1).Address
'Add item to VBA Dictionary
If Not dict.Exists(key) Then
    dict.Add key, val
End If
ActiveCell.Offset(1, 0).Select


Wend

'Debug.Print dict.Count 'Result: 1
'
'For Each key In dict.Keys
'   Debug.Print key
'Next key
'
''Print all items
'For Each val In dict.Items
'   Debug.Print val
'Next val


'copy format of cells where condition matches
'Dim tempaddress As String
'Range("V2").Select
'tempaddress = Selection.Address
'For Each val In dict.Items
'
'Range(val).Select
'Selection.Copy
'Range(tempaddress).PasteSpecial Paste:=xlPasteFormats
'tempaddress = ActiveCell.Offset(1, 0).Address
'
'Next val
'Application.CutCopyMode = False

Sheets("conditionalformattingvba").Select
Dim workingrange, cell As Range
Range("I2:N19").Select
Set workingrange = Selection

For Each cell In workingrange
For Each key In dict.Keys
If InStr(1, cell.Value, key, vbTextCompare) > 0 Then
Range(dict(key)).Select
Selection.Copy
cell.PasteSpecial Paste:=xlPasteFormats
Exit For

Else
cell.ClearFormats
End If
Next key

Next cell


'Dispose of VBA Dictionary
Set dict = Nothing


End Sub

Conditional formatting using VBA

Option Explicit


Sub conditionalfinal()
Sheets("conditionalformattingvba").Select
'Range("G1").Select
'
'Range(Selection, Selection.End(xlDown)).Select
'Range(Selection, Selection.End(xlToRight)).Select
'
Dim workingrange, cell As Range

'Set workingrange = Selection
'


'MsgBox (workingrange.Address)

'Dim workingrange As Range
'Set workingrange = Application.InputBox(Title:="Select the range for conditionalformatting", Prompt:="select the range", Type:=8)
'MsgBox (workingrange.Address)

'Sheets("conditionalformatting").Select
'Range("I5").CurrentRegion.Select
'
'Set workingrange = Selection
'
'
'
'MsgBox (workingrange.Address)

Sheets("conditionalformatting").Select
Range("I2:N19").Select
Set workingrange = Selection
MsgBox (workingrange.Address)


For Each cell In workingrange
If InStr(1, cell.Value, "North", vbTextCompare) > 0 Then
cell.Interior.ColorIndex = 3
cell.Font.ColorIndex = 19
ElseIf InStr(1, cell.Value, "South", vbTextCompare) > 0 Then
cell.Interior.ColorIndex = 23
cell.Font.ColorIndex = 2
ElseIf InStr(1, cell.Value, "West", vbTextCompare) > 0 Then
cell.Interior.ColorIndex = 4
cell.Font.ColorIndex = 30
ElseIf InStr(1, cell.Value, "East", vbTextCompare) > 0 Then
cell.Interior.ColorIndex = 27
cell.Font.ColorIndex = 1
Else
cell.ClearFormats
End If




Next cell





End Sub

Saturday, May 2, 2020

Adding datestamp to a filename using a function with a filename as a parameter in Powershell 7 in Debian 10

function adddatetofilename{
    Param(
        [Parameter(Mandatory=$true,position=1)]
        [string]$filename

    )
   
#$filename="\home\sourav\test.txt"
new-item -type file -name $filename
$todaysdate=get-date -Format MMddyy
$file=Get-ChildItem $filename 
$newfilename=$file.BaseName+"."+$todaysdat+$file.Extension
Rename-Item -path $filename -NewName $newfilename -verbose
}
adddatetofilename -filename ./test.txt

Adding a datestamp to a filename in powershell 7 in Debian 10

create a test file

new-item -type file -name test.txt

$filename="\home\sourav\test.txt"

$todaysdate=get-date -Format MMddyy

$file=Get-ChildItem $filename  

$newfilename=$file.BaseName+"."+$todaysdat+$file.Extension

Rename-Item -path $filename -NewName $newfilename -verbose