Showing posts with label Scripting. Show all posts
Showing posts with label Scripting. Show all posts

Monday, February 1, 2021

Encrypt and Decrypt your password in your Powershell script.


Powershell is not a precompiled type of language.  So therefore, anyone can read the contents of the script.  What if you need to use a password to have the script access certain resources?  You can always encrypt your password as a secured string and then decrypt it at runtime.  First you will need to encrypt your password using the code below.

$password = Read-Host -Prompt 'Enter your password to encrypt' -AsSecureString

Then, you will need to dump the output of the secure string into an xml file where you powershell script will call at runtime and decrypt.

$password | Export-Clixml -Path 'C:\securepassword.xml'

You can see that the contents of the file it create, securepassword.xml, has your password in encrypted format.

Next, have you powershell call that file and decrypt it.

$password = Import-CliXml -Path 'c:\securepassword.xml'
$plain_password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
write-host $plain_password

One caveat is that you must run the Import-CliXml command as the same user you use to encrypt the password.

Monday, April 6, 2020

Create folders from a text file in Powershell with modified date.


$folders = import-csv C:\mycsvfile.csv
cd myfolder

foreach ($f in $folders)
{
     mkdir $f.name
     $path = "C:\myfolder\"+$f.name
     $temp = Get-Item $path
     $temp.LastWriteTime = $f.configvalue
}

Note:  the csv file has to have a column called 'name' to powershell to identify the column.



Thursday, July 12, 2018

How to clear your variables in Powershell.


After running a Powershell command with a variable, the contents in that variable will stay in memory unless its cleared or overwritten to.  The command below is how to clear it from memory.  This helps when you're writing and testing a script to make sure you get accurate results and not results from stale memory in variables.

Remove-Variable * -ErrorAction SilentlyContinue

Power on a batch of VM's using Powershell


If you have a list of vm's and you need it to be powered on, the script below will help you do that.  To give the storage system air to breathe and not cause a boot storm, it powers on a VM every 2 seconds and waits 5 minutes after ever 50 VM is powered on.

Import-Module vmware.vimautomation.core
Remove-Variable * -ErrorAction SilentlyContinue
$vcenter = "hostname of vCenter or ESX host"
connect-viserver $vcenter
$count = 0
$csvfile = import-csv "Path to csv file"
foreach($vm in $csvfile)
{
    $vm_info = Get-VM -Name $vm.VMName   #VMName refers to column header in the  csv file.
    if ($vm_info.PowerState -eq "PoweredOff")
    {
        Write-Host "Powering on "$vm_info.Name
        $poweron = Get-VM $vm_info.Name | Start-VM -Confirm:$false
        Sleep 2             #power on a vm every 2 seconds.
        $count++
        if($count -eq 50)   #powers on 50 vm's then waits for 5 minutes for  storage to breathe.
        {
            Sleep 300
            $count = 0
        }
    }
}

Tuesday, July 3, 2018

Power on a batch of virtual machines in a csv file using PowerCLI.

Use the following PowerCLI script to power on a list of Virtual Machines from a CSV file.

import-module vmware.vimautomation.core

$vcenter = <my vCenter server>
connect-viserver $vcenter
$allvms = import-csv RVTools_tabvInfo.csv

foreach ($strNewVMName in $allvms)
{   
        #gets all the VM's properties.  We're interested in the PowerState  Property.
        $vmdata = Get-view -ViewType VirtualMachine -Filter @{"name" =  $strNewVMName.vm}  #vm is the column header name in the csv on the first line.
        #if the PowerState is not PoweredOn, then power it on.
        if ($vmdata.Runtime.PowerState -ne "PoweredOn")
        {
            Write-Host "Powering on "$strNewVMName.vm
            Start-VM -VM $strNewVMName.vm
            Sleep 2
        }
}

Wednesday, May 2, 2018

Change Network Failover Detection Policy on vSwitches and portgroups.



Need to change the NetworkFailoverDetectionPolicy for all your vSwithes and portgroups?  The following script traverses all clusters and host to check the NetworkFailoverDetectionPolicy for Beacon Probing.  If its Beacon Probing, change it to Link Status.

