by TechiBee
on February 8, 2013
Powershell provides some sort of parallelism with RunSpaceFactory. It give good control over how many PS instances you want to create at any point of time, etc. It is very good(at the same time complex) and useful. Recently I came across another method in powershell which provides parallelism in a simple way. This is available only in Powershell V3. It has got a very good and large set of new features and one of them is WorkFlows(oh! I love it). When a Foreach is used inside workflow, it is allowing to given -Parallel option and it is doing the trick. That means, to utilize this parallelism you need to write a work flow. Don’t worry that is not too hard and we can write very simple and basic work flow to utilize this new feature.
Here I am giving a simple example on how to use this parallelism in Powershell V3. Here I am querying spooler service status on a list of remote computers using Workflow and I am get them the status in just a single shot.
Try the blow code in Powershell v3 and you will realize what I am saying. But the caveat here is, we can not control how many things it should execute in parallel. If you provide a array of 100 computers, then it will execute on all of them at time t — not sure how much time it will take to complete(I am still researching that).
WorkFlow Run-InParallel {
param(
[string[]]$ComputerName
)
foreach -Parallel ($Computer in $ComputerName) {
$ser = Get-Service -PSComputerName $Computer -Name Spooler
"Status of {0} service on Computer {1} is {2}" -f $ser.Name, $Computer, $ser.Status
}
}
Run-InParallel -ComputerName PC1, PC2, PC3
Hope this tip Helps you. Feel free to comment if you have any suggestions or questions.
{ }
by TechiBee
on February 4, 2013
In today PSTIP section, I will show you how to find empty folder/directories in a disk/folder using powershell. It is a simple scripts that takes directory or Drive name as parameter and searches for empty folders inside that path. Currently this script is not deleting any empty folders but you can update it to remove them if you want. Let me know if any one needs help in that.
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string]$DirectoryName
)
$Directories = Get-ChildItem -Path $DirectoryName -Recurse | ? {$_.PSIsContainer -eq $true }
foreach($Directory in $Directories) {
$Items = Get-ChildItem -Path $Directory.FullName
if(!$items) {
Write-Host "$($Directory.Fullname) is empty"
}
}
Usage:
.\Get-EmptyFolders.ps1 -DirectoryName C:\
Hope this helps. Feedback welcome.
{ }
by TechiBee
on January 31, 2013
Today I got a requirement to use Regular expressions in one of script. After some googling, I came across below Cheat Sheet which is very useful for understanding and using regular expressions in Powershell. I printed and pasted it at my desk for quick reference.
http://www.addedbytes.com/download/regular-expressions-cheat-sheet-v2/pdf/
Hope you will also find this useful.
{ }
by TechiBee
on January 25, 2013
In today’s PSTIP# section will show you how to start a new process and get its PID using powershell. Sometimes we may get requirement to kill the process we started and in such cases knowing the PID will help us in easily killing the process. Unfortunately, Start-Process cmdlet in Powershell will not return the PID of the process after starting it. So we need to depend on [Diagnostics.Process] dotnet class for this purpose.
Code:
$Process = [Diagnostics.Process]::Start("notepad")
$id = $Process.Id
Write-Host "Process created. Process id is $id"
Write-Host "sleeping for 5 seconds"
Start-Sleep -Seconds 5
try {
Stop-Process -Id $id -ErrorAction stop
Write-Host "Successfully killed the process with ID: $ID"
} catch {
Write-Host "Failed to kill the process"
}
Hope this helps.
{ }
by TechiBee
on January 25, 2013
If you have a VMware environment and would like to use VMware Powershell CLI to get list of Snapshots of a given VM, use the below command.
Get-VM -Name "myVM1" | Get-SnapShot
This lists the snapshot name, description and the state of snapshot. Needless to say that you need to connect to you virtual center server before executing this command. Connection can be established by using
Connect-VIServer -Server MYVC1
Hope this helps.
{ }
by TechiBee
on December 6, 2012
Sometimes, we may want to know when a particular Powershell command was executed in our current shell. Simply scrolling through the powershell history will not help you as it just shows the commands. I thought having current date and time as part of poweshell prompt improves the situation to a greater level. It also helps you in recording your changes in proper way.
Here is a small piece of code which helps you to add current date time to powershell prompt. You can change the formatting of the date and time to meet your requirements. But make sure to keep the function name same
Code:
function prompt
{
"PS " + $(get-location) + " [$(Get-Date)]> "
}
Usage and Output:
You can clearly see in the above picture that, I simply copy pasted the code into powershell prompt and it started showing the date time stamp in the prompt section. The date and time are changing when switched to a new directory or simply pressed enter or when entering a command.
This is very helpful for tracking. Add this to your powershell profile to get this prompt every time you open powershell window.
{ }
by TechiBee
on December 6, 2012
In this post I will show you how to query for empty folders/directories in windows computer using powershell. Empty directory/folder means it will not have anything inside it. So our logic is to find child items inside each directory and see if it returns any objects or not. If we get any objects back, the folder is not empty otherwise, it is.
Here is the code and usage example:
FileName : Get-EmptyDirectories.ps1
[cmdletbinding()]
param(
[string]$DirectoryName
)
$Directories = Get-ChildItem -Path $DirectoryName -Recurse | ? {$_.PSIsContainer -eq $true }
foreach($Directory in $Directories) {
$Items = Get-ChildItem -Path $Directory.FullName
if(!$items) {
Write-Host "$($Directory.Fullname) is empty"
}
}
Output:
Read this post if you want to find empty or zero sized files in the file system.
{ }
by TechiBee
on December 6, 2012
In this post let see how to find out the older item(be it folder or file) in a given folder. This can be achieved by reading all files/folders in the given path using Get-ChildItem cmdlet and then sorting by CreationTime Property of each returned output. By default Sort-Object does sorting by ascending order. After sorting, the output is further filtered out using select statement and -First parameter to get the first value in the sorted list which is the oldest item in the folder.
Below is the code.
File Name: Get-OldestItemInFolder.ps1
[cmdletbinding()]
param(
[string]$FolderName
)
$Item = Get-ChildItem -Path $FolderName | Sort CreationTime | select -First 1
Write-Host "Oldest file/folder in $FolderName is $($Item.FullName)"
Write-host "Creation Time is $($item.creationtime)"
Output:
This script takes optional -FolderName parameter if you want to give a specific folder. Otherwise it will run against current directory from where the script is triggered.
{ }
by TechiBee
on November 30, 2012
Today I ran into a situation where my powershell process memory utilization increased to ~2GB. I know why it happened. I ran a Powershell script from the PS window which queries event log from a few computers. The event log data will be high in volume generally and since PS keeps this run time data in memory, the process memory utilization increased to such a high value. In ideal world, the memory should get freed up at the end of script execution, but it didn’t happen.
I can close my powershell process to clear the memory but that is a good solution. Moreover, I did some work in that console and would like to retain/review that(like history). After searching for sometime to find a solution finally I landed on System.GC (Garbage collection) class in Dotnet. It has a method to perform garbage collection for current powershell process. I used the below command to release the memory used by current powershell process.
[System.GC]::Collect()
Do you have any other better method to do this? Feel free to comment.
{ }
by TechiBee
on November 29, 2012
I came across a nice article today explaining various inside outs of vCPUs in VMware ESXi. It talks starting from how vCPUs are formed and its relation with physical CPUs, how multi-threading effects no. of vCPUs, and more importantly how over provisioned vCPUs can cause your Virtual machine to run slow compared with virtual machines with single vCPU.
http://www.virtualinstruments.com/sanbestpractices/best-practices/avoiding-the-virtual-cpu-dilemma-overprovisioning-vcpu-to-pcpu-ratios/
I feel its worth reading..
{ }