Thursday, January 18, 2018

Decrypt Files from QNAP with OpenSSL

To decrypt files that was encrypted on a QNAP, use the following command.

From the Linux terminal:

    Decrypt one file
        openssl enc -d -aes-256-cbc -k <decrypt password> -in filename.jpg -out filename.jpg

    Decrypt multiple files in a folder.
        for f in * ; do [ -f $f ] && openssl enc -d -aes-256-cbc -k <decrypt password> -in $f -out _$f;


Export a Sharepoint list to a csv using C#.

Below is the code to export a Sharepoint List to a CSV file using C#.NET

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.IO;

namespace export_sharepoint
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "<Site URL>" ;

            using (SPSite oSite = new SPSite(url))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPList oList = oWeb.Lists["<List Name>" ];

                    foreach (SPListItem oItem in oList.Items)
                    {
                         FileStream fs = new FileStream ( "C:\\Documents and Settings\\administrator.domain\\Desktop\\sites.txt", FileMode.Append, FileAccess.Write, FileShare .Read);
                         StreamWriter writer = new StreamWriter(fs);
                        // Access each item in the list... 
                        writer.Write(oItem[ "Site ID"]);
                        writer.Write( ",");
                        writer.Write(oItem[ "Column Name"]);
                        writer.Write( ",");

                        writer.Close();
                        fs.Close();
                    }

                }
            } 
        }
    }

Create a CIFS share on a Netapp from the command line.


cifs shares -add "SHARE NAME" "/vol/fw_volume1/share location/"
cifs access "AD GROUP" "ROLE_ETC" "Full Control"
cifs access -delete "Everyone"

Saturday, January 13, 2018

Finally got a Sega Saturn. Derby Stallion edition!

Sold a Neo Geo Cyberlip and a Nintendo Game and Watch to buy this console.  Wanted this console for a long time so I thought why not go for the Derby Stallion edition!  This console is awesome looking.  It's looks brand spanking new too.  The game inside is Battle Garegga!


Thursday, January 11, 2018

Reset Local Administrator Password

Here's a way to reset the local Administrator password in Windows 2008.

  1. Boot up a WIndows installer CD.
  2. Press F8 at the Local Deployment Wizard
  3. Type in 
    1. move d:\windows\system32\utilman.exe d:\
    2. copy d:\windows\system32\cmd.exe d:\windows\system32\utilman.exe
  4. Boot to normal Window.  At the log in, click on "Ease of Access" button at the bottom left.
  5. Type in:
    1. net user administrator /active:yes
    2. net user administrator <new password>



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'



Disable SSL check on GIT

When you connect to a GIT repository, it may fail due to
Start GIT Bash
Run the following command.
     git config --global http.sslVerify false


Monday, January 8, 2018

Setting up Redhat Enterprise Virtualization Manager (RHEVM)

Steps to set up Redhat Enterprise Virtualization Manager.

1.  Install Redhat Enterprise Linux 

2.  Register to the Redhat Network
          #>Subscription-manager register
                    Type in your rhn account info.

3.  Attach all the subscriptions available to the version of Redhat Linux you're running.
          #>Subscription-manager attach --auto

4.  Install yum-config-manager utility
          #>yum install yum-utils

5.  Run yum-config-manager to add Redhat Enterprise Virtualization Manager package to the subscription.
          #>yum-config-manager --enable rhel-6-server-rhevm-3.4-rpms

6.  Run yum-config-manager to add JBoss package to the subscription.
          #>yum-config-manager --enable jb-eap-6-for-rhel-6-server-rpms

7.  Install JBoss
          #>yum install jbossas-standalone

8.  Downgrade sos package (not sure why this is required but it was complaining about the sos version is too new)
          #>yum remove sos-3.2-28.el6.noarch
          #>yum install sos-2.2-68.el6.noarch

9.  Install rhevm
          #>yum install rhevm

10. Install rhevm reporting
          #>yum install rhevm-reports

11. Run the setup wizard.
          #>engine-setup

12. Create ISO domain (Use to store .iso files so you can build the vm)

13. Upload to the ISO domain
          #>rhevm-iso-uploader --iso-domain=<ISO domain name> upload myfile.iso --insecure

14.  To be able to mount the windows drivers in the vm, run the following.
          #>yum install virtio-win
          #>yum install libvirt-devel
          #>yum install libvirt
          #>yum install virt-install




Disable SSL on VMWare Converter.

Disabling SSL on VMWare converter can result in faster conversion speeds.

Go to 
C:\ProgramData\VMware\VMware vCenter Converter Standalone\converter-worker.xml
Change   
     <useSsl>true</useSsl>
to
     <useSsl>false</useSsl>



Amazon S3 storage used calculation.

From the reports exported from Amazon S3, the value is in "TimedStorage-BytesHrs"  It's not very useful if you're doing cost analysis.  
Below is the formula to convert it to a usable GB-Months format.

TimedStorage-BytesHrs * 30 * (1 GB/ 1,073,741,824) * (1 Month/744) = GB-Months.

GB-Months x .03 = Total Cost per month.

vCenter database queries

Log into SQL where the vCenter database is on and run the following query:

How many VMs have been deployed.

    select CREATE_TIME,VM_NAME from VPX_EVENT where EVENT_TYPE='vim.event.VMBeingDeployedEvent' and CREATE_TIME>='2012-01-01' and CREATE_TIME<='2013-01-01' and VM_NAME     like 'searchname%' and VM_NAME not like 'vm_name%' and VM_NAME not like 'vm_name%'and VM_NAME not like 'vm_name%' and VM_NAME not like 'vm_name%'    select CREATE_TIME, VM_NAME from VPX_EVENT where EVENT_TYPE= 'vim.event.VMRemovedEvent' and CREATE_TIME >= '2012-01-01' and CREATE_TIME <= '2013-01-01'    select CREATE_TIME, VM_NAME from VPX_EVENT where EVENT_TYPE= 'vim.event.VMCreatedEvent' and CREATE_TIME >= '2012-01-01' and CREATE_TIME <= '2013-01-01'

