Change NTFS folder Owner using Powershell

In this post a quick way of changing the owner of a ntfs folder is illustrated.

Step1: Get the Acl’s of the folder on which we want to change the owner.
[C:\Users\SivaMulpuru]
PS:1 >$acl = Get-Acl C:\Scripts
List the Acl’s
[C:\Users\SivaMulpuru]
PS:2 >$acl | FL
Path : Microsoft.PowerShell.Core\FileSystem::C:\Scripts
Owner : SivaMulpuru-PC\SivaMulpuru
Group : SivaMulpuru-PC\None
Access : BUILTIN\Administrators Allow FullControl
Everyone Allow FullControl
NT AUTHORITY\SYSTEM Allow FullControl
Audit :
As you can see the owner is set to my user account (SivaMulpuru) and in this case we want to change it to local builtin administrator account
Step2: Set the owner to BuiltIn Admin Account using the SetOwner property.
[C:\Users\SivaMulpuru]
PS:3 >$acl.SetOwner([System.Security.Principal.NTAccount] “Administrators”)
List the Acl’s again
[C:\Users\SivaMulpuru]
PS:4 >$acl | FL
Path : Microsoft.PowerShell.Core\FileSystem::C:\Scripts
Owner : BUILTIN\Administrators
Group : SivaMulpuru-PC\None
Access : BUILTIN\Administrators Allow FullControl
Everyone Allow FullControl
NT AUTHORITY\SYSTEM Allow FullControl
Audit :
we are not done yet, even though the Acl’s list Admin as the owner the value is not effective because the changes are not committed.
Step3: Set-Acl (Very Critical)
[C:\Users\SivaMulpuru]
PS:5 >Set-Acl C:\Scripts $acl

Troubleshooting Tip

If you receive the following error, try running powershell as administrator.
Set-Acl : The security identifier is not allowed to be the owner of this object.

Script

###########################################################################
#
#
NAME: Change Owner of NTFS Container
#
#
AUTHOR: SivaMulpuru
#
#
COMMENT:
#
#
VERSION HISTORY:
#
1.0 6/29/2011 – Initial release
#
#
##########################################################################
$acl = Get-Acl C:\Scripts
$acl.SetOwner([System.Security.Principal.NTAccount] Administrators)
Set-Acl C:\Scripts $acl
#Moving further, Add Access rules
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule(Domain-Grp,Modify, ContainerInherit, ObjectInherit, None, Allow)))
Set-Acl C:\Scripts $acl

Citrix Provisioning Server with PowerShell

###########################################################################
#
#
NAME: Citrix_PVS_With_PowerShell
#
#
AUTHOR: SivaMulpuru
#
#
COMMENT: automate advanced citrix pvs tasks
#
can be used in disaster recovery situations to quickly bring up the infrastructure
#
#
VERSION HISTORY:
#
1.0 6/27/2011 – Initial release
#
#
##########################################################################

$devicename = child01
$MACRegEx = ([0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2})
$Domain = MULPURU.LOCAL
$OU = Computers/PVSMachines
$TargetDevice = mcli-get deviceinfo -p devicename=$devicename -f devicemac,adTimestamp
# Checking for existing target device
# mcli-get deviceinfo returns an array of strings, the 4 array entry contains the Number of records found
# Example: – Record #1, hence we use it with -match to find out its existence
if($TargetDevice[3] -match 1)
{
$devicename target device already exists.
if($TargetDevice[4] -match $MACRegEx)
{
$MAC1 = $Matches[1]
$devicename has the $MAC1 as MACAddress
#can be used to create a VM using this MACAddress

}
#adTimestamp contains the time the Active Directory machine account password as generated. Default=0
#we can use this to find out if the machine account is created
#Example: – adTimestamp: 1308685816
#to get the timestamp we split the string with “:”, get the second array value and trim out the empty spaces
if($TargetDevice[5].split(:)[1].Trim() -eq 0)
{
mcli-Run AddDeviceToDomain -p deviceName
=$devicename, domain=$Domain , organizationUnit=$OU
if(!$?)
{
PVS target device $devicename adding to domain failed.
continue
}
Target Device $devicename successfully added to domain and placed under $OU.
}
else
{
Target Device $devicename Computer Object already exists.
}
}

Provision VM on Hyper-V Cluster

The following code provides a scripted way to provision a Virtual Machine on a Hyper-V Cluster using SCVMM Powershell commandlets.
Step1
Create a Template VM with required Hard Disk and place it to the SCVMM Library
Step2
Run the script
Logic statements >

