Archive for the ‘Scripts’ Category

Following script will loop through all Partner Center customers, will export them in batches of 100 and every “chunk” will be exported to separate CSV file.


$custIDs = Get-PartnerCustomer
$chunks = [System.Collections.ArrayList]::new()
for ($i = 0; $i -lt $custIDs.Count; $i += 100) {
    if (($custIDs.Count - $i) -gt 99  ) {
        $chunks.add($custIDs[$i..($i + 99)])
    else {
        $chunks.add($custIDs[$i..($custIDs.Count - 1)])
$today = [datetime]::Today.ToString("yyyy-MM-dd")
$count = 1
foreach ($chunk in $chunks) {
    $path = "c:\Reports\$today Chunk $count of $($chunks.Count).csv"
    $chunk | Export-Csv $path -Append

This script will check if user password expires in 1,3 or 7 days and if yes, it will send email to user


First, encrypt password and store it in file

$password = "somepass"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPwd | ConvertFrom-SecureString
Set-Content "C:\temp\ExportedPassword.txt" $secureStringText


$mailuser = ""

$pwdmail = Get-Content "C:\temp\ExportedPassword.txt"
$securemailPwd = $pwdmail | ConvertTo-SecureString

$EmailCreds = New-Object System.Management.Automation.PSCredential -ArgumentList $mailuser, $securemailPwd

$from = ""

# OU to search 

$path = "CN=Users,DC=example,DC=com"

$users = Get-ADUser -SearchBase $path -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0} `
-Properties "Name", "EmailAddress", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Name", "EmailAddress", `
@{Name = "PasswordExpiry"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed").tolongdatestring() }}

# Days remaining until password expiration
$WarningDays = 1,3,7

# Get current day
$today = (Get-Date).ToLongDateString()
try {
foreach ($user in $users)
 foreach ($WarnDay in $WarningDays){
 if ($user.PasswordExpiry -eq (get-date).adddays($WarnDay).ToLongDateString()) 
  # Calculate days beteween today and date when password will expire
  $ts = New-TimeSpan -Start $today -End $user.PasswordExpiry
  $days = $ts.Days
  $subject = "Password expiration notification - " + $user.Name
  $body = "Dear " + $ + ",`nYour Password will expire in " + $days + " days"
  Send-MailMessage -to $user.EmailAddress -from $from -Subject $subject -Body $body -BodyAsHtml -SmtpServer -UseSsl -Credential $EmailCreds -Port 587

catch {
    from itertools import islice 

    def getListOfFiles(dirName):
    # create a list of file and sub directories 
    # names in the given directory 

    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory 
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
    return allFiles  

dirName = "C:\SIEMLogs\Email"
listOfFiles = getListOfFiles(dirName)

# sort filenames by creation date (ascending)

sorted_files = sorted(listOfFiles, key=os.path.getmtime)

# select top 5 elements from sorted list

top_files = islice(sorted_files,5)

# Print top 5 files
for elem in top_files:

# Number of files in sub directories

cpt = sum([len(files) for r, d, files in os.walk("C:\SIEMLogs\Email")])

print cpt

Listing files in directory (without sub directories),sorting by creation date (ascending) and count of total files:

path = "C:\SIEMLogs\Email"
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime)

for a in time_sorted_list:
    print a

# Number of files in Directory only

path, dirs, files = next(os.walk("C:\SIEMLogs\Email"))
file_count = len(files)

print file_count

This function will print registry value for specific key, in this case HPATH value

import _winreg

def getPath():
    # Open the key and return the handle object.
    hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
    # Read the value.                      
    result = _winreg.QueryValueEx(hKey, "MachineId")
    # Close the handle object.
    result = result[0]
    return result

Another solution:

def regkey_value(path, name="", start_key = None):
    if isinstance(path, str):
        path = path.split("\\")
    if start_key is None:
        start_key = getattr(_winreg, path[0])
        return regkey_value(path[1:], name, start_key)
        subkey = path.pop(0)
    with _winreg.OpenKey(start_key, subkey) as handle:
        assert handle
        if path:
            return regkey_value(path, name, handle)
            desc, i = None, 0
            while not desc or desc[0] != name:
                desc = _winreg.EnumValue(handle, i)
                i += 1
            return desc[1]

posread = regkey_value(r"HKEY_LOCAL_MACHINE\COMODO", "MachineId")

3rd way:

import _winreg

reg_connection = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)

key_value = _winreg.OpenKey(reg_connection, r"COMODO")

print _winreg.QueryValueEx(key_value, "MachineId")[0]

Reading registry keys from x64 versions of Windows using x86 Python installation:

import _winreg

def get_path(name):
        registry_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\\COMODO', 0, (_winreg.KEY_WOW64_64KEY + _winreg.KEY_READ))
        value = _winreg.QueryValueEx(registry_key, "MachineId")[0]     
        return value
    except WindowsError:
        return None

This class will accept 2 input parametrers:

one of type string and second of type integer, and we need to make sure second parameter needs to be integer

# function which tests for type:

def ensure_type(value, types):
    if isinstance(value, types):
        return value
        raise TypeError('Value {value} is {value_type}, but should be {types}!'.format(
            value=value, value_type=type(value), types=types))

class Account():
    def __init__(self, name, amount): = name
        self.amount = amount

    def __str__(self):
        return "Account owner:" + + '\nAmmount$: ' + str(self.amount)    
    def add(self, num):
        self.amount = self.amount + num
        return self.amount
    def name(self):
        return self.__dict__['name']

    def name(self, value):
        self.__dict__['name'] = ensure_type(value, str)

    def amount(self):
        return self.__dict__['amount']

    def amount(self, value):
        self.__dict__['amount'] = ensure_type(value, int)


acc = Account('jose', 100)


Related posts:

Object Oriented Programming (OOP) allows programmers to create their own objects that have methods and attributes. For much larger scripts of python code,functions by themselved aren’t enough for organization and repeatability.

Commonly repeated tasks and objects can be defined with OOP to create code that is more usable.

Name of the class uses Camel case convention

CamelCase is a naming convention in which the first letter of each word in a name is capitalized. (StarCraft,FireHouse)

self” is the instance object automatically passed to the class instance’s method when called, to identify the instance that called it. “self” is used to access other attributes or methods of the object from inside the method. (methods are basically just functions that belong to a class)

Class syntax:

class NameOfClass():

	   self.param1 = param1
       self.param2 = param2	   

     # self is used to connect method to the class
    def some_method(self):
        # perform some action

__init__ is special method (function) which creates instance of class object

param1 param2 input parameters to class

self.param1 self.param2 atributes of the class

Dog class accepts breed parameter and assigns it to breed attribute

class Dog():

    def __init__(self,breed):
        # assign breed atrubute  to self.breed
        self.breed = breed   

# create instance of class Dog

mydog = Dog("dalmatian")

# breed is attribute of class instance mydog



Class object attributes

is attribute that belongs to any instance of class hence it’s globally visible.

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed):

        self.breed = breed = name

Create instance of Dog class

mydog = Dog("dalmatian")

Get class atributes

mydog.breed ‘dalmatian’

mydog.species ‘mammal’


are functions which takes class input parameters through self keyword

We added another class parameter – name

and added method bark() which returns name of the dog.

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed, name):

        self.breed = breed = name
    # method
    def bark(self):
        print(f'{} barks')

mydog = Dog("dalmatian", "Pluton")



# call method

Pluton barks

Methods can take arguments not specified in class inputs

In bark method we added number input, note that in print function it specified without self because this paramter is

“outside” of class, ie, it’s not specified during class definition.

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed, name):

        self.breed = breed = name
    def bark(self, number):
        print(f'{} barks and number is {number}')

mydog = Dog("dalmatian", "Pluton")



# supply number argument


Pluton barks and number is 1

Priniting class objects

If we want to print input parameters, we need to use

__str__ – convert objects to string

__len__ – convert objects to integers

Dog class now has 3 input paraneters:

strings (name and breed)

integers (number)

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed, name, num):

        self.breed = breed = name
        self.num = num
    # return string atribute
    def __str__(self):

        return 'Name: ' + + 'Breed: ' + self.breed    
    # return integer attribute
    def __len__(self):
        return self.num

    def bark(self, number):
        print(f'{} barks and number is {number}')   

my_dog = Dog('husky','pluton', 1) 


'Name: pluton Breed: husky'


is creating new class from existing one. Derived class have all properties of base class (attributes and methods)

Base class:

class Animal():
    def __init__(self):
        print("Animal created")

    def who_am_i(self):
        print("I am an animal")

    def eat(self):
        print("I am eating")

my_animal = Animal()

Animal created

I am eating


I am an animal

Creating Dog class from Animal class.

Dog class “inherits” all methods from Animal class.

class Dog(Animal):
    def __init__(self):
        print ("Dog created")

my_dog = Dog()

Animal created
Dog created

I am eating

I am an animal

Methods from base class can be overriden in “child” (derived) class. It’s called Polymorphism.


allows us to define methods in the child class with the same name as defined in their parent class.

Overriding eat() method.

In Dog class create same method as in base class and change it’s ouptut.

class Dog(Animal):
    def __init__(self):
        print ("Dog created")

    def eat(self):
        print("I'm a dog eating")

I'm a dog eating

Abstract class

cannot be instantiated (objects cannot be created from it)

To create abstract class we need to import following namespace:

from abc import ABC,abstractmethod

ABC stands for abstract class and we need to add @abstractmethod above each method we do not want to instantiate.

from abc import ABC,abstractmethod
 class Animal(ABC):
  def __init__(self, name): = name
      print(f'Animal Created {}')

f we now try to create instance from Animal class we’ll face expected error

TypeError: Can't instantiate abstract class Animal with abstract methods __init__

Let’s add another method to Animal class and derive Dog class from Animal.

from abc import ABC,abstractmethod
class Animal(ABC):
  def __init__(self, name): = name
      print(f'Animal Created {}')
  # @abstractmethod 
  def eat(self):
    print(f'{} eating')
class Dog(Animal):
  def __init__(self, name): = name      
    # Animal.__init__(self)
    print(f'Animal Created {}')    
# output
my_dog = Dog('tom')
'Animal Created tom'
'tom eating'

Calling module from same folder

In Documents folder we have 2 files: with simple function in it:

def my_func():
  print("My function") from which we’ll call function in

To call function from another file we’ll use import keyword followed by file name, then we’ll simple call function from file (my_func)

from mymodule import my_func


My Function

Calling modules from subfolders


Both files are empty.The primary use of is to initialize Python packages


def report_main():
    print("Hey I'm in some_main_script in main package")


def sub_report():
    print("Hey i'm function inside my subscript")

From Documents/ parent folder we’ll call functions in Documents/MainPackage/ and Documents/MainPackage/SubPackage/ files


from keywords is followed by folder name and import is followed by file name located in that folder.

MainPackage/SubPackage corresponds to MainPackage.SubPackage, dot characters is used to express subfolders.

from MainPackage import some_main_script

from MainPackage.SubPackage import mysubscript


Hey I'm in some_main_script in main package


Hey i'm function inside my subscript

Related articles:

LEGB is acronim of:

L:Local – Names assigned in any way within a function (def or lambda) and not declared global in that function.

E:Enclosing function locals – Names in the local scope of any and all enclosing functions (def or lambda), from inner to outer.

G:Global (module) – Names assigned at the top-level of a module file. or declared global in a def within the file.

B:Built-in (Python) – Names preassigned in the built-in names module:open,range,SyntaxError.

Local scope refers to variables defined in current function.Always, a function will first look up for a variable name in its local scope. Only if it does not find it there, the outer scopes are checked.

name = 'This is a global string'

   def myfunc():
      name = "Hello World"

Hello World

In above example we have 2 variables with same name and when function is executed, it’s looking into it’s own namespace (name=’Hello World’), in case there is no variable name inside “enclosing function” – myfunc(), then global name string would be applied, below example illustrates this:

name = 'This is a global string'

   def myfunc():

This is a global string

Let’s look at next example:

x =  50

def func(x):
     print(f'X is {x}')
     # Local reassignment
     x = 200
     print(f'I just changed X to {x} locally')


X is 50
I just changed X to 200 locally


So we get 50 for X although we changed it’s value to 200, it’s because assignment happens only inside local namespace (inside this function), it’not going to affect any variable outside function itself (higher scope).

If we need to “override” global variable we can do it in following way:

we declared global x variable global x, so function will tell python: go to namespace, jump to the global level and get x value, then assign new value to that global variable locallyx = 'new value' and apply changes on global level.

x =  50

def func():
     global x

     print(f'X is {x}')
     # Local reassignment on a global variable 
     x = 'new value'
     print(f'I just locally changed global X to {x}')

X is 50
I just locally changed global X to new value
new value

Above approach is potentially dangerous because we change global variable value so safer solution would be to assign output of function to global variable, without changing it:

x =  50

def func(x):
     print(f'X is {x}')
     # Local reassignment 
     x = 'new value'
     print(f'I just locally changed global X to {x}')
     return x

x = func(x)
X is 50
I just locally changed global X to new value
new value

Related posts:

Booleans are operators used to express True or False statements, used for performing comparations.Needs to be capitalized True is not equal to true and False is not equal to false.None used to define null value or no value at all.

If elif and else statements

if some_condition: 

   # execute some code 

elif some_other_condition: 

   # execute_some_other_code 


   # do something else


# print response based on input code

code = 'CA' 

if code == 'CA': 

  print("CA is California") 

elif code == 'CO': 

  print("CO is Colorado") 

elif code == 'CT': 

  print("CT is Connecticut") 


  print("Invalid. Please enter a valid state code that starts with letter C") 

For Loops

We can iterate over every element in many objects in Ptyhon. Executing block of code for every iteration is possible using for loops.Bellow code will print list value (1,2,3).Item_name is arbitrary variable, it represents values in my_iterable list.For every value (item_name) in my_iterable list, print that value.


my_iterable = [1,2,3] 

for item_name in my_iterable: 


Getting dictionary key pairs

d = {'k1':1,'k2':2,'k3':3} 

for item in d.items(): 


 ('k1', 1) 

('k2', 2) 

('k3', 3) 



# getting values 
for item in d.values(): 




# another way  

for key,value in d.items(): 

while loops executes a block of code while some conditions remains True.

while some_boolean_condition: 

   #do something 

While will execute until x is less than 5, otherwise, it will print “X is not less than 5”

x = 0 

while x < 5:
    print(f'The current value of x is {x}') 
    x = x + 1 
    print("X is not less than 5")    

The current value of x is 0 
The current value of x is 1 
The current value of x is 2 
The current value of x is 3 
The current value of x is 4 
X is not less than 5 

break,continue and pass statements.

break: Breaks out of the current loops

continue: goes to the top of cuttent loops

pass: does noting at all (prevents errors)

Bellow is example for pass

x = [1,2,3] 

    for item in x: 
    # nothing 
  IndentationError: expected an indented block 

# adding pass will prevent syntax error and won't do anything else

x = [1,2,3] 
  for item in x: 
     # nothing 



In below examplw,when for loop finds ‘e’ character, it will simply go back at the begging of the loop, it won’t process ‘e’ character.

string = 'Hello' 
for letter in string: 
   if letter == 'e': 

Break will simple stop executing code when it faces ‘e’ character.

string = 'Hello' 
for letter in string: 
   if letter == 'e': 

Range function prints number in specified range except last number (10 in this case)

a = list(range(1,10))
print (a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

range function includes another parameter:step.

The step is a difference between each number in the result.

for num in range(3,11,2):

List comprehension is an other way how to iterate through list instead of for loop

# for loop
my_string = 'hello'
my_list = []
for letter in my_string:
    if 'l' in letter:

# output

# List comprehension

['True' if 'l' in letter else 'False' for letter in my_string] 

Enumerate function creates index of items in for loop iteration for every location in variable

word = "abcde" 

for item in enumerate(word): 
(0, 'a') 

(1, 'b') 

(2, 'c') 

(3, 'd') 

(4, 'e') 

zip function zips 2 or more lists returns list of tuples
(pairs up one element in one list with element in other list at same index )

mylist1 = [1,2,3] 
mylist2 = ['a','b','c']

for item in zip(mylist1,mylist2):

(1, 'a')
(2, 'b')
(3, 'c'

If 2 lists are not even, zip returns pair for shortest list

mylist1 = [1,2,3,4,5,6]
mylist2 = ['a','b','c']

for item in zip(mylist1,mylist2):

(1, 'a')
(2, 'b')
(3, 'c')

We can convert tuples to list using zip

[(1, 'a'), (2, 'b'), (3, 'c')]

in operator – checks if statement is true or false

# check if x is in list 

'x' in [1,2,3]

'x' in ['x','y','z']

# check if a is in string 

'a' in 'a word'

# check if mykey is in dictionary 

'mykey' in {'mykey':345}

d = {'mykey':345}
345 in d.values ()
345 in d.keys()
345 in d.items()

prompt user for input using string

a = input('Enter something')

# input as number

number = input("Enter a number")


Functions allows creating block of code that can be executed multiple times without need to rewrite block of code.
Return keyword sends back function results, so we can assign this output to variable.

def function_name():
   return ("Hello")

Functions output can be assigned to variables.

output = function_name()



Add parameter to function.

def printme( str ):
    "This prints a passed string into this function"
    return str

printme("I'm first call to user defined function!")

*args and **kwargs

def myfunc(a,b):
    return sum((a,b)) 


TypeError: myfunc() takes 2 positional arguments but 3 were given

If, in above function, we supplied more parametes than needed, then we get error.To enable function to take arbitrary number of paramters we can use *args, and specify as many parameters as we want.
Input parameters are treated as tuple (a,b,c….).

def myfunc(*args):
    return sum(args)

**kwargs creates argument of keypairs, it returns dictionary, and accepts named arguments.In next example,if user passes other argument than city, it won’t be returned but also won’t throw an error.

def myfunc(**kwargs):
    if 'city' in kwargs:
        return ('My favorite city is  {}'.format(kwargs['city']))
        return ("Didn't find any city")    

myfunc(city = 'Zemoon',river = 'Danube')

'My favorite city is  Zemoon'

Map function

passes every single element of list to function, so instead of running custom function multiple times for every string in list, map simple passes every string to our function in “one go”

In this example function will print “EVEN” for string whose lenght is even number, othervise, it will print first letter of non-evcen string.

def splicer(mystring):
    if len(mystring)%2 == 0:
        return 'EVEN'
        return mystring[0]

Now, we can use map to call splicer function and it’s parameter (names)

names = ['Andy','Eve','Sally']

for item in map(splicer,names):

filter function returns an iterator were the items are filtered through a function to test if the item is accepted or not (True) This function accepts numbers, and if input parameter is less than 18, it returns False, othervise, returns True

def myFunc(x):
  if x < 18:
    return False
    return True

Filter function, will iterate through all elemets in ages list and will return only values which are True.

ages = [5, 12, 17, 18, 24, 32]

adults = filter(myFunc, ages)

for x in adults:


Lambda is function that’s defined without name While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Here is equivalet of above myFunc function.

ages = [5, 12, 17, 18, 24, 32]

adults = list(map(lambda x: True if (x > 18) else False,ages))


[False, False, False, False, True, True]

To print only values x>18, again we’l use filter function.

adults = list(filter(lambda x: True if (x > 18) else False,ages))


[24, 32]

return first character of string

names = ['Andy', 'Eve', 'Sally']
first_letter = list(map(lambda x:x[0], names))
['A', 'E', 'S']

Related posts:


Get current directory path and list files in it:

import os

dirpath = os.getcwd()
files = [ f for f in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath,f)) ] 
print('Files:{f} in {d}'.format(f = files ,d = dirpath)) 

# change directory to dirpath 

File modes:

‘r’ – read only

‘w’ – write (will overwrite file or create new)

‘a’ – append (add new lines in file)

‘r+’ – reading and writing

‘w+’ – writing and reading (overwrites exiting files or creates a new one)

# Write to file 

file1 = open("myfile.txt","w")  
file1.write("This is Delhi\nThis is Paris\nThis is London\n") 

# read file 

file1 = open("myfile.txt","r")  

In above examples we need to manually close files using close() method.

Using “with” directives files are automatically closed after writing/reading

# read file and automatically close file  

with open('myfile.txt') as my_file: 
    content = 

# write to file 
with open('myfile.txt', 'w') as my_file: 
  my_file.write("This is Delhi\nThis is Paris\nThis is London\n") 

# append new line to file 
with open('myfile.txt', 'a') as my_file: 
  my_file.write("This is Zemoon\n")