суббота, 12 июня 2010 г.

I've got the power... shell

While testing my projects I often have to do some amount of repetitive actions. Mostly those actions are simple, BUT they do require some time to get them done. Well, I got really annoyed by that and decided to automate those actions.

This is the moment where powershell has entered the house. The essence of my automation is to write a function, add it to powershell profiles on my local and remote machines and run it whenever I need to do the mentioned earlier repetitive actions.

Here is how I did it:

Launch powershell and create its profile by running the following command (if you do not have it already): new-item -type file -path $profile -force
Open the newly created profile in notepad using the following: notepad $profile
Write a function:
function DoSomething([string]$Param1 = "") {
if ($Param1 -eq "") {
Write-Host "You are an IDIOT!!!! You need to enter Param1 value!" -ForegroundColor Red
return
}
$A_OUTPUT = "D:\Destination\"
$B_INPUT = "D:\Files\Images\"
$C_FILE = "Info.txt"

$currentDate = Get-Date -Format yyyyMMdd
$destinationFolder = $A_OUTPUT + $currentDate

if ((Test-Path -path $destinationFolder) -ne $True)
{
New-Item $destinationFolder -type directory | Out-Null
}

$Destination = "$destinationFolder\$Param1"

if ((Test-Path -path $Destination) -ne $True)
{
New-Item $Destination -type directory | Out-Null
}

$files = ls $B_INPUT

$files | %{copy -path $_.FullName -Destination $Destination}
Write-Host "$($files.Count) files" -ForegroundColor Yellow -noNewLine
Write-Host " copied from $B_INPUT to $Destination"

New-Item ($Destination + "\" + $C_FILE) -itemType File -Force | Out-Null
Write-Host "$C_FILE" -ForegroundColor Yellow -noNewLine
Write-Host " is created"
Write-Host "Files $Param1 are reorganizes!" -ForegroundColor Green
}
Save the profile. Here you can bump into a security issue – your operating system can tell you: “you are not allowed to do that, young man”. In this case you should ask it politely:
1. Launch PowerShell as Administrator
2. Run the following command: Set-ExecutionPolicy unrestricted
3. Agree to whatever it’ll ask you :)
After this you are good to go.

Relaunch PowerShell.
Run your function with parameter Test_B13: DoSomething Test_B13
And your function copies files from D:\Files\Images to D:\Destination\\Test_B13 and creates an empty text file Info.txt for description.

You’ll get the following PowerShell response (take into account that the source location has 3 files in it):
3 files copied from D:\Files\Images to D:\Destination\\Test_B13
Info.txt is created
Files Test_B13 are reorganized!

By implementing this into my work process I saved about 50% of time on those routine tasks (or even more if working on remote servers). This time I use more effectively now.

P.S. You can take a quick PowerShell tour here

Also available in russian.

Комментариев нет:

Отправить комментарий