Category Archives: OS

Process Monitoring with PowerShell

PowerShell MVP Jeff Hicks shares his script for watching processes using a WMI event subscription using the CIM cmdlets.

Source: Process Monitoring with PowerShell – Petri

$Poll = 120 #check the computer every two minutes

<#
I want to select all properties from the WMI class called CIM_InstModification.
This is a special system class that’s triggered when an object is modified.
I don’t want to find every object, as it is changed every second. So I tell WMI to check within a time frame of seconds.
When this event fires, WMI will have a new object called the TargetInstance.
This will be the changed object, and I only care about those that are Win32_Process objects.
The ISA operator accomplishes that.
The last part of the query is to limit results to those process objects, which is what the TargetInstance is, with a WorkingSetSize property of greater or equal to 500 MB.
#>

$query = “Select * from CIM_InstModification within $Poll where TargetInstance ISA ‘Win32_Process’ AND TargetInstance.WorkingSetSize>=$(1000MB)” #WMI query

<#
When you create the event subscriber, you can choose to simply record the events in your PowerShell session as matching events are detected.
Or you can take action.
In my case, I want to do a few things everytime a matching process is found.
I want to create a log file, and I want to display a popup message.
#>

$action={
#create a log file
$logPath= “C:\Work\HighMemLog.txt”
“[$(Get-Date)] Computername = $($Event.SourceEventArgs.NewEvent.SourceInstance.CSName)” | Out-File -FilePath $logPath -Append -Encoding ascii
“[$(Get-Date)] Process = $($Event.SourceEventArgs.NewEvent.SourceInstance.Name)” | Out-File -FilePath $logPath -Append -Encoding ascii
“[$(Get-Date)] Command = $($Event.SourceEventArgs.NewEvent.SourceInstance.Commandline)” | Out-File -FilePath $logPath -Append -Encoding ascii
“[$(Get-Date)] PID = $($Event.SourceEventArgs.NewEvent.SourceInstance.ProcessID)” | Out-File -FilePath $logPath -Append -Encoding ascii
“[$(Get-Date)] WS(MB) = $([math]::Round($Event.SourceEventArgs.NewEvent.SourceInstance.WorkingSetSize/1MB,2))” | Out-File -FilePath $logPath -Append -Encoding ascii
“[$(Get-Date)] $(‘*’ * 60)” | Out-File -FilePath $logPath -Append -Encoding ascii

#create a popup
$wsh = New-Object -ComObject Wscript.shell
$Title = “$(Get-Date) High Memory Alert”
$msg = @”
Process = $($Event.SourceEventArgs.NewEvent.SourceInstance.Name)
PID = $($Event.SourceEventArgs.NewEvent.SourceInstance.ProcessID)
WS(MB) = $([math]::Round($Event.SourceEventArgs.NewEvent.SourceInstance.WorkingSetSize/1MB,2))
“@

#timeout in seconds. Use -1 to require a user to click OK.
$Timeout = 10
$wsh.Popup($msg,$TimeOut,$Title,16+32)

}

#Now that I have the action scriptblock all that remains is to register the subscription with the Register-CimIndicationEvent.#
Register-CimIndicationEvent -Query $query -SourceIdentifier “HighProcessMemory” -Action $action

#You can see the registration with the Get-EventSubscriber cmdlet.
#This subscription will run for as long as my PowerShell session is running.
#The corollary is that I will need to recreate it every time I want to start monitoring.
#If this is a daily task, I could put it in my PowerShell profile script.

#If you want to get rid of the subscriber, simply unregister it.
#Get-EventSubscriber -SourceIdentifier “HighProcessMemory” | Unregister-Event

 

How to Create a Bootable USB Drive

Step 1: Using DISKPART command

  1. Insert your USB flash drive to your running computer.
  2. Run Command Prompt as administrator.
  3. Type ‘diskpart‘ on Command Prompt (without quotes) and hit Enter.
  4. Type ‘list disk‘ to view active disks on your computer and hit Enter and find the USB drive disk #.
  5. Type ‘select disk 1‘ (or whatever the USB drive is).
  6. Type ‘clean‘ and hit Enter to remove all of data in the drive.
  7. Type ‘create partition primary‘ and hit Enter. Creating a primary partition and further recognized by Windows as ‘partition 1‘.
  8. Type ‘select partition 1‘ and hit Enter. Choosing the ‘partition 1‘ for setting up it as an active partition.
  9. Type ‘active‘ and hit Enter. Activating current partition.
  10. Type ‘format fs=ntfs quick‘ and hit Enter. Formatting current partition as NTFS file system quickly.
  11. Type ‘exit‘ and hit Enter. Leaving DISKPART program but don’t close the Command Prompt instead. We would still need it for next process.