Memory usage for the year.

    select sample_time, stat_name, stat_value from VPXV_HIST_STAT_YEARLY where stat_group='mem' and stat_name='usage'

Restore bare metal with SCDPM

Bare Metal Recovery with System Center Data Protection Manager.

     - Boot from Windows DVD
     - Click on "Repair Your Computer" (instead of the "Install Now" link)
     - Click on the "Windows Complete PC Restore" option
     - Click "Restore a Different Backup option"
     - Enter the path to the second share
     - Select the backup from the list and click Next
     - Select Windows format and repartition disk.


Mount CIFS share in Linux

mount -t cifs //netbiosname/sharename /media/sharename -o username=username,password=password,uid=linuxusername,iocharset=utf8,umask=664,rw

Friday, January 5, 2018

Reset vmware ESX evaluation license.

VMWare ESXi license expires in 60 days.  You can reset that 60 days by doing the following.

-ssh into the ESXi host.
-rm -f /etc/vmware/vmware.lic /etc/vmware/license.cfg
-reboot

SQL does not allow modifying of table.

If you've dealt with MS SQL before, by default, it does not allow you to modify a table without you dropping it and recreating it. It's kind of annoying.   Here's a way to get around it.  Do this at your own risk of corrupting your database.

-Go to the Tools menu -> Options
-Click on "Designers" on the left menu tree
-Uncheck "Prevent saving changes that require table re-creation"



VMWare - Power ON a vm from the command line

To power on a virtual machine from the command line:

-List the inventory ID of the virtual machine with the command:
               vim-cmd vmsvc/getallvms |grep <vm name>
               Note: The first column of the output shows the vmid.

-Check the power state of the virtual machine with the command:
               vim-cmd vmsvc/power.getstate <vmid>

-Power-on the virtual machine with the command:
               vim-cmd vmsvc/power.on <vmid>

How to use ImageX

imagex /capture <source disk> <destination disk>:\<wim filename> "description"
imagex /capture d: z:\c.wim "wimtest"

DISKPART>list disk
DISKPART>select disk (id)
DISKPART>online disk (if the disk is not online)
DISKPART>clean
DISKPART>convert mbr (or gpt)
DISKPART>create partition primary
DISKPART>select part 1
DISKPART>active (if this is the boot partition)
DISKPART>format fs=ntfs label=(name) quick
DISKPART>assign letter c:
DISKPART>list volume
DISKPART>exit

X:\Tools>net use n: \\server\share /user:Domain\username "password"
X:\Tools>imagex /apply <source disk>:\<wim filename> "samedescription" c:
X:\bcdboot c:\windows
chkdsk c: /f /v /x

1.  go to windows aik tools directory and run "copype.cmd x86 c:\winpe" to create winpe structure to c:\winpe.

2.  mount the wim file on c:\winpe\winpe.
                      "imagex /mountrw d:\boot.wim 1 d:\image.mount"

3.  edit image........
4.  unmount the wim file and commit changes.
                      "imagex /umount /commit d:\image.mount"

5.  copy the wim file to winpe structure created in step 1.  c:\winpe\ISO\sources

6.  create an iso from image.
                      "oscdimg -n -bc:\winpe\iso\boot\etfsboot.com c:\winpe\iso d:\ghost.iso"

Get formatted date in a batch file.

SET mm=%DATE:~4,2%   -  This moves 4 positions and gets the next 2 positions.
SET dd=%DATE:~7,2%     -  This moves 7 positions and gets the next 2 positions.
SET yyyy=%DATE:~10,4% -  This moves 10 positions and gets the next 4 positions.

Output it in a script
%yyyy%.%mm%.%dd%

VSS Error while running system state/bare metal restore backup using SCDPM.

When running a system state/bare metal restore backup using SCDPM, you may encounter a VSS error leading to a protection point inconsistency.  This is due to automounter being disabled and the system restore partition being offline in disk management.  The cause of this may be a third party snapshot tool that leverages VSS such as Netapp's SnapDrive.  In order to get SCDPM to do a system state/bare metal restore, you will need to do the following steps.  Note: this works for VMWare converter as well if you're getting

System Partition is offline.  No drive letters

1.  log into the server you want to protect.
2.  open a command prompt
3.  type "diskpart"
4.  type "automount" to display the current state of automount.  If its disabled, open another command prompt and run "diskpart> automount enable" to enable it.
5.  in diskpart, get a list of volumes by typing "list volume".
6.  find the system restore partition and note down the volume number.
7.  type "select volume (x)" where x is the volume number of the system restore partition.
8.  type "online volume" to bring the volume online.
9.  rerun the SCDPM consistency check and it should be successful.

Before

After (Notice "System Reserved" volume is labeled)

Get network info from vmnic using esxcli


Display driver info for network adapter
    esxcli network nic get -n vmnicX

Display network statistics (bytes transferred, errors, packets transferred)
    esxcli network nic stats get -n vmnicX

GIT usage

git clone http://ift.tt/2CJipdp


  • Get the newest stuff from gitlab repository (sync your local repo with the “origin”):
    • git pull
  • Add it to “staging” in the local repo
    • git add "filename"
  • Commit the change in the local repo
    • git commit -m “whatever was changed”
  • Push changes “up” to gitlab server
    • git push origin master
  • Verify commit shows up in the web interface of the gitlab server
  

ESXTOP quick troubleshooting overview


vSAN 6.x cluster shut down and power on procedures

Shutting down the vSAN 6.x cluster