#import-module VMware.VimAutomation.Core
#Connect-VIServer -Server vcenter_hostname
#uncomment for testing
#$vmhosts = "hostname1","hostname2"
 
#uncomment for live run
#get the hostnames of all the hosts in every cluster
$vmhosts = get-cluster | get-vmhost | select name
foreach($vmhost in $vmhosts)
{
    #Gets all the vSwitch names that has beacon probing set on the host.
    $switch_policy = Get-VirtualSwitch -VMHost $vmhost.Name | where {$_.Name -ne "vSwitchiDRACvusb"} | Get-NicTeamingPolicy | Where-Object {$_.NetworkFailoverDetectionPolicy -eq "BeaconProbing"} | select -ExpandProperty VirtualSwitch # | select VirtualSwitch | format-wide
    if ($switch_policy)
    {
        foreach ($switch in $switch_policy)
        {
            $vs = Get-VirtualSwitch -VMHost $vmhost.Name -Name $switch
            Get-NicTeamingPolicy -VirtualSwitch $vs | Set-NicTeamingPolicy -NetworkFailoverDetectionPolicy LinkStatus
        }
    }
 
    #Gets all the port group names that has beacon probing set on the host.
    $portgroup_policy = Get-VirtualPortGroup -VMHost $vmhost | Get-NicTeamingPolicy | Where-Object {$_.NetworkFailoverDetectionPolicy -eq "BeaconProbing"} | select -ExpandProperty VirtualPortGroup
    if ($portgroup_policy)
    {
        foreach ($p in $portgroup_policy)
        {
            #Sets the nicteamingpolicy from the host and its portgroup.
            $vpg = Get-VirtualPortGroup -VMHost $vmhost.Name -Name $p
            Get-NicTeamingPolicy -VirtualPortGroup $vpg | Set-NicTeamingPolicy -NetworkFailoverDetectionPolicy LinkStatus
        }
    }
}

Tuesday, January 9, 2018

Add local printer via powershell

add-printerport -name 'printer_name' -printerhostaddress '192.168.0.1'
add-printerdriver -Name 'HP LaserJet 4200/4300 PCL6 Class Driver'
add-printer -Name 'printer_name' -DriverName 'HP LaserJet 4200/4300 PCL6 Class Driver' -PortName 'printer_name'



Friday, January 5, 2018

Powershell: Check if a registry key exist.

This script traverse through an OU and get all the computer names and check to see if "CryptoLocker_0388" key exists.
If it does, then that machine has been infected by the CryptoLocker virus.

$ou=[ADSI]"LDAP://path_to_organizational_unit"