Step 2: Creating Boot Sector

Mount the ISO file to a drive.

Let us assume that the flash / USB drive is the D: drive and the DVD installer located on drive F:The first step, we will navigate Command Prompt to set installation DVD as its active directory.

  • (if you want to create boot from ISO file then, first thing to do is to mount the ISO of the Windows OS you just downloaded. Double-click the ISO file to mount it. Check the drive letter and make note of the drive letter).
  1. By default, Command Prompt’s active directory for Administrator permission is on C:\Windows\System32>. We will navigate Command Prompt to set on DVD (F:) as its active directory. Just type ‘f:‘ then hit Enter, and the active directory changed to F:
  2. Type ‘cd boot‘ and hit Enter. Active directory changed to F:\boot>.
  3. Type ‘bootsect /nt60 d:‘ and hit Enter. Creating boot sector on D: drive (USB flash drive).
  4. Type ‘exit‘ and hit Enter to close the Command Prompt. Until this step we have made a bootable USB drive successfully, and the flash drive is ready to be used as a boot media.

Step 3: Copying Installation Files

To install Windows from a bootable USB drive, we just need to copy the whole installation files contained on the DVD installer to flash drive. To do this, open the Command Prompt as in previous steps. Once it opens, type ‘xcopy f:\*.* d:\ /E /H /F‘ and then press Enter. Wait until all the files in the DVD installer copied to the flash drive. Now bootable USB drive is ready to be used for installing Windows from flash drive and you’re done !

 

How to Shutdown a Failover Cluster or a Node.

Shutting Down a Node

When shutting down or rebooting a node in a Failover Cluster, you first want to drain (move off) any roles running on that server (such as a virtual machine).  This ensures that the shutting down of a node is graceful to any applications running on that node.

  1. Open Failover Cluster Manager (CluAdmin.msc)
  2. Click on “Nodes”
  3. Right-click on the node name and under ‘Pause’ click on ‘Drain Roles’
  4. Under Status the node will appear as ‘Paused’.  At the bottom of the center pane click on the ‘Roles’ tab.  Once all roles have moved off this node, it is safe to shut down or reboot the node.

    To resume the node after it has been restarted…

    When the node is once again powered on and ready to be put back into service, use the Resume action to re-enable the node to host roles.

    1. Open Failover Cluster Manager (CluAdmin.msc)
    2. Click on “Nodes”
    3. Right-click on the node name and select ‘Resume’, then select either:
      1. Fail Roles Back’ – This will resume the node and move any roles which were running on the node prior to the node back.  Caution:  This could incur downtime based on the role
      2. Do Not Fail Roles Back’ – This will resume the node and not move any roles back.

Shutting Down a Node with Windows PowerShell®

  1. Open a PowerShell window as Administrator
  2. Type:  Suspend-ClusterNode -Drain
  3. Type:  Get-ClusterGroup
    1. Verify that there are no roles listed under “OwnerNode” for that node
    2. This could be scripted with the following syntax:
      PS C:\> (Get-ClusterGroup).OwnerNode –eq “NodeBeingDrained”
  4. Shutdown or restart the computer by typing either:
    1. Stop-Computer
    1. Restart-Computer

To resume the node after it has been restarted…

  1. Open a PowerShell window as Administrator
  2. Type:  Resume-ClusterNode
    1. If you wish to fail back the roles which were previously running on this node type:

PS C:\> Resume-ClusterNode –Failback Immediate

Shutting Down a Cluster

Shutting down the entire cluster involves stopping all roles and then stopping the Cluster Service on all nodes.  While you can shut down each node in the cluster individually, using the cluster UI will ensure the shutdown is done gracefully.

  1. Open Failover Cluster Manager (CluAdmin.msc)
  2. Right-click on the cluster name, select ‘More Actions’, then “Shut Down Cluster…”
  3. When prompted if you are sure you want to shut down the cluster, click “Yes”

Shutting Down a Cluster with PowerShell

  1. Open a PowerShell window as Administrator
  2. Type:  Stop-Cluster

Controlling VM Behavior on Shutdown

When the cluster is shut down, the VMs will be placed in a Saved state.  This can be controlled using the OfflineActionproperty.