$Template = Get-Template -VMMServer $VMMServer | where {$_.Name -eq VDI_Template}

$Template holds the VDI Template Object that was created in step 1

$BestHost = $(Get-VMHostRating -Template $Template -VMName temp -VMHostGroup $VMClusterHostGroup -DiskSpaceGB 15 | sort rating -Descending | select -First 1 -Property VMHost).VMHost

$BestHost will hold the suitable hyper-v host from the cluster, it does by getting all the hosts from the cluster, sorts them by the rating and selects the first one.

$Path = $(Get-VMHostVolume -VMHost $BestHost | where {$_.IsClustered -and $_.IsAvailableForPlacement -and $_.Capacity -gt 15GB } | select Name -First 1).Name

The VM Path is selected by querying volume for the selected Hyper-V host and filters out the local disks with $_.IsClustered and Quorum disk with $_.Capacity properties.

Complete Script

###########################################################################
#
#
NAME: VM Provion on Hyper-V Cluster
#
#
AUTHOR: SivaMulpuru
#
#
COMMENT:
#
#
VERSION HISTORY:
#
1.0 6/24/2011 – Initial release
#
#
##########################################################################

# Add VMM snapin
Add-PSSnapin -Name Microsoft.SystemCenter.VirtualMachineManager
$VMName = ChildVM
$VMMServer = SCVMM01.MULPURU.LOCAL
Get-VMMServer -ComputerName
$VMMServer
$MAC1 = New-PhysicalAddress -Commit
PVS MAC $MAC1
$MAC2 = New-PhysicalAddress -Commit
VM MAC $MAC2
$Template = Get-Template -VMMServer $VMMServer | where {$_.Name -eq VDI_Template}
$BestHost = $(Get-VMHostRating -Template $Template -VMName temp -VMHostGroup $VMClusterHostGroup -DiskSpaceGB 15 | sort rating -Descending | select -First 1 -Property VMHost).VMHost
Placing $VMName on $BestHost
$Path = $(Get-VMHostVolume -VMHost $BestHost | where {$_.IsClustered -and $_.IsAvailableForPlacement -and $_.Capacity -gt 15GB } | select Name -First 1).Name
$VMName path is $Path
$JobGroupID = [Guid]::NewGuid().ToString()
JobGroupID is $JobGroupID
$CPUType = Get-CPUType -VMMServer $VMMServer | where {$_.Name -eq 2.20 GHz Opteron (dual core)}
New-VirtualNetworkAdapter -VMMServer
$VMMServer -JobGroup $JobGroupID -PhysicalAddress $MAC1 -PhysicalAddressType Static -VirtualNetwork STREAMING -VLanEnabled $false -VMNetworkOptimizationEnabled $false -MACAddressesSpoofingEnabled $false
New-VirtualNetworkAdapter -VMMServer
$VMMServer -JobGroup $JobGroupID -PhysicalAddress $MAC2 -PhysicalAddressType Static -VirtualNetwork INTERNET -VLanEnabled $false -VMNetworkOptimizationEnabled $true -MACAddressesSpoofingEnabled $false -Synthetic
New-HardwareProfile -VMMServer
$VMMServer -Owner MULPURU\Siva -CPUType $CPUType -Name HWProfile$JobGroupID -Description Profile used to create a VDI VM Template -CPUCount 4 -MemoryMB 512 -ExpectedCPUUtilization 20 -DiskIO 0 -CPUMax 100 -CPUReserve 0 -NetworkUtilization 0 -RelativeWeight 100 -HighlyAvailable $true -NumLock $false -BootOrder PxeBoot, CD, IdeHardDrive, Floppy -LimitCPUFunctionality $false -LimitCPUForMigration $false -DynamicMemoryEnabled $true -DynamicMemoryMaximumMB 4096 -DynamicMemoryBufferPercentage 20 -MemoryWeight 5000 -VirtualVideoAdapterEnabled $false -JobGroup $JobGroupID
HWProfile$JobGroupID Hardware Profile created.
$HardwareProfile = Get-HardwareProfile -VMMServer $VMMServer | where {$_.Name -eq HWProfile$JobGroupID}
New-VM -Template
$Template -Name $VMName -Description “” -VMHost $BestHost -RunAsynchronously -RunAsSystem -StartAction NeverAutoTurnOnVM -StopAction SaveVM -SkipInstallVirtualizationGuestServices -UseHardwareAssistedVirtualization $true -JobGroup $JobGroupID -Path $Path -HardwareProfile $HardwareProfile
if(!$?)
{
$VMName creation failed.
$HardwareProfile | Remove-HardwareProfile
continue
}
$VMName creation started.
$HardwareProfile | Remove-HardwareProfile
HWProfile$JobGroupID removed from library.

