Sunday, December 27, 2015

Retrieve log files from a specific date

Hi,

Below is a very basic script that simply retrieve log files from a specific date,
Based on the LastWriteTime attribute of the file.

In the script i'm mapping the destination machine drive, this is because i need to use different credentials to access the remote machine.

In case you have already permission to access the remote machine C$ share / other, adjust the script below, just to save time and issue using map drive.

Write-Host "Enter The Requested Date To Filter Files,`nUse The Following Example - 24/12:" -ForegroundColor Green
$RequestedDate = Read-Host
Write-Host "Enter Computer Name / IP, To Retreive Files From..." -ForegroundColor Green
$ComputerName = Read-Host

# Map Network Drive
net use O: \\$ComputerName\C$ /USER:BlaBla BlaBla

# Check If Local Temp Path Exists
if (!(Test-Path C:\Logs\$ComputerName)) {mkdir C:\Logs\$ComputerName}

$ClientLogs = Get-ChildItem O:\LocalApp\Client\Logs\ -Recurse
$ServerLogs =  Get-ChildItem O:\LocalApp\Server\Logs\


$ClientLogs_Results = $ClientLogs | Where-Object {$_.LastWriteTime.ToString("dd/MM") -eq $RequestedDate}
$ServerLogs_Results = $ServerLogs | Where-Object {$_.LastWriteTime.ToString("dd/MM") -eq $RequestedDate}

    foreach ($ServerLogs_R in $ServerLogs_Results) {

        Write-Host -ForegroundColor Green "Copying $ServerLogs_R"
        Copy-Item -LiteralPath $ServerLogs_R.fullname -Destination C:\Logs\$ComputerName -Force
        
    } # END of ServerLogs_Results Loop

    foreach ($ClientLogs_R in $ClientLogs_Results) {

        Write-Host -ForegroundColor Green "Copying $ClientLogs_R"
        Copy-Item -LiteralPath $ClientLogs_R.fullname -Destination C:\Logs\$ComputerName -Force
        
    } # END of ServerLogs_Results Loop

# Remove Map Network Drive
Net use O: /delete /y

Write-Host "`n`nPress Enter To Exit..." -ForegroundColor Green
Read-Host



Enjoy!

Tuesday, July 21, 2015

Retreive Monitor Serial Number

Retrieve Monitor Serial Number Using PowerShell

Small script to retrieve monitor serial number using PowerShell,
using a WMI method called WmiMonitorID under the root\wmi namespace.

This WMI method exist from Vista and above, if you are having XP and below, you still can retrieve the information using a registry query and convert the EDID to the monitor information which include the monitor serial number.

Script Below



# Import Computers from txt file
$Computers = Get-Content C:\temp\List.txt

# Foreach loop
$BigOutput = foreach ($Computer in $Computers) {
    
    # Create output object
    $output = "" | Select-Object -Property Computer, Manufacturer, ProductCode, SerialNumber, Name, Week, Year
    
    # Get all connected monitors using WMI class WmiMonitorID
    $Monitors = Get-WmiObject -Namespace root\wmi -Class WmiMonitorID -ComputerName $Computer

        # Internal foreach loop to go over each connected monitor
        foreach ($Monitor in $Monitors) {
            
            $output.Computer = $Computer
            # get monitor info and convert to char
            $Monitor.ManufacturerName | foreach {$output.Manufacturer += [char]$_}
            $Monitor.ProductCodeID | foreach {$output.ProductCode += [char]$_}
            $Monitor.SerialNumberID | foreach {$output.SerialNumber += [char]$_}
            $Monitor.UserFriendlyName | foreach {$output.Name += [char]$_}
            # Get week and year
            $output.Week = $Monitor.WeekOfManufacture
            $output.Year = $Monitor.YearOfManufacture
            $output
            $output = "" | Select-Object -Property Computer, Manufacturer, ProductCode, SerialNumber, Name, Week, Year

        } #END internal foreach loop

} # END foreach loop

# Export result to CSV file
$BigOutput | Export-Csv C:\GetMonitorSN.csv


Enjoy!



Tuesday, June 2, 2015

Load PowerCLI into PoweShell ISE