To configure the shut down action for an individual VM (where “Virtual Machine” is the name of the VM):

PS C:\> Get-ClusterResource “Virtual Machine” | Set-ClusterParameter OfflineAction 1

 

 Value  Effect
 0  The VM is turned off
 1 (default)  The VM is saved
 2  The guest OS is shut down
 3  The guest OS is shut down forcibly

To start the cluster after it has been shut down

  1. Type:  Start-Cluster

Source: How to Properly Shutdown a Failover Cluster or a Node – Clustering and High-Availability – Site Home – MSDN Blogs

Search WMI for Useful Information in  PowerShell

Search WMI for Useful Information

Source: Search WMI for Useful Information – Power Tips – PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources

<#

WMI is a great source of information, but it is not always easy to find out the names of valid WMI classes to query.

Here is a little search tool: it asks for a keyword, then searches WMI for all valid classes with this keyword. The results are shown in a grid view window, and when you choose a class and press OK, the tool queries the class for you, showing the results:

#requires -Version 3

#>

function Search-WMI
{
param([Parameter(Mandatory=$true)]$Keyword)

Get-WmiObject -Class “Win32_*$Keyword*” -List |
Where-Object { $_.Properties.Count -gt 6 } |
Where-Object { $_.Name -notlike ‘Win32_Perf*’ } |
Sort-Object -Property Name |
Select-Object -Property @{Name=’Select one of these classes’; Expression={$_.Name }} |
Out-GridView -Title ‘Choose one’ -OutputMode Single |
ForEach-Object {
Get-WmiObject -Class $_.’Select one of these classes’ | Out-GridView
}
}

<#

Example:

Search-WMI -Keyword network

#>

how to Assign Multiple IP Addresses to One Single Network Interface in Linux

The concept of creating or configuring multiple IP addresses on a single network interface is called IP aliasing. IP aliasing is very useful for setting up

Source: Create Multiple IP Addresses to One Single Network Interface

Assign Multiple IP Addresses to One Single Network Interface

  1. The device network (NIC) files located in “/etc/sysconfig/network-scripts/” directory.
  2. Navigate to the directory and do “ls -l” to list all devices.

                cd /etc/sysconfig/network-scripts/

ls –l

[root@******** network-scripts]# ls -l

total 236

-rw-r–r–. 1 root root   394 Nov  5 13:13 ifcfg-ens192

  1. Copy existing parameters of interface “ifcfg- ens192” in virtual interfaces called ifcfg- ens192:0, ifcfg- ens192:1 and ifcfg- ens192:2.

cp ifcfg- ifcfg-ens192 ifcfg- ifcfg-ens192:0

                                cp ifcfg- ens192 ifcfg- ens192:1

                                cp ifcfg- ens192 ifcfg- ens192:2

  1. edit each file and rename the DEVICE name to its corresponding alias and change the IPADDR address.

For example:

DEVICE=” ens192 ” replace with ens192:0

BOOTPROTO=static

ONBOOT=yes

TYPE=”Ethernet”

IPADDR=172.16.16.125 replace with the new virtual IP.

NETMASK=255.255.255.224

GATEWAY=172.16.16.100

HWADDR=00:0C:29:28:FD:4C

  1. Once, you’ve made all changes, save all your changes and restart/start the network service for the changes to reflect.

[root@*************]# /etc/init.d/network restart

How to Assign Multiple IP Address Range

  1. if you would like to create a range of Multiple IP Addresses to a particular interface called “ifcfg-eth0“.

cd /etc/sysconfig/network-scripts/

cp -p ifcfg-eth0 ifcfg-eth0-range0

  1. Now open “ifcfg-eth0-range0” file and add “IPADDR_START” and “IPADDR_END” IP address range as shown below.

[root@***********]# vi ifcfg-eth0-range0

 

#DEVICE=”eth0″

#BOOTPROTO=none

#NM_CONTROLLED=”yes”

#ONBOOT=yes

TYPE=”Ethernet”

IPADDR_START=172.16.16.126

IPADDR_END=172.16.16.130

IPV6INIT=no

#GATEWAY=172.16.16.100

  1. Save it and restart/start network service

[root@**************]# /etc/init.d/network restart

How to Clean up the WinSxS Directory and Free Up Disk Space on Windows Server 2008 R2.

Source: Disk Cleanup Wizard addon lets users delete outdated Windows updates on Windows 7 SP1 or Windows Server 2008 R2 SP1

