Posted on March 1st, 2007 by Mark Sheppard
I’m currently downloading the March CTP of Visual Studio Orcas. There’s two versions this month, a Virtual PC image and for the first time a full install. Combined this all totals 11.9GB and 20 files to download!
So how long will it take to download on my 4Mbs Internet Connection?
1> New-TimeSpan -seconds $(11.9gb / (4mb / 8))
Days : 0
Hours : 6
Minutes : 46
Seconds : 11
Milliseconds : 0
Ticks : 243710000000
TotalDays : 0.282071759259259
TotalHours : 6.76972222222222
TotalMinutes : 406.183333333333
TotalSeconds : 24371
TotalMilliseconds : 24371000
Of cause, that’s the theoretical maximum of my line, in reality I tend to get about 480KBs:
2> New-TimeSpan -seconds $(11.9gb / (480kb))
Days : 0
Hours : 7
Minutes : 13
Seconds : 16
Milliseconds : 0
Ticks : 259960000000
TotalDays : 0.30087962962963
TotalHours : 7.22111111111111
TotalMinutes : 433.266666666667
TotalSeconds : 25996
TotalMilliseconds : 25996000
Not bad, it’ll e done by breakfast J
I often compute this on a calculator, but PowerShell offers us a better alternative, but typing it into the command line every time will get old very fast. So I’ve just knocked together a little script to do this for me.
Usage: Calc-DownloadTime.ps1 <downloadSize> [connectionSpeed]
Both parameters are int64’s and if connectionSpeed is not supplied, it will try to use a global variable named $networkSpeed. Should the $networkSpeed global variable not exist, the script will throw an exception.
1 Comment »
Filed under: PowerShell
Posted on February 27th, 2007 by Mark Sheppard
Mamood had a problem! He needed to get some information on a bunch of machines he manages and like a good follower of the church of PowerShell, he fired up his favourite blue and white command line tool (which he for some reason changes to be black with green text) and set about trying to obtain the information required.
Somewhere along the way he got stuck, so somehow he managed to find his Office Communicator window in amongst what must have been at least 50 others including several terminal server client sessions (each containing at least another 20 windows) and contacted me. He needed to perform a nslookup on an IP Address and grep the resolved host name for his information.
I sent him back the following three functions (cobbled together on the spur of the moment):
function Ping-Host([string]$hostName) {
$pinger = new-object system.Net.NetworkInformation.Ping;
$pinger.Send($hostName);
}
function Resolve-HostByAddress([string]$ipAddress) {
return [System.Net.Dns]::GetHostByAddress($ipAddress);
}
function Resolve-HostByName([string]$hostName) {
return [System.Net.Dns]::GetHostByName($hostName);
}
I then told him to save them in a script called networkTools.ps1 and then Dot-source them into his session and have a play to see if they do what he wanted:
[D:\PsScripts]
1> . .\networkTools.ps1
[D:\PsScripts]
2> resolve-hostByName “localhost”
HostName Aliases AddressList
——– ——- ———–
machine1.cpatinliteral.net {} {127.0.0.1}
[D:\PsScripts]
3> resolve-hostByAddress “192.168.8.5″
HostName Aliases AddressList
——– ——- ———–
machine1.cpatinliteral.net {} {192.168.8.5}
[D:\PsScripts]
4> “machine1″, “machine2″, “machine3″ | % { resolve-hostByName $_ }
HostName Aliases AddressList
——– ——- ———–
machine1.captainliteral.net {} {192.168.8.5}
machine2.captainliteral.net {} {192.168.8.3}
machine3.captainliteral.net {} {192.168.8.8}
No Comments »
Filed under: PowerShell
Posted on February 18th, 2007 by Mark Sheppard
One of the reasons why PowerShell is so good and so easy to sell to people is because of .NET. PowerShell is a .NET 2.0 application and it uses .NET to achieve virtually everything it does – but how can users leverage to power of .NET from within PowerShell?
How do I create an object?
There are basically two way to get an object to work with in PowerShell, either call new-object or get one returned by calling something.
Things return objects?
[D:\PsScripts]
1> get-process
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
——- —— —– —– —– —— — ———–
256 12 77716 70736 558 0.91 5680 powershell
What’s actually going on here? It turns out that the get-process cmdlet returns .NET objects, in the above case it’s an array of System.Diagnosticts.Process objects and that allows us to work with them the same as if we had created them in code.
You can work with objects by either keeping a reference to them or by passing them down the pipeline to another cmdlet, object or piece of script. If you want to know what you can do with an object, call get-member:
[D:\PsScripts]
2> $processes = get-process
[D:\PsScripts]
3> $processes.Length
90
[D:\PsScripts]
4> get-member -InputObject $processes
TypeName: System.Object[]
Name MemberType Definition
—- ———- ———-
Count AliasProperty Count = Length
… … …
An object array? Where are the process objects?
[D:\PsScripts]
5> get-member -InputObject $processes[0]
TypeName: System.Diagnostics.Process
Name MemberType Definition
—- ———- ———-
Handles AliasProperty Handles = Handlecount
Name AliasProperty Name = ProcessName
… … …
1 Comment »
Filed under: PowerShell
Posted on February 1st, 2007 by Mark Sheppard
I’ve been using PowerShell now for a few months and it’s become a standard feature on my desktop. Having used it for a while I have some observations to share:
IDE
PowerShell doesn’t have an IDE shipped as part of the product, so the out-of-the-box experience of scripting it limited to nothing more fancy than Notepad. My experience though has been that an IDE of some sorts really is required for working with anything but the most basic .ps1 script files. Additionally, I’ve had bugs in one-liners that pipe together several command and full IDE support for pipelines would be a real winner – imagine being able to set a breakpoint between piped commands.
The main features that I would like an IDE for PowerShell to provide are:
- Colourisation of text – Different types and operators get different colours when viewed in an IDE, so you can see what you’re working on more clearly.
- Full Debugging capabilities – Including breakpoints and watch windows. Without these basic tools, scripts get littered with write-Debug commands all over the place, it kind of reminds me of days gone by when I’ve been debugging ASP3 web applications – doable, but not as easy as it should be.
- IntelliSense – tab completion is a godsend, but you need to know what’s there before it really works, I’m constantly piping to get-member to find out what an object supports.
4 Comments »
Filed under: PowerShell
Posted on January 31st, 2007 by Mark Sheppard
I spent a lot of time automating SharePoint when the company I work for installed SharePoint Portal Server 2003, so I was quite disappointed when SharePoint version 3 was released without PowerShell support – after all, Exchange 2007 managed it and it’s part of the Office 2007 Server suite, so why didn’t the other server products?
On a positive note though, I did find that stsadm.exe had been extended to now support a lot more operations:
[C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN]
3> .\stsadm.exe –help
Usage:
stsadm.exe -o <operation> [<parameters>]
stsadm.exe -help [<operation>]
Operations:
activatefeature
addalternatedomain
addcontentdb
addpath
addpermissionpolicy
addsolution
addtemplate
adduser
addwppack
addzoneurl
authentication
backup
backuphistory
binddrservice
blockedfilelist
canceldeployment
changepermissionpolicy
copyappbincontent
createadminvs
creategroup
createsite
createsiteinnewdb
createweb
databaserepair
deactivatefeature
deleteadminvs
deletealternatedomain
deleteconfigdb
deletecontentdb
deletegroup
deletepath
deletepermissionpolicy
deletesite
deletesolution
deletetemplate
deleteuser
deleteweb
deletewppack
deletezoneurl
deploysolution
deploywppack
disablessc
displaysolution
email
enablessc
enumalternatedomains
enumcontentdbs
enumdeployments
enumgroups
enumroles
enumservices
enumsites
enumsolutions
enumsubwebs
enumtemplates
enumusers
enumwppacks
enumzoneurls
execadmsvcjobs
export
extendvs
extendvsinwebfarm
forcedeletelist
getadminport
getproperty
getsitelock
geturlzone
import
installfeature
listlogginglevels
localupgradestatus
managepermissionpolicylevel
migrateuser
provisionservice
refreshdms
refreshsitedms
registerwsswriter
removedrservice
removesolutiondeploymentlock
renameserver
renameweb
restore
retractsolution
retractwppack
scanforfeatures
setadminport
setapppassword
setconfigdb
setlogginglevel
setproperty
setsitelock
setworkflowconfig
siteowner
spsearch
spsearchdiacriticsensitive
syncsolution
unextendvs
uninstallfeature
unregisterwsswriter
updateaccountpassword
updatealerttemplates
updatefarmcredentials
upgrade
upgradesolution
upgradetargetwebapplication
userrole
For information about other operations and parameters,
use “stsadm.exe -help” or “stsadm.exe -help <operation>”
But how useful are these commands? Consider the example of enumsites – this command lists all Site Collections or a given Web Application.
2 Comments »
Filed under: PowerShell, SharePoint
Posted on January 29th, 2007 by Mark Sheppard
One of the comments I had on a post I did last week was about how to run scripts. It’s a fair point, somebody new to PowerShell will find it a little odd that they can’t just run a script found on the Internet – I find it reassuring.
On a newly installed PowerShell system, running a script will result in something like the following:
[D:\PsScripts]
1> & D:\PsScripts\test-scriptExecution1.ps1
File D:\PsScripts\test-scriptExecution1.ps1 cannot be loaded because the execution of scripts is disabled on this syste
m. Please see “get-help about_signing” for more details.
At line:1 char:38
+ D:\PsScripts\test-scriptExecution1.ps1 <<<<
Understanding the Execution Policy
The reason for this is the Execution Policy in place on the machine prevents all scripts from running by default. There are 4 Execute Policies defined in PowerShell, according to the help files, they are:
- Restricted – Does not load configuration files or run scripts. “Restricted” is the default.
- AllSigned – Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on the local computer.
- RemoteSigned – Requires that all scripts and configuration files downloaded from the Internet be signed by a trusted publisher.
- Unrestricted – Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet, you are prompted for permission before it runs.
To control execution policies, PowerShell ships with a couple of cmdlets Get-ExecutionPolicy and Set-ExecutionPolicy. They basically do what they say on the tin:
2 Comments »
Filed under: PowerShell
Posted on January 22nd, 2007 by Mark Sheppard
I’ve been obsessed since Adrian (ps1.soapyfrog.com) posted his Sudoku solving PowerShell script a couple of weeks ago. When I first read his post on the subject, I pulled down his script and ran it - at the time he didn’t know how long it would take to solve the harder of the two puzzles he posted - after about an hour PowerShell had crashed on my computer! Since then Adrian has posted saying that his script takes 1.2 days to solve his harder puzzle!
Having peeked at his script I quickly discovered that it works on a brute-force principle (i.e. if you don’t know what number you should have in a square, guess), this seemed to work well for the easier of his samples (solved in less than a second). I decided that I’d see if I could do better and learn a few things along the way. And so started my obsession with implementing a speedy Sudoku solver in PowerShell – this shouldn’t have taken two weeks, but work, life and a couple of other things got in the way. I swear, I don’t know how people play with technology and constantly post about it.
To start with, I had no idea how to solve a Sudoku puzzle with a computer, yet alone in PowerShell – Enter a trusty search engine to the rescue. I quickly found Andrew’s Sudoku solver. Now, what’s interesting about Andrew’s site is that he not only solves Sudoku, he shows you step by step how to do it and he’s published over 30 different strategies for solving Sudoku, complete with pictures. J
7 Comments »
Filed under: PowerShell
Posted on January 2nd, 2007 by Mark Sheppard
PowerShell Community Extensions is a great addition to PowerShell that supplements the out-of-the box set of cmdlets. However, it doesn’t work out-of-the-msi on an x64 platform.
When installing, I opted to use the Shared Profile, but got the following when I tried to run PowerShell:
Windows PowerShell
Copyright (C) 2006 Microsoft Corporation. All rights reserved.Add-PSSnapin : Windows PowerShell snap-in Pscx is not installed on the machine.
At C:\Documents and Settings\Mark\MyDocs\WindowsPowerShell\profile.ps1:38 char:13
+ Add-PSSnapin <<<< Pscx
Transcript started, output file is C:\Documents and Settings\Mark\MyDocs\WindowsPowerShell\Transcripts\20070102.1
43613.7364.txt
[C:\Documents and Settings\Mark]
1> Get-PSSnapinName : Microsoft.PowerShell.Core
PSVersion : 1.0
Description : This Windows PowerShell snap-in contains Windows PowerShell management cmdlets used to manage components
of Windows PowerShell.Name : Microsoft.PowerShell.Host
PSVersion : 1.0
Description : This Windows PowerShell snap-in contains cmdlets used by the Windows PowerShell host.Name : Microsoft.PowerShell.Management
PSVersion : 1.0
Description : This Windows PowerShell snap-in contains management cmdlets used to manage Windows components.
Name : Microsoft.PowerShell.Security
PSVersion : 1.0
Description : This Windows PowerShell snap-in contains cmdlets to manage Windows PowerShell security.
Name : Microsoft.PowerShell.Utility
PSVersion : 1.0
Description : This Windows PowerShell snap-in contains utility Cmdlets used to manipulate data.
[C:\Documents and Settings\Mark]
2> Get-PSSnapin -Registered
Name : PowerGadgets
PSVersion : 1.0
Description : Generates Charts, Gauges and Maps Gadgets from Windows PowerShell data
Well the snap-in isn’t registered on my system, let’s try PowerShell (32bit):
1 Comment »
Filed under: PowerShell
Posted on January 2nd, 2007 by Mark Sheppard
I just needed to know how long it was since my box was last rebooted. Windows Vista has a nice feature where this is now a property of the Performance tab in Task Manager. But alas, there’s no such nice functionality in Windows 2K3. Usually I end up in PerfMon to get the number of seconds the box has been up and then in calculator to convert this into real time.
Enter PowerShell to the rescue:
function GLOBAL:Get-SystemBootupTime([String]$computer=”localhost”) {
  $wmiOsInformation = Get-WmiObject -computer $computer -class Win32_OperatingSystem
  $wmiOsInformation.ConvertToDateTime($wmiOsInformation.LastBootUpTime)
}
function GLOBAL:Get-SystemUptime([String]$computer=”localhost”) {
  $wmiPerfOsSystem = Get-WmiObject -computer $computer -class Win32_PerfFormattedData_PerfOS_System
  $wmiPerfOsSystem.SystemUpTIme
}
# Get System Bootup time
PS C:\> Get-SystemBootupTime
21 December 2006 17:16:02
# Get system uptime in seconds
PS C:\> Get-SystemUptime
1016328
Not bad, I can now see the system uptime in seconds, but I want the result formatted
function GLOBAL:Get-SystemUptimeFormatted([String]$computer=”localhost”) {
  $wmiPerfOsSystem = Get-WmiObject -computer $computer -class Win32_PerfFormattedData_PerfOS_System
[TimeSpan] $systemUptime = New-TimeSpan -seconds $wmiPerfOsSystem.SystemUpTIme
  [String]::Format(”{0:G}”, $systemUptime)
}
PS C:\> Get-SystemUptimeFormatted
11.18:53:16
Job done! As a developer, I tend towards using .NET all over, so I’ve probably missed some rather subtle ways of achieving the formatting with PowerShell.
You can get a lot of other useful information from the WMI classes that could be the focus of other functions:
PS C:\> $computer = “localhost”
PS C:\> $wmiOsInformation = Get-WmiObject -computer $computer -class Win32_OperatingSystem
PS C:\> $wmiOsInformation SystemDirectory : C:\WINDOWS\system32
Organization : My Org
BuildNumber : 3790
RegisteredUser : Me
SerialNumber : xxxxx-xxx-xxxxxxx-xxxxx
Version : 5.2.3790
4 Comments »
Filed under: PowerShell
Posted on September 10th, 2006 by Mark Sheppard
Windows PowerShell is an fantastic tool that will become part of my “used daily†toolkit. I came across Jeffrey Snover’s blog a couple of weeks ago and have really enjoyed reading it. I also recommend the 10 part series on managing Active Directory with powerShell on the /\/\o\/\/ PowerShelled blog, it is very insightful but I felt that I need something more basic to learn the product from the ground up.
Enter Jeffrey’s recently published presentation (from tech-Ed 2006) on PowerShell – this guy makes an hour and 15 minutes of the command line amusing to watch and very informative. I’d prescribe it to all IT Pros as this is going to be your tool of choice in the future.
A couple of things stand out from the presentation. One is that all other scripting mechanism shipped with windows are “feature complete†and two is that in Exchange 2007 (E 12), the MMC admin interface calls PowerShell to perform functions.
The implications of the first one are massive, cscript/wscript/WSH will not be extended in the future and CMD will not get any more features added! PowerShell will be the ONLY scripting tool for admin scripting and will I imagine replace CMD. This is a big shift and if you don’t embrace PowerShell in the Longhorn Server timeframe, you’ll find yourself without any scripting tools and without any community support!
No Comments »
Filed under: PowerShell