Remove Bitlocker Volume

Windows 7 installation creates a 100-300 MB partition to easily enable bitlocker with out repartitioning the disk in future, but in cases of virtualization there is no need for bitlocker and this volume can be safely recovered by following steps.

  • Bcdboot c:\windows /s c: from command prompt with admin token.
  • Make c: active using diskpart or disk management.
  • Reboot.
  • Delete the 100-300 volume using disk management.
  • Expand C:\ to utilize the unallocated space.

This can also be prevented in first place by using the following variable in Customsettings.ini (MDT)

DoNotCreateExtraPartition = YES

DRIVER SELECTION PROCESS ON VISTA AND LATER

Ever wondered why windows picks up different driver then the one you wanted it to, the following explains why
In reference to windows deployment using MDT, the drivers are pre-staged and the OS picks the appropriate one from the driver store, my advice is to be a control freek and pre-stage only the absolute required drivers for that particular device using MDT driver groups.
windows selects the driver based on best match of the following

  1. Device hardware ID
  2. Digital Signer Score
  3. Driver Rank

Windows selects the driver with the lowest rank value as the best match for the device.
However, if there are multiple equally ranked drivers that are a best match for a device, Windows uses the driver’s date and version to select a driver.

To picturize the process refer to
%windir%\inf\setupapi.dev.log
In this case I am using my Nvidia Graphic driver (NVIDIA GeForce 8500 GT) selection as example
When windows loaded for the first time it found the Hardware ID’s of this device and matching drivers from the driver store

GraphicHWID
NVIDIA HW ID's

Driver Matches
Two driver matches found


Best driver selected based on above mentioned points

Key Points

  • Windows selects the driver with the lowest rank value as the best match for the device.
  • Unsigned drivers are last choice even when they have low rank value, so don’t ever change the rank manually this will break the integrity of the driver
  • WDDM v1.1 = win7 driver and v1.0 = vista driver.

Hope this aids in your driver troubleshooting ๐Ÿ™‚

C# MULTI-THREADING DEMO

###########################################################################
#
# NAME: MThreadingDemo
#
# AUTHOR:  SivaMulpuru
#
# COMMENT: This Program illustrates the advantage of using multithreading
#
# VERSION HISTORY:
# 1.0 5/4/2011 - Initial release
#
###########################################################################

using System;
using System.Threading;
using System.Diagnostics; //for Stopwatch
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Processor Count is {0}\n"Environment.ProcessorCount);
        Stopwatch stopwatch = new Stopwatch();
        Console.WriteLine("#################SingleThread####################");
        stopwatch.Start();
        Console.WriteLine("Fibonacci of {0} is {1}", 40, Fibonacci(40).ToString());
        Console.WriteLine("Fibonacci of {0} is {1}", 41, Fibonacci(41).ToString());
        stopwatch.Stop();
   Console.WriteLine("Time taken for Fibonacci of {0} and {1} asynchronously is {2} secs",
                            40, 41, stopwatch.ElapsedMilliseconds / 1000);
        Console.WriteLine("#################SingleThreadEnd#################\n");
        Console.WriteLine("#################TwoThreads####################");
        int[] x = new int[2];
        Thread[] threads = new Thread[2];
        x[0] = 40;
        x[1] = 41;
        stopwatch.Restart();
        for (int i = 0; i < x.Length; i++)
        {
            threads[i] = new Thread(DoMath);
            threads[i].Start(x[i]);
        }
        for (int i = 0; i < x.Length; i++)
        {
            threads[i].Join();
        }
        stopwatch.Stop();
   Console.WriteLine("Time taken for Fibonacci of {0} and {1} synchronously is {2} secs",
                            40, 41, stopwatch.ElapsedMilliseconds / 1000);
        Console.WriteLine("#################TwoThreadsEnd#################");
        Console.ReadLine();
    }
    static void DoMath(object n)
    {
        int _n = (int)n;
        Console.WriteLine("Fibonacci of {0} is {1}; Thead ID {2}", 
            _n, Fibonacci(_n).ToString(), Thread.CurrentThread.ManagedThreadId);
    }
    static long Fibonacci(int x)
    {
        if (x <= 1)
            return 1;
        return Fibonacci(x - 1) + Fibonacci(x - 2);
    }
}