Download Update for Windows Server 2008 R2 x64 Edition (KB2852386).

After you install this update, follow these steps to clean up Windows update files.

Note You must have administrator permissions to do this.

  1. Start the Disk Cleanup wizard. To do this, use one of the following methods:
    • Method 1: Click Start, type cleanmgr in the Start Search box, and then click OK.
    • Method 2: Click Start, click All Programs, click Accessories, click System Tools, and then click Disk Cleanup.
    • Method 3: If a Low Disk Space notification appears, click the notification to open the Disk Cleanup wizard.
  2. Select the Windows 7 or Windows Server 2008 R2 system drive, and then click OK.NoteThis operation might take several seconds because the Disk Cleanup wizard searches for files on the drive that can be cleaned up.
  3. If the Windows Update Cleanup option is not displayed on the Disk Cleanuptab, click Clean up system files. If the Windows Update Cleanup option is displayed on the Disk Cleanup tab, go to step 5.Note The Windows Update Cleanup option is available only when you log on by using administrator permissions.
  4. Select the Windows 7 or Windows Server 2008 R2 system drive, and then click OK.
  5. On the Disk Cleanup tab, select Windows Update Cleanup, and then click OK.Note By default, the Windows Update Cleanup option is already selected.
  6. When a dialog box appears, click Delete Files.

Notes

  • The Disk Cleanup wizard runs in the background.
  • You may have to restart the computer to finish the cleanup process.

How To Copy Command History to the clipboard in PowerShell

Copying Command History

Source: Copying Command History – Power Tips – PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources

You can copy your entire command history to the clipboard:

(Get-History).CommandLine | clip.exe 

This technique uses automatic unrolling introduced in PowerShell 3.0. To use it in PowerShell 2.0, you would have to manually expand the CommandLine property like this:

Get-History | Select-Object -ExpandProperty commandline | clip.exe 

To copy only the last five commands, simply add the -Count parameter to Get-History:

(Get-History -Count 5).CommandLine | clip.exe

How To Find Process Owner With PowerShell

Get-Process gets you a list of all running processes, but it will not reveal the process owner. To find the process owner, you would need to ask the WMI service, for example.

To make this easier, here is a little helper function:

filter Get-ProcessOwner
{
  $id = $_.ID
  $info = (Get-WmiObject -Class Win32_Process -Filter "Handle=$id").GetOwner()
  if ($info.ReturnValue -eq 2)
  {
    $owner = '[Access Denied]'
  }
  else
  {
    $owner = '{0}\{1}' -f $info.Domain, $info.User
  }
  $_ | Add-Member -MemberType NoteProperty -Name Owner -Value $owner -PassThru
}

When you pipe process objects into Get-ProcessOwner, it appends a new property called “Owner” to the process object. This property is hidden unless you ask Select-Object to show it:

 
PS> Get-Process -Id $pid | Get-ProcessOwner | Select-Object -Property Name, ID, Owner

Name                    Id Owner                    
----                    -- -----                    
powershell_ise       10080 TOBI2\Tobias 

This works for multiple process objects as well:

 
PS> Get-Process | Where-Object MainWindowTitle | Get-ProcessOwner | Select-Object -Property Name, ID, Owner

Name                    Id Owner                    
----                    -- -----                    
chrome               13028 TOBI2\Tobias             
devenv               13724 TOBI2\Tobias             
Energy Manager        6120 TOBI2\Tobias             
ILSpy                14928 TOBI2\Tobias             
(...)

Note that you get process owners only when you have Administrator privileges. Without these privileges, you can get the owner only for your own processes, which is relatively pointless.

Finding Process Owner – Power Tips – PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources.

How to fix Task Scheduler error: The task image is corrupt or has been tampered with

Known issue 1

After you install this security update, you may receive an error message that resembles the following when you open Task Scheduler (taskschd.msc):

Task taskname: The task image is corrupt or has been tampered with.

Specifically, this problem can occur in the following scenario:

  1. Your computer is running Windows Vista or Windows Server 2008.
  2. You install security update 2305420.
  3. You upgrade to the release version (RTM) of Windows 7 or Windows Server 2008 R2. 
  4. You install Service Pack 1 (SP1) for Windows 7 and Windows Server 2008 R2.

In this scenario, all inbox tasks in Windows Server 2008 R2 and all tasks that are created after the upgrade from Windows Vista and Windows Server 2008 are affected.