function Load-PowerCLI
{
    Add-PSSnapin VMware.VimAutomation.Core
    Add-PSSnapin VMware.VimAutomation.Vds
    . "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"


Once execute you may connect to your vSphere using the following command:


Connect-VIServer -Server "Server"

 Replace the "Server" with your vSphere address / hostname,

You will receive a prompt for user name and password -



For some reason, since we are using the ISE interface we need to switch to the new PS-Drive created for us, in order to run PowerCLI commands.

cd vi:\

you may check your connection to the vSphere using a PowerCLI command, example -

get-vm
 
Enjoy!

Wednesday, March 25, 2015

Find Specific MS HF using Powershell


From time to time, especially in my country, we need to recursively search for a specific Hot Fix installed on the system.

In the script below we show how to search for the following KB, KB2863058
This can be change to fit your needs.

$list = Get-Content C:\tmp\list.txt
$Exception = ""
$Updates = ""
$OperatingSystem = ""
$Update_KB2863058 = ""

$BigResult = foreach ($l in $list) {

    Clear-Variable OperatingSystem
    Clear-Variable Updates
    Clear-Variable Exception
    Clear-Variable Update_KB2863058

    $result = "" |select -Property Name, OS, Update_KB2863058

    $OperatingSystem = Get-WmiObject -ComputerName $l -Class Win32_OperatingSystem
                        
    if ($OperatingSystem -ne $null) {

        $Updates = Get-WmiObject -ComputerName $l -Class Win32_QuickFixEngineering
        if ($Updates.count -gt "1") {
            $Update_KB2863058 = $Updates | ? {$_.HotFixID -eq "KB2863058"}
            
            if ($Update_KB2863058 -eq $null) {
                $result.Update_KB2863058 = "Not Installed"}
            else {$result.Update_KB2863058 = "Installed"}
        }
        else {
            $Update_KB2863058 = "Please Check Manually";
            $result.Update_KB2863058 = $Update_KB2863058;
        }

        $result.Name = $l
        $result.OS = $OperatingSystem.Caption

        $result

    } # END OperationSystem IF
                        
    else {
        $result.Name = $l; $result.Update_KB2863058 = "Can't Connect"; $result;
    }

} # END Foreach

$BigResult | Export-Csv -Path C:\tmp\GetInstalledHotFix.csv



Enjoy.

Thursday, March 12, 2015

Remotely Query IE Version Using Powershell (.Net / WMI)


In this post i will show you how to get the IE version from remote computers using Powershell.

The way i will do it is with Remote Registry Query, which this can help you for future use and not just for the IE version,
There are two ways to do this, I'm sure you will find them both on the Internet but i though it could be nice to get the both methods on one post.

Option 1: Remote Registry Query Using .Net

#################################################
#################################################
###### Get IE Version From Remote Computer ######
######                .NET                 ######
#################################################
#################################################


### Important ###
#
# In order to use the .NET framework to open the Registry on 
# remote computer the Remote Registry service must be turn on!
#
### Important ###


# Read remote machines from a list
$list = Get-Content C:\Temp\List.txt


# Define the key to retreive
$hklm = "LocalMachine"
$keyname = 'SOFTWARE\\Microsoft\\Internet Explorer'


# Foreach loop for the list of machines,
# and capture the result to a new object for export later to CSV
$CSVOutput = foreach ($machine in $list) {


$output = "" | Select-Object -Property Machine, Value

$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($hklm, $machine)
$key = $reg.OpenSubkey($keyname)


# Value to search for under the defined Hive & Key
$value = $key.GetValue('svcVersion')


# On IE11 the value behind the svcVersion key, on lower version the value behind Version,
# So, the below just check if the above $Version is not empty, and if it doesn it means 
# we have a lower version. and pull the old Version key.
if ($value -eq $null) {$value = $key.GetValue('Version') } # END IF Get Value


# Push the result to the $Output variable we have created
$output.Machine = $machine
$output.Value = $value


$output


} # END foreach CSVOutput loop


# Change the output path to ever you want
$CSVOutput | Export-Csv C:\Temp\IEVer.csv 

Option 2: Remote Registry Query Using WMI


#################################################
#################################################
###### Get IE Version From Remote Computer ######
######                 WMI                 ######
#################################################
#################################################


### WMI Regitry Hive
# HKEY_CLASSES_ROOT (2147483648 (0x80000000))
# HKEY_CURRENT_USER (2147483649 (0x80000001))
# HKEY_LOCAL_MACHINE (2147483650 (0x80000002))
# HKEY_USERS (2147483651 (0x80000003))
# HKEY_CURRENT_CONFIG (2147483653 (0x80000005))


# Read remote machines from a list
$list = Get-Content C:\Temp\List.txt


# Define the key to retreive
$hklm = 2147483650
$key = "SOFTWARE\Microsoft\Internet Explorer"


# Foreach loop for the list of machines,
# and capture the result to a new object for export later to CSV
$CSVOutput = foreach ($machine in $list) {


$output = "" | Select-Object -Property Machine, IEVersion
$wmi = ""
$Version = ""


# Value to search for under the defined Hive & Key
$value = "svcVersion"


# initial the WMI instance & Query the key for a specific value
$wmi = Get-WmiObject -List -Namespace "root\default" -ComputerName $machine | Where-Object {$_.Name -eq "StdRegProv"}
$Version = ($wmi.GetStringValue($hklm,$key,$value)).svalue


# On IE11 the value behind the svcVersion key, on lower version the value behind Version,
# So, the below just check if the above $Version is not empty, and if it doesn 
# it means we have a lower version and pull the old Version key.
if ($Version -eq $null) {$value = "Version"; $Version = ($wmi.GetStringValue($hklm,$key,$value)).svalue}


# Push the result to the $Output variable we have created
$output.Machine = $machine
$output.IEVersion = $Version


$output


} # END foreach CSVOutput loop


# Change the output path to ever you want
$CSVOutput | Export-Csv C:\Temp\IEVer.csv 


Enjoy!

Friday, February 13, 2015

"Telnet" in PowerShell Style

I guess that I'm not the only one that had a connection test to perform and found out that the Telnet Client is not installed on the system.

And again, Powershell to the rescue...

I decided to write a small PowerShell function to perform the same concavity test as Telnet will, and in order to perform this test we will leverage the System.Net.Sockets.TcpClient .NET object,
You may read some more about it at:
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx

And now for the function:
 
# PowerShell PSTelnet function

function PSTelnet([string]$Destination, [int]$Port) {
  
  # Create a TcpClient .NET object  
  $TCPClient = New-Object System.Net.Sockets.TcpClient
    
    # Try & Catch
    try {
          $TCPClient.Connect($Destination, $Port)
        } # END try
    catch [System.Net.Sockets.SocketException] {
            Write-Host -ForegroundColor Red "`nPSTelnet failed to connect with the following error:`n"
            Write-Output -ForegroundColor Red $Error.Item(0)
          } #END cache
  
  # Test if the connection established
  if ($TCPClient.Connected) {
    Write-Host -ForegroundColor Green "`nPSTelnet Successfully Connected"
    } # END if

  # Close and reset the connection
  $TCPClient.Close()

} # END of function

### Example of usage

PSTelnet -Destionation 127.0.0.1 -Port 445

### Example of output

PSTelnet Successfully Connected

Hope this helps,

Enjoy.

Monday, January 5, 2015

"Ping" in PowerShell style

Hi,

This PowerShell script will retrieve the IP address of a remote computer on the network,
You may provide a list of Hostnames that the script will go through.

# Set Error Action to Silently Continue
# This is in order to continue without any error in case you encounter one
$ErrorActionPreference = "SilentlyContinue"

# Get a list of computers from a TXT file
$list = Get-Content C:\Temp\Hosts.txt


# Create Ping .Net object
$Ping = New-Object System.Net.NetworkInformation.Ping

# Global var to contain all results
$BigResult = `
foreach ($l in $list) {

$Result = "" | Select-Object -Property Hostname, IP

$PingResult = ""
    
    # Try & Catch
    try {
    $PingResult = $Ping.Send($l)
    } 
        catch [System.Net.NetworkInformation.PingException]
        {
            $PingResult = ""
        } # END Try & Catch

# Check the PingResult var for successfull ping
if ($PingResult.Status -eq "Success") {
    
    $Result.IP = $PingResult.Address
    $Result.Hostname = $l

} else {
        
        $Result.IP = "Failed To Retrieve"
        $Result.Hostname = $l

    }

$Result

} # END foreach loop

# Display Output To Screen
$BigResult

# Save Output To CSV File
$BigResult | Export-Csv C:\Temp\IP.csv

Enjoy!