To shut down the vSAN cluster:
  1. Shut down all virtual machines running on the vSAN Cluster.

    Note:The vCenter Server virtual machine must be shut down at the end.

  2. Note the host that your vCenter Server virtual machine resides on. 

    Note: VMware recommends to migrate the vCenter Server virtual machine to the first ESXi host, so you can easily find the virtual machine when powering on your vSAN cluster again.

  3. Ensure that there are no vSAN components currently resynching. For more information, see the Monitor the Resynchronization Tasks in the Virtual SAN Cluster section in the Administering VMware Virtual SAN.
  4. Shut down the vCenter Server virtual machine. This makes the vSphere Web Client unavailable.
  5. Connect to the ESXi host shell. For more information, see  Using ESXi Shell in ESXi 5.x and 6.0 (2004746).
  6. Place all ESXi hosts into Maintenance Mode. This operation must be done using one of the CLI methods that supports setting the vSAN mode when entering Maintenance Mode. You can either do this by logging directly in to the ESXi Shell and running the ESXCLI command locally or you can invoke this operation on a remote system using ESXCLI.
  7. Run this ESXCLI command and ensure that the No Action option is selected when you enter Maintenance Mode:

    # esxcli system maintenanceMode set -e true -m noAction

  8. Shut down all ESXi hosts. You can log in to each ESXi hosts using either the vSphere Client or the ESXi shell. You can also perform this operation remotely using a vSphere API, such as PowerCLI.




Powering on the vSAN 6.x cluster

To power on your vSAN cluster:
  1. Boot up the ESXi hosts through remote console session or physically.
  2. Connect to the shell of each ESXi host and run this command to exit maintenance mode:

    # esxcli system maintenanceMode set -e false

  3. Locate your vCenter virtual machine and power it on using a vSphere client connection directly to the host.
  4. Using the vSphere Client, connect to the ESXi host that contains your vCenter virtual machine. Power on your vCenter Server

    Note: This should be on the first ESXi host, If you moved this virtual machine to that host in step 2 of the shut down procedure.

  5. Connect to your vCenter Server using the vSphere Web Client.

    Note: It may take a few minutes for vCenter Server to become available again

  6. Do a quick health check on the vSAN cluster. Check for network partitions and resyncing components. For more information, see the Monitoring Virtual SAN section of the Administering VMware Virtual SAN.
  7. Power on the remaining virtual machines in the vSAN cluster.


Power off a Virtual SAN Cluster

Power off a Virtual SAN Cluster

Prerequisites
If the vCenter Server VM is running on the Virtual SAN cluster, migrate the VM to the first host, or record the host where it is currently running.
Procedure

1
Power off all virtual machines that are running on the Virtual SAN cluster.
The vCenter Server virtual machine must be powered off last.
2
Place all ESXi hosts that compose the cluster in maintenance mode.
Run the esxcli command to set the Virtual SAN mode for entering the maintenance state.
esxcli system maintenanceMode set -e true -m noAction
3
Power off the ESXi hosts.


Bare metal recovery for Windows 2012 from a Windows Server Backup image.

Bare metal recovery for Windows 2012 from a Windows Server Backup image.

  1. Create an ISO of the backup image and mount it to VM.
  2. Install a fresh OS
  3. Install vmware tools.
  4. Reboot into Windows install ISO.
  5. Select System Image Recovery
  6. Select the command prompt.
  7. Type in "start /w wpeinit"  to enable the network and get an ip.
  8. Exit the command prompt.
  9. Select System Image Recovery.
  10. Select the Operating System.
  11. Select the "Select a system image" radio button and next.
  12. Click on the "Advanced.." button.
  13. Click on "Search for a system image on the network"
  14. Type in the path of the backup.  Make sure its the path that has the "WindowsImageBackup" folder or it will not detect an available image.
  15. Type in your credentials.
  16. Select the backup from the list and click Next.


Update user home directory with Powershell

Import-Module ActiveDirectory
$users = Get-ADUser -SearchBase "<Path to Organizational Unit" -Filter * -Properties *