Output

Processor Count is 4
#################SingleThread####################
Fibonacci of 40 is 165580141
Fibonacci of 41 is 267914296
Time taken for Fibonacci of 40 and 41 asynchronously is 11 secs
#################SingleThreadEnd#################
#################TwoThreads####################
Fibonacci of 40 is 165580141; Thead ID 3
Fibonacci of 41 is 267914296; Thead ID 4
Time taken for Fibonacci of 40 and 41 synchronously is 7 secs
#################TwoThreadsEnd#################

Prevent External HardDisk from going to sleep

Lately I am loosing my temper with my 2TB external FANTOM External USB Device (GreenDrive); It goes to sleep and makes me wait for a few secs before it wakes up.
So here is a powershell one liner that writes a file periodically, thus preventing it from sleeping.

while($true){new-item h:\tmp.txt -type file; remove-item h:\tmp.txt; sleep 30}

H: is my FANTOM Drive.
tmp.txt is the file thats being written.
sleep 30 is the seconds that the script pauses execution.

This can be further extended by using windows Task Scheduler and running this script at every user login.
If scripting is not your cup of tea, try using NoSleepHD; does the same thing but has a GUI ๐Ÿ˜‰
http://nosleephd.codeplex.com/

Spit out FY H-1B Cap Count from USCIS – PowerShell

###########################################################################
#
# NAME: USCIS_H-1B
#
# AUTHOR:  Siva Mulpuru
#
# COMMENT: This script will spit out FY H-1B Cap Count by parsing through 
#           HTML Body
#
# VERSION HISTORY:
# 1.0 4/27/2011 - Initial release
#
###########################################################################

cls
$ie= new-object -com InternetExplorer.Application
$ie.Navigate('http://www.uscis.gov/h-1b_count')
sleep 1 #Time Allowed to fetch the webpage

if(!(Test-Path c:\tmp))
{
    New-Item -type directory -path c:\tmp
}
if(Test-Path c:\tmp\USCISBuffer)
{
    Remove-Item c:\tmp\USCISBuffer
}
#Save the body content to a file
$ie.Document.Body.InnerText > c:\tmp\USCISBuffer
$ie.Stop()
#Quite IE COM Obj, or else the IE process will still be running after the script exits
$ie.Quit()
#Grab the two lines we are intereted in
$result = Get-Content c:\tmp\USCISBuffer | Select-String "h-1b Regular", "h-1b Master"
#Make sure we got the two lines of text we need
if($result.Length -eq 2){
$Regular =  $result[0] #H-1B Regular Cap 65,000 8,0004/22/2011
$Masters =  $result[1] #H-1B Masterโ€™s Exemption 20,0005,9004/22/2011
}
else
{
Write-Output "Regular and Masters strings not found. Exiting..."
exit
}
#Regular Expression to sperate in to groups <TOTAL Cap> <Filled Cap> <Published Date>
#Regular Expression to sperate in to groups <65,000> <8,000> <4/22/2010>
$regex = "(\d{1,2}[,]?\d{3}\s?)(\d{1,2}[,]?\d{3}\s?)(\d{1,2}/\d{1,2}/\d{2,4})"
function printResult([int] $TotalQuota, [int]$FiledQuota,[DateTime]$PublishedDate)
{
    #Output Format
    Write-Output ("Out of {0:N0}; {1:N0} has been filled on {2:d}" -f $TotalQuota,$FiledQuota,$PublishedDate)
}
if($Regular -match $regex)
{
$TotalQuota = [int] $Matches[1]
$FiledQuota = [int] $Matches[2]
$PublishedDate = [DateTime] $Matches[3]
printResult $TotalQuota $FiledQuota $PublishedDate
}
if($Masters -match $regex)
{
$TotalQuota = [int] $Matches[1]
$FiledQuota = [int] $Matches[2]
$PublishedDate = [DateTime] $Matches[3]
printResult $TotalQuota $FiledQuota $PublishedDate
}

Download Script

USCIS_H-1B.ps1

Sample Output

Out of 65,000; 8,000 has been filled on 4/22/2011
Out of 20,000; 5,900 has been filled on 4/22/2011

WordPress Appliance - Powered by TurnKey Linux