To avoid this problem, use one of the following methods:

  • Upgrade directly from Windows Vista or Windows Server 2008 to a version of Windows 7 or Windows Server 2008 R2 that includes SP1. 
  • After you upgrade to the RTM version of Windows 7 or Windows Server 2008 R2, install security update 2305420 before you install SP1.

To resolve this issue if it has already occurred, follow the steps in the “Workaround” section of “Known issue 2.”

Known issue 2

After you upgrade from Windows Vista or Windows Server 2008 to Windows 7 or Windows Server 2008 R2 by using an installation package that includes this security update (KB2305420), you may find that scheduled tasks do not work correctly. For example, you may receive an error message that resembles the following when you open Task Scheduler:

This task image is corrupt or has been tampered with.

When you close the message, the task no longer appears in Task Scheduler.

Workaround

Important When you use the following registry workaround, any tasks that may have been corrupted by malware will also be validated. We recommend that you validate the Action that is associated with each task, including inbox tasks, to verify that the task is valid and is not associated with malware.

Important This section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly. Therefore, make sure that you follow these steps carefully. For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs. For more information about how to back up and restore the registry, click the following article number to view the article in the Microsoft Knowledge Base:

322756 How to back up and restore the registry in Windows

NoteYou must perform the following steps while logged on as a local user who has administrative permissions.

To recover the corrupted tasks, follow these steps:

Step 1: Locate the corrupted task references in the registry and in Task Scheduler

To do this, follow these steps:

  1. Open Task Scheduler.
  2. Expand Task Scheduler Library tree in the left pane, and located the folder that contains the corrupted task. Make a note of the location of the corrupted task. You will need this information later in this procedure.
  3. Locate the registry sub-key that corresponds to the corrupted task in one of the following registry sub-key. You can locate the subkey by searching for the name of the task:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree

Click the registry sub-key that corresponds to the corrupted task, and then make a note of the GUID value in the “Id” entry. For example, {2911FBBD-A0AA-4A79-A8EE-84EF7555A71B}. You will need this information in the next step of this procedure.

  1. Locate the registry sub-key that corresponds to the corrupted task in one of the following registry three sub-keys. To locate this sub-key, search for the GUID value that you noted in the previous step. For example, {2911FBBD-A0AA-4A79-A8EE-84EF7555A71B}. The task will exist in only one of the three locations:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Plain

Or:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Logon

Or:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Boot

Make a note of the registry location of the corrupted task. You will need this information later in this procedure.

Step 2: Create a temporary copy of the corrupted task file

To do this, follow these steps:

  1. Open the following folder in Windows Explorer:
  2. %SYSTEMDRIVE%\Windows\System32\Tasks\<Corrupted_Task_Name>
  3. Locate and then copy the task file that corresponds to the corrupted task to a temporary location.


Step 3: Clean up the corrupted task

To do this, follow these steps:

  1. Delete the task file that corresponds to the corrupted task from the Tasks folder (%SYSTEMDRIVE%\Windows\System32\Tasks).
  2. Delete the registry sub-key that corresponds to the corrupted task from the following registry sub-key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree

  1. Delete the registry sub-key that corresponds to the corrupted task from the following registry sub-key. The task will be in GUID format. For example, {2911FBBD-A0AA-4A79-A8EE-84EF7555A71B}.Note Refer to the note that you made earlier in this procedure to locate the registry folder.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks

  1. Delete the registry sub-key that corresponds to the corrupted task from one of the following registry three sub-keys. The task will exist in only one of the three locations and will be in GUID format. For example, {2911FBBD-A0AA-4A79-A8EE-84EF7555A71B}.Note Refer to the note that you made earlier in this procedure to locate the registry folder.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Plain

Or:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Logon

Or:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Boot

Step 4: Re-create the task by using the temporary backed-up copy

To do this, follow these steps: To do this, follow these steps:

  1. Open Task Scheduler.
  2. Expand Task Scheduler Library tree in the left pane, and open the folder that previously contained the corrupted task.Note Refer to the note that you made earlier in this procedure to locate the folder.
  3. Right-click the folder that previously contained the corrupted task, and then click Import Task.
  4. In the Open dialog box, select All files (*.*). Browse to the temporary folder that contains the backed up task file, and then select the task file. Click Open. The new task is created and is visible in Task Scheduler.

Or, you can use the following command line command to restore the backed-up task:

Schtasks.exe /CREATE /TN <New_Task_Name> /XML <Xml_File_Name>

MS10-092: Vulnerability in Task Scheduler could allow for elevation of privilege.