ForEach ($user in $users)
{
$sam = $user. SamAccountName
Set-ADuser -Identity $sam -HomeDirectory "\\server\users$\ $sam"

To find a VM with a particular snapshot name

Get-Snapshot -VM VM -Name '<snapshot name>'


Power on/off VM via command line.


Power on a VM
To power on a virtual machine from the command line:
  1. List the inventory ID of the virtual machine with the command:

    vim-cmd vmsvc/getallvms |grep <vm name>

    Note: The first column of the output shows the vmid.

  2. Check the power state of the virtual machine with the command:

    vim-cmd vmsvc/power.getstate <vmid>

  3. Power-on the virtual machine with the command:

    vim-cmd vmsvc/power.on <vmid>

Get all vm's with connected CD rom drives

This is a powercli command to get all the vm's with connected cdrom drive.  

get-cluster | where {$_.Name -eq "SFColo Test & Dev"} | get-vm | where { $_ | get-cddrive | where { $_.ConnectionState.Connected -eq "true" } } | select Name


Get VMX and VMWare tools version and export to CSV

To get the VMware tools versions and export it to a csv called vmtools.csv

get-vm | where {$_.powerstate -ne "PoweredOff" } | where {$_.Guest.ToolsVersionStatus -ne "guestToolsCurrent"} | % { get-view $_.id } | select Name, @{ Name="ToolsVersion"; Expression={$_.config.tools.toolsVersion}}, @{ Name="ToolStatus"; Expression={$_.Guest.ToolsVersionStatus}} | Export-Csv -NoTypeInformation -UseCulture -Path d:\vmtools.csv

VMWare - VCBMounter Command

VCBMounter Command

to mount full vm.
vcbmounter.exe -h vcenter_hostname -u fwvcb -p <password> -r d:\vmbackups\<name> -a name:name_of_vm -t fullvm -m nbd

to umount full vm.
vcbmounter.exe -h vcenter_hostname -u fwvcb -p <password> -U d:\vmbackups\<name>

Disable IPv6 via commands in Windows

get-netadapterbinding
set-NetAdapterBinding -Name “Network Adapter Name” –ComponentID ms_tcpip6 –Enabled $False

new-itemproperty -Path HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters -Name DisabledComponents -PropertyType DWord -Value ffffffff

Reset a slot in Cisco UCS.

- Reset a slot (equivalent to remove power from the blade and reapplying):
     #reset slot x/y (where x = chassis and y = blade or server #)

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

Enable SNMP on ESXi

  1. ssh into the esxi host.
  2. esxcli system snmp set --communities="string name"
  3. esxcli system snmp set --targets="<monitoring server>"@161/"string name","<monitoring server>"@161/"string name"
  4. esxcli system snmp set --enable true
  5. esxcli system snmp test
  6. log into vi client.
  7. find the server and go to the configuration tab.
  8. select Security Profile under Software
  9. select Properties under Firewall
  10. find SNMP server and click on the Options button.
  11. start the service.


esxcli system snmp set --communities="MRTG"
esxcli system snmp set --targets="fwprd-slw-ape1"@161/"MRTG","fwprd-slw-ape2"@161/"MRTG","fwprd-slw-core"@161/"MRTG"
esxcli system snmp set --enable true
esxcli system snmp test


Set up Gnome in Arch Linux

1.  check what type of video card
         lspci | grep VGA
2.  install video driver
         pacman -Syu xf86-video-intel (for intel graphics card), xf86-video-ati (for ati), xf86-video-nv (for nvidia)
3.  install touchpad driver
         pacman -Syu xf86-input-synaptics
4.  install xorg
         pacman -Syu xorg-server
5.  install xorg-xinit
         pacman -Syu xorg-xinit
6.  install gnome and gdm
         pacman -Syu gnome
         pacman -Syu gdm
7.  enable gdm on startup
         systemctl enable gdm

         pacman -Syu gnome-panel
         pacman -Syu gnome-tweak-tool
         pacman -Syu gnome-themes-extras

Setup iptables in Linux

Ubuntu does come with iptables preset like in Fedora. Here's the base set up for iptables.

Add iptable rules.

Block Null Packets
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

Reject Syn-Flood Attack

iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

Reject XMAS/recon packets

iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

Allow custom ports
<here>

Accept Established Connections

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A INPUT -j REJECT iptables -A FORWARD -j REJECT

iptables -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A FORWARD -j REJECT

iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

Use iptables-save to save it to a file.
iptables-save > /etc/iptables.rules

Edit rc.local to import iptables rules during boot up.
iptables-restore < /etc/iptables.rules

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

Base server build with Arch Linux

From usb stick(sdb) to hard drive(sda)

1. boot from usb stick.

2. run cfdisk to partition hard drive (sda)

        a. cfdisk /dev/sda

b. create a root (/) partition - sda1

c. create a swap (swap) partition - sda2

3. format disk to ext4

a. mkfs.ext4 /dev/sda1

b. mkfs.ext4 /dev/sda2

4. make swap

a. mkswap /dev/sda2

5. turn swap on

a. swapon /dev/sda2

6. mount the hard disk.

a. mount /dev/sda1 /mnt

7. install arch linux base

a. pacstrap -i /mnt base

8. generate fstab

a. genfstab -U -p /mnt >> /mnt/etc/fstab

9. chroot into /mnt

a. arch-chroot /mnt

10. set location

a. vi /etc/locale.gen

b. uncomment en_US.UTF-8 UTF-8

11. set hostname

a. echo myservername > /etc/hostname

12. set up network

a. cp /etc/network.d/examples/ethernet-static to /etc/network.d

b. ls /sys/class/net to get the list of interfaces.

c. vi ethernet-static and edit ip/gw info. Change the interface to the correct interface.

d. vi /etc/conf.d/netcfg and point NETWORKS=(ethernet-static)

For DHCP:

a. systemctl enable dhcpcd@eth0

b. systemctl start dhcpcd@eth0

13. enable netcfg service

a. systemctl enable netcfg.service

14. change password

a. passwd

15. Install grub bootloader

a. pacman -S syslinux

b. syslinux-install_update -i -a -m

c. vi /boot/syslinux/syslinux.cfg and change APPEND root-/dev/sda3 ro to the correct boot partition.

d. pacman -S grub-bios

e. grub-install --recheck /dev/sda1

16. exit chroot

17. unmount /mnt

18. reboot and remove the usb stick.

Get Last Backup Field in vCenter with Powershell.

#This is a little Powershell script that gets the last time a vm in the Cluster that it has been backed up.  Emails out if it has not been backed up in 14days.

$daystoalert = 14
$vCenter = "vCenter server name"

add-pssnapin vmware.vimautomation.core
connect-viserver $vCenter
$today_date = get-date

$all_vms = get-cluster "Cluster Name" | get-vm | Sort-Object Name

foreach($vm in $all_vms)
{
    #check $vm for null?
    Try {
        $last_backup_date = $vm. CustomFields.Get_Item( "Last Backup")
        $last_backup_converted = get-date $last_backup_date
        $days_with_no_backups = New-TimeSpan -Start $last_backup_converted .DateTime -End $today_date. DateTime
        if ($days_with_no_backups .Days -gt $daystoalert)
        {
            Write-output " $($vm. Name),$( $days_with_no_backups.Days) "
        }
    }
    Catch {
        # VM was never backed up gets caught in this exception.
        Write-output " $($vm. Name), Never backed up"
    }

Delete files in a folder and subfolders of files based on last access time

Get-ChildItem -path "D:\ftp.archived.logs" -Recurse | Where-Object{$_.LastAccessTime -lt (get-date).AddDays(-90)} | remove-item 

add -whatif at the end of remove-item to show what will get removed.



Enable/Disable SMBv1,2,3 in Windows


Disable form repost on browser refresh

Here's a trick I found to prevent a form repost on browser refresh


        protected void Page_PreRender(object sender, EventArgs e)
        {
                     ViewState["Check_Page_Refresh"] = Session["Check_Page_Refresh"];
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["Check_Page_Refresh"] = DateTime.Now.ToString();
            }
        }

protected void btn_Click(object sender, EventArgs e)
{
if (ViewState["Check_Page_Refresh"].ToString() == Session["Check_Page_Refresh"].ToString())
{
     <your main code you want to execute once on button click here>
}
}

Active Directory authentication using C#

bool authenticated;
using(PrincipalContext pc =newPrincipalContext(ContextType.Domain, domain.ToString()))
{
     authenticated = pc.ValidateCredentials(<user name>,<password>,ContextOptions.Negotiate);
}
if (authenticated)
{

}

Reset vmware ESX evaluation license.

VMWare ESXi license expires in 60 days.  You can reset that 60 days by doing the following.

-ssh into the ESXi host.
-rm -f /etc/vmware/vmware.lic /etc/vmware/license.cfg
-reboot

SQL does not allow modifying of table.

If you've dealt with MS SQL before, by default, it does not allow you to modify a table without you dropping it and recreating it. It's kind of annoying.   Here's a way to get around it.  Do this at your own risk of corrupting your database.

-Go to the Tools menu -> Options
-Click on "Designers" on the left menu tree
-Uncheck "Prevent saving changes that require table re-creation"



VMWare - Power ON a vm from the command line

To power on a virtual machine from the command line:

-List the inventory ID of the virtual machine with the command:
               vim-cmd vmsvc/getallvms |grep <vm name>
               Note: The first column of the output shows the vmid.

-Check the power state of the virtual machine with the command:
               vim-cmd vmsvc/power.getstate <vmid>

-Power-on the virtual machine with the command:
               vim-cmd vmsvc/power.on <vmid>

VSS Error while running system state/bare metal restore backup using SCDPM.

When running a system state/bare metal restore backup using SCDPM, you may encounter a VSS error leading to a protection point inconsistency.  This is due to automounter being disabled and the system restore partition being offline in disk management.  The cause of this may be a third party snapshot tool that leverages VSS such as Netapp's SnapDrive.  In order to get SCDPM to do a system state/bare metal restore, you will need to do the following steps.  Note: this works for VMWare converter as well if you're getting

System Partition is offline.  No drive letters

1.  log into the server you want to protect.
2.  open a command prompt
3.  type "diskpart"
4.  type "automount" to display the current state of automount.  If its disabled, open another command prompt and run "diskpart> automount enable" to enable it.
5.  in diskpart, get a list of volumes by typing "list volume".
6.  find the system restore partition and note down the volume number.
7.  type "select volume (x)" where x is the volume number of the system restore partition.
8.  type "online volume" to bring the volume online.
9.  rerun the SCDPM consistency check and it should be successful.

Before

After (Notice "System Reserved" volume is labeled)

ESXTOP quick troubleshooting overview


Bare metal recovery for Windows 2012 from a Windows Server Backup image.

Bare metal recovery for Windows 2012 from a Windows Server Backup image.

  1. Create an ISO of the backup image and mount it to VM.
  2. Install a fresh OS
  3. Install vmware tools.
  4. Reboot into Windows install ISO.
  5. Select System Image Recovery
  6. Select the command prompt.
  7. Type in "start /w wpeinit"  to enable the network and get an ip.
  8. Exit the command prompt.
  9. Select System Image Recovery.
  10. Select the Operating System.
  11. Select the "Select a system image" radio button and next.
  12. Click on the "Advanced.." button.
  13. Click on "Search for a system image on the network"
  14. Type in the path of the backup.  Make sure its the path that has the "WindowsImageBackup" folder or it will not detect an available image.
  15. Type in your credentials.
  16. Select the backup from the list and click Next.


To find a VM with a particular snapshot name

Get-Snapshot -VM VM -Name '<snapshot name>'


Power on/off VM via command line.


Power on a VM
To power on a virtual machine from the command line:
  1. List the inventory ID of the virtual machine with the command:

    vim-cmd vmsvc/getallvms |grep <vm name>

    Note: The first column of the output shows the vmid.

  2. Check the power state of the virtual machine with the command:

    vim-cmd vmsvc/power.getstate <vmid>

  3. Power-on the virtual machine with the command:

    vim-cmd vmsvc/power.on <vmid>

Get all vm's with connected CD rom drives

This is a powercli command to get all the vm's with connected cdrom drive.  

get-cluster | where {$_.Name -eq "SFColo Test & Dev"} | get-vm | where { $_ | get-cddrive | where { $_.ConnectionState.Connected -eq "true" } } | select Name


Get VMX and VMWare tools version and export to CSV

To get the VMware tools versions and export it to a csv called vmtools.csv

get-vm | where {$_.powerstate -ne "PoweredOff" } | where {$_.Guest.ToolsVersionStatus -ne "guestToolsCurrent"} | % { get-view $_.id } | select Name, @{ Name="ToolsVersion"; Expression={$_.config.tools.toolsVersion}}, @{ Name="ToolStatus"; Expression={$_.Guest.ToolsVersionStatus}} | Export-Csv -NoTypeInformation -UseCulture -Path d:\vmtools.csv

Disable IPv6 via commands in Windows

get-netadapterbinding
set-NetAdapterBinding -Name “Network Adapter Name” –ComponentID ms_tcpip6 –Enabled $False

new-itemproperty -Path HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters -Name DisabledComponents -PropertyType DWord -Value ffffffff

Reset a slot in Cisco UCS.

- Reset a slot (equivalent to remove power from the blade and reapplying):
     #reset slot x/y (where x = chassis and y = blade or server #)

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

Setup iptables in Linux

Ubuntu does come with iptables preset like in Fedora. Here's the base set up for iptables.

Add iptable rules.

Block Null Packets
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

Reject Syn-Flood Attack

iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

Reject XMAS/recon packets

iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

Allow custom ports
<here>

Accept Established Connections

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A INPUT -j REJECT iptables -A FORWARD -j REJECT

iptables -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A FORWARD -j REJECT

iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

Use iptables-save to save it to a file.
iptables-save > /etc/iptables.rules

Edit rc.local to import iptables rules during boot up.
iptables-restore < /etc/iptables.rules

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

Restart Management Agent on ESXi.

Run the following commands to restart the management agent on an ESXi host.
/etc/init.d/hostd restart
/etc/init.d/vpxa restart


Get Last Backup Field in vCenter with Powershell.

#This is a little Powershell script that gets the last time a vm in the Cluster that it has been backed up.  Emails out if it has not been backed up in 14days.

$daystoalert = 14
$vCenter = "vCenter server name"

add-pssnapin vmware.vimautomation.core
connect-viserver $vCenter
$today_date = get-date

$all_vms = get-cluster "Cluster Name" | get-vm | Sort-Object Name

foreach($vm in $all_vms)
{
    #check $vm for null?
    Try {
        $last_backup_date = $vm. CustomFields.Get_Item( "Last Backup")
        $last_backup_converted = get-date $last_backup_date
        $days_with_no_backups = New-TimeSpan -Start $last_backup_converted .DateTime -End $today_date. DateTime
        if ($days_with_no_backups .Days -gt $daystoalert)
        {
            Write-output " $($vm. Name),$( $days_with_no_backups.Days) "
        }
    }
    Catch {
        # VM was never backed up gets caught in this exception.
        Write-output " $($vm. Name), Never backed up"
    }

Delete files in a folder and subfolders of files based on last access time

Get-ChildItem -path "D:\ftp.archived.logs" -Recurse | Where-Object{$_.LastAccessTime -lt (get-date).AddDays(-90)} | remove-item 

add -whatif at the end of remove-item to show what will get removed.



Enable/Disable SMBv1,2,3 in Windows


Disable form repost on browser refresh

Here's a trick I found to prevent a form repost on browser refresh


        protected void Page_PreRender(object sender, EventArgs e)
        {
                     ViewState["Check_Page_Refresh"] = Session["Check_Page_Refresh"];
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["Check_Page_Refresh"] = DateTime.Now.ToString();
            }
        }

protected void btn_Click(object sender, EventArgs e)
{
if (ViewState["Check_Page_Refresh"].ToString() == Session["Check_Page_Refresh"].ToString())
{
     <your main code you want to execute once on button click here>
}
}

Reset vmware ESX evaluation license.

VMWare ESXi license expires in 60 days.  You can reset that 60 days by doing the following.

-ssh into the ESXi host.
-rm -f /etc/vmware/vmware.lic /etc/vmware/license.cfg
-reboot

SQL does not allow modifying of table.

If you've dealt with MS SQL before, by default, it does not allow you to modify a table without you dropping it and recreating it. It's kind of annoying.   Here's a way to get around it.  Do this at your own risk of corrupting your database.

-Go to the Tools menu -> Options
-Click on "Designers" on the left menu tree
-Uncheck "Prevent saving changes that require table re-creation"



VMWare - Power ON a vm from the command line

To power on a virtual machine from the command line:

-List the inventory ID of the virtual machine with the command:
               vim-cmd vmsvc/getallvms |grep <vm name>
               Note: The first column of the output shows the vmid.

-Check the power state of the virtual machine with the command:
               vim-cmd vmsvc/power.getstate <vmid>

-Power-on the virtual machine with the command:
               vim-cmd vmsvc/power.on <vmid>

VSS Error while running system state/bare metal restore backup using SCDPM.

When running a system state/bare metal restore backup using SCDPM, you may encounter a VSS error leading to a protection point inconsistency.  This is due to automounter being disabled and the system restore partition being offline in disk management.  The cause of this may be a third party snapshot tool that leverages VSS such as Netapp's SnapDrive.  In order to get SCDPM to do a system state/bare metal restore, you will need to do the following steps.  Note: this works for VMWare converter as well if you're getting

System Partition is offline.  No drive letters

1.  log into the server you want to protect.
2.  open a command prompt
3.  type "diskpart"
4.  type "automount" to display the current state of automount.  If its disabled, open another command prompt and run "diskpart> automount enable" to enable it.
5.  in diskpart, get a list of volumes by typing "list volume".
6.  find the system restore partition and note down the volume number.
7.  type "select volume (x)" where x is the volume number of the system restore partition.
8.  type "online volume" to bring the volume online.
9.  rerun the SCDPM consistency check and it should be successful.

Before

After (Notice "System Reserved" volume is labeled)

ESXTOP quick troubleshooting overview


Power off a Virtual SAN Cluster

Power off a Virtual SAN Cluster

Prerequisites
If the vCenter Server VM is running on the Virtual SAN cluster, migrate the VM to the first host, or record the host where it is currently running.
Procedure

1
Power off all virtual machines that are running on the Virtual SAN cluster.
The vCenter Server virtual machine must be powered off last.
2
Place all ESXi hosts that compose the cluster in maintenance mode.
Run the esxcli command to set the Virtual SAN mode for entering the maintenance state.
esxcli system maintenanceMode set -e true -m noAction
3
Power off the ESXi hosts.


Bare metal recovery for Windows 2012 from a Windows Server Backup image.

Bare metal recovery for Windows 2012 from a Windows Server Backup image.

  1. Create an ISO of the backup image and mount it to VM.
  2. Install a fresh OS
  3. Install vmware tools.
  4. Reboot into Windows install ISO.
  5. Select System Image Recovery
  6. Select the command prompt.
  7. Type in "start /w wpeinit"  to enable the network and get an ip.
  8. Exit the command prompt.
  9. Select System Image Recovery.
  10. Select the Operating System.
  11. Select the "Select a system image" radio button and next.
  12. Click on the "Advanced.." button.
  13. Click on "Search for a system image on the network"
  14. Type in the path of the backup.  Make sure its the path that has the "WindowsImageBackup" folder or it will not detect an available image.
  15. Type in your credentials.
  16. Select the backup from the list and click Next.


To find a VM with a particular snapshot name

Get-Snapshot -VM VM -Name '<snapshot name>'


Power on/off VM via command line.


Power on a VM
To power on a virtual machine from the command line:
  1. List the inventory ID of the virtual machine with the command:

    vim-cmd vmsvc/getallvms |grep <vm name>

    Note: The first column of the output shows the vmid.

  2. Check the power state of the virtual machine with the command:

    vim-cmd vmsvc/power.getstate <vmid>

  3. Power-on the virtual machine with the command:

    vim-cmd vmsvc/power.on <vmid>

Get all vm's with connected CD rom drives

This is a powercli command to get all the vm's with connected cdrom drive.  

get-cluster | where {$_.Name -eq "SFColo Test & Dev"} | get-vm | where { $_ | get-cddrive | where { $_.ConnectionState.Connected -eq "true" } } | select Name


Get VMX and VMWare tools version and export to CSV

To get the VMware tools versions and export it to a csv called vmtools.csv

get-vm | where {$_.powerstate -ne "PoweredOff" } | where {$_.Guest.ToolsVersionStatus -ne "guestToolsCurrent"} | % { get-view $_.id } | select Name, @{ Name="ToolsVersion"; Expression={$_.config.tools.toolsVersion}}, @{ Name="ToolStatus"; Expression={$_.Guest.ToolsVersionStatus}} | Export-Csv -NoTypeInformation -UseCulture -Path d:\vmtools.csv

Disable IPv6 via commands in Windows

get-netadapterbinding
set-NetAdapterBinding -Name “Network Adapter Name” –ComponentID ms_tcpip6 –Enabled $False

new-itemproperty -Path HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters -Name DisabledComponents -PropertyType DWord -Value ffffffff

Reset a slot in Cisco UCS.

- Reset a slot (equivalent to remove power from the blade and reapplying):
     #reset slot x/y (where x = chassis and y = blade or server #)

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

Setup iptables in Linux

Ubuntu does come with iptables preset like in Fedora. Here's the base set up for iptables.

Add iptable rules.

Block Null Packets
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

Reject Syn-Flood Attack

iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

Reject XMAS/recon packets

iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

Allow custom ports
<here>

Accept Established Connections

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A INPUT -j REJECT iptables -A FORWARD -j REJECT

iptables -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A FORWARD -j REJECT

iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

Use iptables-save to save it to a file.
iptables-save > /etc/iptables.rules

Edit rc.local to import iptables rules during boot up.
iptables-restore < /etc/iptables.rules

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

Get Last Backup Field in vCenter with Powershell.

#This is a little Powershell script that gets the last time a vm in the Cluster that it has been backed up.  Emails out if it has not been backed up in 14days.

$daystoalert = 14
$vCenter = "vCenter server name"

add-pssnapin vmware.vimautomation.core
connect-viserver $vCenter
$today_date = get-date

$all_vms = get-cluster "Cluster Name" | get-vm | Sort-Object Name

foreach($vm in $all_vms)
{
    #check $vm for null?
    Try {
        $last_backup_date = $vm. CustomFields.Get_Item( "Last Backup")
        $last_backup_converted = get-date $last_backup_date
        $days_with_no_backups = New-TimeSpan -Start $last_backup_converted .DateTime -End $today_date. DateTime
        if ($days_with_no_backups .Days -gt $daystoalert)
        {
            Write-output " $($vm. Name),$( $days_with_no_backups.Days) "
        }
    }
    Catch {
        # VM was never backed up gets caught in this exception.
        Write-output " $($vm. Name), Never backed up"
    }

Delete files in a folder and subfolders of files based on last access time

Get-ChildItem -path "D:\ftp.archived.logs" -Recurse | Where-Object{$_.LastAccessTime -lt (get-date).AddDays(-90)} | remove-item 

add -whatif at the end of remove-item to show what will get removed.



Enable/Disable SMBv1,2,3 in Windows


Disable form repost on browser refresh

Here's a trick I found to prevent a form repost on browser refresh


        protected void Page_PreRender(object sender, EventArgs e)
        {
                     ViewState["Check_Page_Refresh"] = Session["Check_Page_Refresh"];
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["Check_Page_Refresh"] = DateTime.Now.ToString();
            }
        }

protected void btn_Click(object sender, EventArgs e)
{
if (ViewState["Check_Page_Refresh"].ToString() == Session["Check_Page_Refresh"].ToString())
{
     <your main code you want to execute once on button click here>
}
}

Reset vmware ESX evaluation license.

VMWare ESXi license expires in 60 days.  You can reset that 60 days by doing the following.

-ssh into the ESXi host.
-rm -f /etc/vmware/vmware.lic /etc/vmware/license.cfg
-reboot

SQL does not allow modifying of table.

If you've dealt with MS SQL before, by default, it does not allow you to modify a table without you dropping it and recreating it. It's kind of annoying.   Here's a way to get around it.  Do this at your own risk of corrupting your database.

-Go to the Tools menu -> Options
-Click on "Designers" on the left menu tree
-Uncheck "Prevent saving changes that require table re-creation"



VMWare - Power ON a vm from the command line

To power on a virtual machine from the command line:

-List the inventory ID of the virtual machine with the command:
               vim-cmd vmsvc/getallvms |grep <vm name>
               Note: The first column of the output shows the vmid.

-Check the power state of the virtual machine with the command:
               vim-cmd vmsvc/power.getstate <vmid>

-Power-on the virtual machine with the command:
               vim-cmd vmsvc/power.on <vmid>

VSS Error while running system state/bare metal restore backup using SCDPM.

When running a system state/bare metal restore backup using SCDPM, you may encounter a VSS error leading to a protection point inconsistency.  This is due to automounter being disabled and the system restore partition being offline in disk management.  The cause of this may be a third party snapshot tool that leverages VSS such as Netapp's SnapDrive.  In order to get SCDPM to do a system state/bare metal restore, you will need to do the following steps.  Note: this works for VMWare converter as well if you're getting

System Partition is offline.  No drive letters

1.  log into the server you want to protect.
2.  open a command prompt
3.  type "diskpart"
4.  type "automount" to display the current state of automount.  If its disabled, open another command prompt and run "diskpart> automount enable" to enable it.
5.  in diskpart, get a list of volumes by typing "list volume".
6.  find the system restore partition and note down the volume number.
7.  type "select volume (x)" where x is the volume number of the system restore partition.
8.  type "online volume" to bring the volume online.
9.  rerun the SCDPM consistency check and it should be successful.

Before

After (Notice "System Reserved" volume is labeled)

ESXTOP quick troubleshooting overview


Power off a Virtual SAN Cluster

Power off a Virtual SAN Cluster

Prerequisites
If the vCenter Server VM is running on the Virtual SAN cluster, migrate the VM to the first host, or record the host where it is currently running.
Procedure

1
Power off all virtual machines that are running on the Virtual SAN cluster.
The vCenter Server virtual machine must be powered off last.
2
Place all ESXi hosts that compose the cluster in maintenance mode.
Run the esxcli command to set the Virtual SAN mode for entering the maintenance state.
esxcli system maintenanceMode set -e true -m noAction
3
Power off the ESXi hosts.


Bare metal recovery for Windows 2012 from a Windows Server Backup image.

Bare metal recovery for Windows 2012 from a Windows Server Backup image.

  1. Create an ISO of the backup image and mount it to VM.
  2. Install a fresh OS
  3. Install vmware tools.
  4. Reboot into Windows install ISO.
  5. Select System Image Recovery
  6. Select the command prompt.
  7. Type in "start /w wpeinit"  to enable the network and get an ip.
  8. Exit the command prompt.
  9. Select System Image Recovery.
  10. Select the Operating System.
  11. Select the "Select a system image" radio button and next.
  12. Click on the "Advanced.." button.
  13. Click on "Search for a system image on the network"
  14. Type in the path of the backup.  Make sure its the path that has the "WindowsImageBackup" folder or it will not detect an available image.
  15. Type in your credentials.
  16. Select the backup from the list and click Next.


To find a VM with a particular snapshot name

Get-Snapshot -VM VM -Name '<snapshot name>'


Power on/off VM via command line.


Power on a VM
To power on a virtual machine from the command line:
  1. List the inventory ID of the virtual machine with the command:

    vim-cmd vmsvc/getallvms |grep <vm name>

    Note: The first column of the output shows the vmid.

  2. Check the power state of the virtual machine with the command:

    vim-cmd vmsvc/power.getstate <vmid>

  3. Power-on the virtual machine with the command:

    vim-cmd vmsvc/power.on <vmid>

Get all vm's with connected CD rom drives

This is a powercli command to get all the vm's with connected cdrom drive.  

get-cluster | where {$_.Name -eq "SFColo Test & Dev"} | get-vm | where { $_ | get-cddrive | where { $_.ConnectionState.Connected -eq "true" } } | select Name


Get VMX and VMWare tools version and export to CSV

To get the VMware tools versions and export it to a csv called vmtools.csv

get-vm | where {$_.powerstate -ne "PoweredOff" } | where {$_.Guest.ToolsVersionStatus -ne "guestToolsCurrent"} | % { get-view $_.id } | select Name, @{ Name="ToolsVersion"; Expression={$_.config.tools.toolsVersion}}, @{ Name="ToolStatus"; Expression={$_.Guest.ToolsVersionStatus}} | Export-Csv -NoTypeInformation -UseCulture -Path d:\vmtools.csv

Check if a user is in an AD group.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Security.Principal;

namespace test_adgroup
{
   class Program
    {
       static void Main(string[] args)
        {
           string username = "cykill";
           //string username = WindowsIdentity.GetCurrent().Name;

           PrincipalContext pc = new PrincipalContext(ContextType.Domain,"mydomainname");
           UserPrincipal up = UserPrincipal.FindByIdentity(pc, username);

           if(up.IsMemberOf(pc,IdentityType.SamAccountName,"mygroup"))
            {
               Console.WriteLine("In Group");
            }
           else
            {
               Console.WriteLine("Not In Group");
            }

        }
    }
}

Caveat:  This does not work for the "Domain Users" group.  It always return false.  I don't know why.
Update:  Seems it doesn't work for large AD groups.

Disable IPv6 via commands in Windows

get-netadapterbinding
set-NetAdapterBinding -Name “Network Adapter Name” –ComponentID ms_tcpip6 –Enabled $False

new-itemproperty -Path HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters -Name DisabledComponents -PropertyType DWord -Value ffffffff

Reset a slot in Cisco UCS.

- Reset a slot (equivalent to remove power from the blade and reapplying):
     #reset slot x/y (where x = chassis and y = blade or server #)

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