Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. 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, June 27, 2019

Run Powershell commands remotely with PSSession.


Here's a way to run Powershell commands on a remote machine.  It saves the hassle of RDP'ing into the remote machine, wait for Windows to load your profile, run startup scripts, apply GPO settings, load your desktop, etc...  That can be time consuming if you're always logging into to remote machine to verify something.

  1. Create a remote session
    • new-pssession <computer hostname>
  2. Get the ID of the remote session.
    • get-pssession
  3. Connect to that remote session using the ID.
    • enter-pssession <ID>
  4. Once connected, you should see the computer hostname in brackets like below.
    • [computername]: PS C:\users\guest
  5. Execute your Powershell command like so.
    • [computername]: PS C:\users\guest> get-volume
  6. To exit the session, just type the following.
    • exit or exit-pssession
  7. After exiting of the session, you would want to remove/close the session from your computer.
    • remove-pssession <id>
      • Leave me a comment if you know of a way to remove 'all' the sessions at once without looping it in a script.

Hope this helps.

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
        }
    }
}

Saturday, June 9, 2018

Change IP address using Powershell.


  1. Get-NetIPAddress
    1. get the InterfaceIndex number for the nic you want to change the IP address on.
  2. Remove-NetIPAddress -InterfaceIndex X
  3. New-NetIPAddress -InterfaceIndex X -IPAddress x.x.x.x -PrefixLength 23 -DefaultGateway x.x.x.x
  4. Set-DnsClientServerAddress -InterfaceIndex X -ServerAddresses  x.x.x.x, x.x.x.x

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
        }
    }
}

Find overcommited compute resources in VMWare.



The following commands requires PowerCLI to run.

Get-MemoryOvercommit -Cluster "Cluster Name"
Get-CPUOvercommit -Cluster "Cluster Name"



Get space utilization of all disk from a computer


[CmdletBinding ()]
param(
        [Parameter(Mandatory =$True, ValueFromPipeline=$True )]
        [string[]] $ComputerName
    )
ForEach ( $Name in $ComputerName ) {
    write-host "Drive info for " $Name
    Get-WmiObject -Class win32_logicaldisk -ComputerName $Name |
ft DeviceID , @{Name= "Free Disk Space (GB)";e= {$_.FreeSpace /1GB }}, @{Name ="Total Disk Size (GB)";e ={$_ .Size / 1GB}} -AutoSize

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

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>'


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

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"
        }
    }
}

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.



To find a VM with a particular snapshot name

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


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