foreach($childin$ou.psbase.Children)
{
   if($child.ObjectCategory-like'*computer*')
    {
          $line=$child.Name

       try
             {
               # Test-Connection -ComputerName $line -Count 1
               $reg=[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('CurrentUser',$line)
               $regkey=$reg.OpenSubkey("SOFTWARE\\CryptoLocker_0388")
               if(!$regkey)
                            {
                  write-host$line-----"Key Not Found"
                }
               else
                          {
                  write-host$line-----"Key Found"
                }
        }
       catch
             {
               write-host$line-----"Offline"
        }
    }
}

Tarball an entire Linux system

#!/bin/bash
#Version: 1.0
#Description:  Checks for a destination mount directory.  Mounts it if it does not exist, the backs up the server to the mount directory.

mountdir="<mount directory>"
servername="<servername>"
exclusions="--exclude=/mnt --exclude=/proc --exclude=/lost+found --exclude=/tmp --exclude=/media --exclude=/sys --exclude=/dev --exclude=/run --exclude=/var/cache"

if [ -d $mountdir ]; then
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
else
     sudo mount -t cifs -o username=moatisuser,password=moatisuser,rw \\\\fw24\\ata_1 /mnt/fw24
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
fi

Write to a file in CSharp

Quick and dirty way to write to a file in C#.

StreamWriter log = new StreamWriter(@c:\log.txt);
log.WriteLine(ErrorMessage);
log.WriteLine();
log.Close();

test test

Tarball an entire Linux system

#!/bin/bash
#Version: 1.0
#Description:  Checks for a destination mount directory.  Mounts it if it does not exist, the backs up the server to the mount directory.

mountdir="<mount directory>"
servername="<servername>"
exclusions="--exclude=/mnt --exclude=/proc --exclude=/lost+found --exclude=/tmp --exclude=/media --exclude=/sys --exclude=/dev --exclude=/run --exclude=/var/cache"

if [ -d $mountdir ]; then
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
else
     sudo mount -t cifs -o username=moatisuser,password=moatisuser,rw \\\\fw24\\ata_1 /mnt/fw24
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
fi

Write to a file in CSharp

Quick and dirty way to write to a file in C#.

StreamWriter log = new StreamWriter(@c:\log.txt);
log.WriteLine(ErrorMessage);
log.WriteLine();
log.Close();

test test

Tarball an entire Linux system

#!/bin/bash
#Version: 1.0
#Description:  Checks for a destination mount directory.  Mounts it if it does not exist, the backs up the server to the mount directory.

mountdir="<mount directory>"
servername="<servername>"
exclusions="--exclude=/mnt --exclude=/proc --exclude=/lost+found --exclude=/tmp --exclude=/media --exclude=/sys --exclude=/dev --exclude=/run --exclude=/var/cache"

if [ -d $mountdir ]; then
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
else
     sudo mount -t cifs -o username=moatisuser,password=moatisuser,rw \\\\fw24\\ata_1 /mnt/fw24
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
fi

Write to a file in CSharp

Quick and dirty way to write to a file in C#.

StreamWriter log = new StreamWriter(@c:\log.txt);
log.WriteLine(ErrorMessage);
log.WriteLine();
log.Close();

test test

Tarball an entire Linux system

#!/bin/bash
#Version: 1.0
#Description:  Checks for a destination mount directory.  Mounts it if it does not exist, the backs up the server to the mount directory.

mountdir="<mount directory>"
servername="<servername>"
exclusions="--exclude=/mnt --exclude=/proc --exclude=/lost+found --exclude=/tmp --exclude=/media --exclude=/sys --exclude=/dev --exclude=/run --exclude=/var/cache"

if [ -d $mountdir ]; then
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
else
     sudo mount -t cifs -o username=moatisuser,password=moatisuser,rw \\\\fw24\\ata_1 /mnt/fw24
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
fi

Write to a file in CSharp

Quick and dirty way to write to a file in C#.

StreamWriter log = new StreamWriter(@c:\log.txt);
log.WriteLine(ErrorMessage);
log.WriteLine();
log.Close();

test test

Wednesday, January 3, 2018

Get all properties of the file in powershell.

 Get-Item -Path c:\myfile.txt | format-list -Property * -Force
http://ift.tt/2CBzkBe

Tuesday, January 2, 2018

Write to a file in CSharp

Quick and dirty way to write to a file in C#.

StreamWriter log = new StreamWriter(@c:\log.txt);
log.WriteLine(ErrorMessage);
log.WriteLine();
log.Close();

Tarball an entire Linux system

#!/bin/bash
#Version: 1.0
#Description:  Checks for a destination mount directory.  Mounts it if it does not exist, the backs up the server to the mount directory.

mountdir="<mount directory>"
servername="<servername>"
exclusions="--exclude=/mnt --exclude=/proc --exclude=/lost+found --exclude=/tmp --exclude=/media --exclude=/sys --exclude=/dev --exclude=/run --exclude=/var/cache"

if [ -d $mountdir ]; then
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
else
     sudo mount -t cifs -o username=moatisuser,password=moatisuser,rw \\\\fw24\\ata_1 /mnt/fw24
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
fi

Wednesday, September 6, 2017

Add local printer via powershell

add-printerport -name 'hn-check' -printerhostaddress '192.168.0.1'

add-printerdriver -Name 'HP LaserJet 4200/4300 PCL6 Class Driver'

add-printer -Name 'hn-check' -DriverName 'HP LaserJet 4200/4300 PCL6 Class Driver' -PortName 'hn-check'