Ads 468x60px

Showing posts with label Hack. Show all posts
Showing posts with label Hack. Show all posts

Creating Registry Values

In a previous tip we introduced the new function New-RegKey that could create one or more registry keys. Here is a function that creates registry values. It uses New-RegKey internally if the key you specify does not yet exist, so make sure you include both functions
function New-Regkey {
  
param($key)

  
$key = $key -replace ':',''
  $parts = $key -split '\\' 
  $tempkey = ''
  $parts | ForEach-Object {
    
$tempkey += ($_ + "\")
    
if ( (Test-Path "Registry::$tempkey"-eq $false)  {
      
New-Item "Registry::$tempkey"   | Out-Null
    }
  }
}
function Set-RegistryValue {
  
param(
    
$key,
    
$name,
    
$value,
    
$type='String'
  )
 
  $key = $key -replace ':',''
  New-Regkey $key
  $regkey = "Registry::$key"
  Set-ItemProperty -Path $regkey -Name $name -Value $value -Type $type
}
Now check out how easy it is to set a new registry value! If the key is missing, it will also be created:
Set-RegistryValue HKCU:\Software\TestKey Testvalue -Value 123 –Type DWORD

Extract Paths from Strings Like Environment Variables

If you'd like to add a path to the %PATH% environment variable, that's easy:
PS$env:path += ';c: \newpath'
But how would you remove a path? Here's a clever way:
PS> (($env:path -split ';'-ne 'C:\Windows\system32') -join ';'
To better understand the technique used, check out this part first:
PS$env:path -split ';'
It will separate the paths in %PATH%. Next, -ne will return all paths that do not match the one you want to get rid of. Finally, -join adds these parts back to a semicolon-separated list.

Copying Files in the Background

In a previous tip we showed how you can use the BITS service to copy files. The main advantage of BITS is that it can copy things silently in the background, and it is resilient to interruptions such as reboots. After a reboot, BITS will continue the copy process, so this can be a good starting point to create a robust backup mechanism.
Import-Module BitsTransfer 

# adjust source and destination to your needs:

$Source
 = "$env:userprofile\downloads\*.exe"
$Destination
 = "C:\BackupFolder\" 

if
 ( (Test-Path $Destination-eq $false)
{
 $null = New-Item -Path $Destination -ItemType Directory
}


$params
 = @{
    
Source = $Source
    
Destination = $Destination
    
Description = "Backup"
    
DisplayName = "Backup"
    
Asynchronous = $true


Start-BitsTransfer
 @params
This script would copy all downloaded EXE files to a backup location. Since the backup is running in the background, you get back immediately a response like this:
JobId                                       DisplayName                      TransferType                     JobState                         OwnerAccount               
-----                                       -----------                      ------------                     --------                         ------------               
0488f61c-ab39-4661-81ce-b8f8a3... Backup                             Download                          Transferring                    TobiasAir1\Tobias 
To check progress, you can check progress using Get-BITSTransfer. You can call this cmdlet anytime, even next week after a couple of restarts. It may look like this:
PS> Get-BitsTransfer

JobId                                           DisplayName                   TransferType                     JobState                         OwnerAccount              
-----                                           -----------                   ------------                     --------                         ------------              
287ed32a-ec3a-4e13-b88d-9f288f...    Upload TUDI Data             Upload                             Transferred                     TobiasAir1\Tobias          
546c7a07-315b-4900-b1de-134aaa...    Upload TUDI Data             Upload                             Transferred                     TobiasAir1\Tobias          
0488f61c-ab39-4661-81ce-b8f8a3...    Backup                          Download                           Transferring                   TobiasAir1\Tobias     
You may see other BITS operations in this list as well since Windows is using the BITS service, too, to receive updates and upload data.
To actually complete the backup once it is done, you need to call Complete-BITSTransfer:
Import-Module BITSTransfer

Get-BitsTransfer
 |
  
Where-Object { $_.DisplayName -eq 'Backup' } |
  
ForEach-Object {   $_ | Select-Object -Property *

        
if ($_.JobState -eq 'Transferring') {
           
$transferred = $_.FilesTransferred  
           
$total = $_.FilesTotal
           
$text = '{0} of {1} files transferred. Try again later.' -f 
$transferred
$total
           
Write-Warning $text
     } 
else {
           
$done = $_.TransferCompletionTime
          
Complete-BitsTransfer $_
          
Write-Warning "Backup process done at $done"
     }
  }

Checking Size of Downloads-Folder

Whenever you download something with IE, by default the files get stored in your personal download folder. Often, over time a lot of garbage can accumulate. This line tells you just how much data you store in this folder:
$folder = "$env:userprofile\Downloads"
Get-ChildItem
 -Path $folder -Recurse -Force -ea 0 |
  
Measure-Object -Property Length -Sum |
  
ForEach-Object {
    
$sum = $_.Sum / 1MB
    
"Your Downloads folder wastes {0:#,##0.0} MB storage" -f $sum
}
You may be surprised just how much stuff has been collected there.

Converting Letters to Numbers and Bit Masks


Sometimes, you may need to turn characters such as drive letters into numbers or even bit masks. With a little bit of math, this is easily doable. Here is a sample:

Let's start with a dirty and unsorted list of drive letters. This is how PowerShell can sort and normalize them:
$DriveList = 'a''b:''d''Z''x:'
$DriveList |
    
ForEach-Object { $_.toUpper()[0] } |
     Sort-Object
With a little more code, you get back drive indices, taking advantage of the ASCII code of characters:
$driveList = 'a''b:''d''Z''x:'
$DriveList |
    
ForEach-Object { $_.toUpper()[0] } |
    
Sort-Object |
    ForEach-Object { ([Byte]$_-65 }
To turn this into a bit mask, use the Pow() function:
$driveList = 'a''b:''d''Z''x:'

Implicit Foreach in PSv3


PowerShell v3 Beta is available for quite some time now, so every now and then we start tossing in some PowerShell v3 tips. We'll clearly mark them as such since they only run on PowerShell v3, not v2. This is something new in PowerShell v3:

When you work with array data, in previous PowerShell versions you had to loop through all elements to get to their properties and methods. No more in PowerShell v3. PowerShell now detects that you are working with an array and applies your call to all array elements. So with this line you could gracefully close all running notepad.exe.
PS> (Get-Process notepad).CloseMainWindow()
Previously, you would have had to write:
PSGet-Process notepad | ForEach-Object { $_.CloseMainWindow() }
 
Blogger Wordpress Gadgets