Thursday, December 27, 2012

Transcripts : Leverage them

This post is a result of the query asked on the Facebook page of Bangalore PowerShell User Group.
When someone asks a question regarding a Script, it becomes very difficult to follow through it especially if it  is related to some very different domain like SQL, SharePoint (especially for me).

I personally feel one could attempt to even try answering the question if he knows what happens behind the scenes like the Verbose Output associated with the cmdlets one is executing and the type of Objects that are being emitted etc.
Someone could ask the beginners to pipe the Objects into the Get-Member cmdlet to see the intricacies of the Object, or the Process one follows. Here we can leverage transcripts.

Already transcripts are used by PowerShell Gurus in the presentations or trainings , so that later you can see them and find out what went in which order.

In short Transcripts capture whatever appears in the PowerShell Console host.

Note! Windows PowerShell ISE doesn't support the transcripts here but you can follow Scripting Guy's post to make transcripts from ISE as well.

To keep things a bit easier I am going to use PowerShell Console for this post.


The Secret Sauce

The another great feature which I as a beginner found great is that PowerShell follows Universal Code Execution Model, which in simple terms means whatever works in the Script non-interactively can also be run interactively in the Shell and vice-versa.
This is actually great because I can try something interactively on the PowerShell Console, if it works as expected....Grab the code and put it in a Script. It will work too...awesome isn't it.


Example

I would take an elaborate example here . Please bear with me...

Suppose I was trying something related to services like I am trying to change the "start mode" of a running service (I know this is a typical example here)


Suppose I got the following Script form somewhere or someone :

$spooler = Get-Service -Name spooler
if ($spooler.Status -eq 'running'){
Write-Verbose "The Print Spooler Service is running..Trying to change the start mode"
$spooler.startMode = "automatic" # try to set the start  mode here
}
else {
Write-Verbose "The Print Spooler Service is not running"
}

Now when I run it it throws an error "Property 'startMode' cannot be found on this object; make sure it exists and is settable."
I did something obviously wrong here. So if I post the script in some forum they will ask me to post the Error first , if the experienced Power Users are already familiar with the Error the solution will come right in. If not then they will ask you to post the result of when you pipe the $spooler to Get-Member to know exactly what you did wrong.
One would go ahead and simply paste the output in the forum where the formatting goes awry some time. Better way is to do this.

Start the Transcript and Execute the Script Code statement by statement. Also to make things much clearer, after an Object is created pipe it into Get-Member to give clarity on the Object being spitted out.




Now execute the next statement



After you are done. Issue cmdlet "Stop-Transcript".

Now see the Transcript file has captured whatever you did in the Console and it also has the Error which was generated.


Take the file created and post it alongside your Question in the Forum. Someone could see it and observe that there is no property named "startmode" on the Object captured in $spooler.....Hmmmm..so this is where it went wrong ( Who knew ;) )

Now this is a very simple scenario where the transcripts can also be used . You can get creative in supplying the Useful information to others by putting $verbosepreference = 'continue' to include verbose messages in the transcript too( my little POSH trick ).

You can do more with them just pipe yourself to Get-Creative !!

Sunday, December 09, 2012

ServerCore + Create Test Users using Facebook

So Recently my VHD got corrupted and had to make the VHD Boot again work. Thankfully I had all the PowerShell one-liners I used to get my Lab up in less time.

First of all I will add 100 test users by following this awesome Hey Scripting Guys Blog Post.

To make things a bit clear I am on a workstation with RSAT for Active Directory installed and my DC is a servercore machine.

Just to give a hint when I need to run a cmdlet to get any information from the AD, I need to specify the name of the DC with -Server  parameter from where I want to get the information but a new connection will be opened and closed for each cmdlet invocation.

For Example :
Get-ADForest -Server dexservercore.dexter.com

Better way explained in Active Directory PowerShell Blog is to map a PSDrive for better performance. Since I have only one DC in my test environment , when I Import the ActiveDirectory Module it will automatically map a PSDrive on my remote workstation.





Now I don't want to add users like TestUser01, TestUser02... So I began to think from where can I get the data to create few test users for my Domain....and the answer to it is what better than FaceBook :P

Below are the steps I carried out:

Create a new Organizational Unit
I used the following cmdlet to create an OU named 'IT' under dexter.com
   New-ADOrganizationalUnit -Name IT -Path 'dc=dexter,dc=com' -ProtectedFromAccidentalDeletion:$false

Get the relevant data from Facebook

To get the some basic info for the User I used already available PowerShell Module for Facebook( credits to the Developer). On a how to use this module see my earlier post.


Set up a New FB Connection and be ready to retrieve data from Facebook 
 

 You can see that I have stored all my FB friends in $friends, but it doesn't return much information. What can be done here..there is an another cmdlet Get-FBObjectData which returns objects with greater deal of information. So just expand the property ID and pipe it and use as below



Better save this valuable data as a facebook.xml which I will use later.....

Create the AD Users 

Now I have all the information I could gather from Facebook into an XML file for later use. Now I will do some manipulation with the Objects I get from ...Below is the Script block which I used.


Above is the Script block that I used later from the PowerShell ISE.
First import the XML data into variable $facebookdata then do some Object manipulation in order to be consistent with the AD User attributes. Finally pipe it into the New-ADUser cmdlet with the -path parameter specifying the OU in which the Users need to be created.

Note that there is a -whatif parameter added at last to just check if we are headed in the right direction. Execute the Script block to get something like below ouput



If you read it properly it tells our success story :)
Go ahead and remove the -whatif parameter and execute the Script block again

When I run the script block I get two errors :
Below one is because some of my friends have same name and the other one is because of some formatting issues in the name of some friends.





Finally verify the User creation:



That's all for today.
Thank you!

Sunday, October 28, 2012

Deploying AD Domain using PowerShell + Completing LAB Setup

I would like to divide this post in two parts :
1. Deploying a domain dexter.com on my Server Core .
2. Adding my Physical Host running Server 2012 to the domain dexter.com.


Step 1. Deploying domain dexter.com on my Server Core.

First of all I need to add the Active Directory Domain Services role in my Server Core. To get the Active Directory Roles on my Server Core use the following cmdlet


The highlighted entry shows that the AD-Domain-Services Role is already installed on my Server Core. But if it is not then you can issue the following to install it.

Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools

Now the role is installed and till Server 2K8 R2 , one would have gone and run the dcpromo.exe (this one is deprecated now with Server 2012) but here I will try to use PowerShell ..this is the link I followed


Windows Server 2012 has a new module named " ADDSDeployment" and if I check the cmdlets supplied:

 
You get the idea...Now I am going to setup a Forest with the domain "dexter.com" this one is all in my internal Hyper-V network...Remember I added a internal virtual switch using the Add-VMSwitch cmdlet in this Post.

Now my best clue is Install-ADDSForest will do the job, so let's kick the help first :


But wait there is one cool cmdlet Test-ADDSForestInstallation which runs the prerequisites (only) for installing a new forest in Active Directory . You can try this but anyways when you .

##########################################################################
But Wait what's the Secret to all this learning...I sure didn't came up with all this..What I did is as under.

Now what I really did was fire-up server manager on my Server 2012 with GUI (base machine) ..
Click on "Promote this Server to a Domain Controller"



Next a wizard similar to dcpromo.exe shows up



Now in next few pages set the password, domain and forest functional level etc and then finally there will come a screen like the following ....



Now click on the "View Script" to get the equivalent PowerShell script that will do the same changes as you selected in the Wizard...Now use this script (after appropriate changes..ofcourse ) to deploy the Forest on your Server Core....Cool way to learn , eh !

Following is the Script I executed in my Server Core to install the domain dexter.com...I haven't done any changes like changing the Domain and Forest Functional Level but this may change according to your needs.
Import-Module ADDSDeployment
Install-ADDSForest -CreateDnsDelegation:$false -DatabasePath "C:\Windows\NTDS" `
-DomainMode "Win2012"  -DomainName "dexter.com"  -DomainNetbiosName "DEXTER" `
-ForestMode "Win2012" -InstallDns:$true -LogPath "C:\Windows\NTDS" `
-NoRebootOnCompletion:$false -SysvolPath "C:\Windows\SYSVOL" -Force:$true




Step 2. Adding my Physical Host running Server 2012 to the domain dexter.com.

Now, I have a domain "dexter.com" running in my Hyper-V internal network. But the problem is I am connected to a public network on my Physical Host with Server 2012...and through which I access internet.

So here is what I did to add my physical machine (DexterPOSH) to the domain dexter.com and still access the Internet

First let's check the Net Adapter's on my DexterPOSH machine ...


I have renamed the Adapter as "Internet" to indicate that I access Internet through it using Rename-NetAdapter cmdlet. Now assign the IP "192.168.1.1" and DNS "192.168.1.2" to the Hyper-V Internal Adapter with ifindex "18"....wondering how ? see my previous post ...to do it via Shell. 

Now get the Net IP Configuration
 
  Now, If you try Test-Connection 192.168.1.2 (dexservercore) it shows it's online....But when you do this
Test-Connection dexservercore and Test-connection dexter.com....what it does is it looks out through your internet connected address and resolve the IP address.

What I want is that whenever my Machine tries to reslove "dexter.com" it should not go to the Internet rather my inernal network having dexter.com domain on machine dexservercore. There may be a various ways to do this but the simplest solution I tried was to edit the hosts file at location C:\Windows\System32\Drivers\etc\hosts and add the following entry to it.

192.168.1.2    dexter.com
192.168.1.2    dexterservercore


So now whenever I try to contact dexter.com or dexservercore it just resolves the IP address from here (Oh! Wait it means the dexter.com on the Internet can't be resolved by my system now..Guess will have to live with that.. :) :D lol ).

 Now a better way can be to add DNS Server Role to my phsical machine add an entry for it. But this one is simple and effective and works fine too... :)

Last, step now is to add my machine to the domain. Issue the following on the Shell :

   
So the end result is I have a domain dexter.com on my server core (dexservercore) and my physical host (dexterposh) is connected to the domain dexter.com and internet is running fine too....so to just prove it get the connection profile...



 
That's all for now...

Monday, October 22, 2012

Assigning Static IP Address to the Server Core

Now for the first time you boot a Server Core..you get nothing but a Command Shell (cmd.exe).
Now before we begin further let's assign a static IP address to the Server Core VM.

REMINDER : My Lab has server named "DexterPOSH" Server 2012( on Physical Host) and then in Hyper-V a VM named "dexservercore" running Server Core 2012.



Open "Hyper-V Manager" and Right-Click and "Connect" to the VM (start it if it is not started yet)


There are actually three ways to do this..You may be familiar with all three maybe but I wanted to list all the ways to do this.

1. Using Netsh utility - this one is old school

But this one is depreciated see the screenshot below..It's recommending PowerShell ( will cover it in 3rd step)


anyways to set the IP address..first get your interface by using :






Now I have the interface with me...Time to set the IP address (old school)




Okey done.


2 . Using Sconfig utility - Server 2K8 R2 way

Now this Sconfig utility was introduced in Server 2008 R2 to easily get the Server Core up and bring it on the network , to enable the server management remotely. Type Sconfig in the cmd.exe and hit Enter.

Following screen shows up :


Now if you look at the options this one is a great utility to do simple configuration on the Server Core.
Now my IP Address is already set from above Netsh example..But I will still go and show you how to do it.

Press 8 to change the "Network Settings" then it will list the available Network Adapter. Choose the Index# to change the settings on that Network Adapter.


After selecting the Network Adapter. It will list the set of actions that can be performed on the Network Adapter..go ahead and select "1".




After this select the type of IP Address you want, we want the static IP address ...select "S" and then type in the IP Address...easy !



3. The PowerShell Way .. :)

Go the Cmd.exe and typer "Start PowerShell" to get the PowerShell console ....(Yay! Finally )
Now put the POSH console in the foreground.....Let's do this


Now First of all get all the network adapters using Get-NetAdapter...(PowerShell 3.0 dynamically loads the module so no need to load the Net* modules for this)

Then once you have the Adapter status ...go ahead and set the IP Address using New-NetIPAddress cmdlet. I used -whatif before actually using the cmdlet to be sure....then remove -whatif and perform the operation
Refer help for New-NetIPAddress.


Note that if the IP is already set then the New-NetIPAddress cmdlet throws an error. To show this and remove already present IP settings....what I did was use Remove-NetIPAddress cmdlet to remove the earlier settings.

Phewww..! This post went long....Thanks for bearing me (if you made this far).

Choose the method that fits you best..(hopefully the PowerShell way)

Thanks

~Dexter~

Sunday, October 21, 2012

Server 2012 and Server Core...New Plan

I am taking this new initiative to learn Server 2012 along with Server Core.....

Lab Setup:
I have VHD booted Server 2012 with full blown GUI on my Physical Machine (Name - DexterPOSH).
Then I have enabled the Hyper-V role on my this machine and installed a Server Core 2012 on a VM created in the Hyper-V (Name - DexServercore).

Along doing this Lab Setup, I came to learn cool things and I want to share them:

Step 1: Download the trial Server 2012 iso.

Step 2: I have a Windows 7 box , so to test the Server 2012 I am going to VHD Boot the Server 2012 for 180 days (license period) then delete the VHD and the boot entry. Here is a great article on how to do this for Windows 8 but the steps are the same for Server 2012 too.

Step3: Once you have VHD Booted your machine to Server 2012. Open our favorite PowerShell console and run the following to install Hyper-V role on the host

 Get-WindowsFeature -name *hyper* | Install-WindowsFeature

Reboot your machine to complete Hyper-V installation

Step 4: After reboot, create a new VM in Hyper-V

But before we do this we need to create a virtual switch using PowerShell v3, I am going to create a new internal network switch

New-VMSwitch -Name "internal network" -SwitchType Internal

Once the switch is created use this when creating the New VM :

New-VM -Name "ServerCore" -VHDPath D:\VHD\ServerCore.vhd -MemoryStartupBytes 1024MB -BootDevice IDE -SwitchName "Internal Network"

Step 5: Now the VM is created ...I need to add the Server Core iso to the VM and Boot it

Add-VMDvdDrive -VMName ServerCore –Path D:\ISOs\ServerCore.iso 

Start-VM -Name "ServerCore"

Now Boot the VM by going to Hyper-V manager and Connect to the VM and complete the installation.

 Following is a  ScreenShot of my Lab, Note that the Server Core is running in the VM ..Cool !


P.S. - Now there is another method which can be used.....Follow the VHD boot article(shared in step 2)  and apply the appropriate WIM Image from the ISO to the VHD of the New VM and you are good to go too :)
 --------------------------

That's all for now, will keep posting what I try on this setup.

Thanks



Thursday, October 18, 2012

Resuming Blogging...

I was busy learning PowerShell and attending PowerShell events in India.
Now, I am a member of New Delhi PowerShell User Group and Bangalore PowerShell User Group.
I blogged occasionally for New Delhi PowerShell UG on Citrix and PowerShell.

Just to get a hint of my inactivity on this blog.......


I think I am back for good now.....

Monday, April 30, 2012

2012 Scripting Games : Beginner Event #2

The second problem for the SG 2012 can be found here

In this Event there was a little confusion as to what I had to do.....But going through comments on this problem and Scripting Wife's hint the picture became clear that I had to only find the Stoppable running services (complicated eh !).

Scripting Guy's design point can be a bit confusing at times but the key to solve is to think how to encompass all the design points.


The Script I wrote worked fine..what I did was queried the services running on the system ,then filtered one running with the status "Running", then finally filtered those with canstop property set to $true........but when read the comments on my script I learned a few things

Things learned:

1.  How to write compound Where clause.Read this article here . After reading this learned how to handle Boolean values and write compound where clause.

2. Read previous Scripting Games problem and solutions :)



param (
        $commputername = $env:computername
)

Get-Service -ComputerName $computername |
    where {$_.status -eq "running"} |
    where {$_.canstop -eq $true } 

Tuesday, April 17, 2012

2012 Scripting Games : Beginner Event #1



I had heard a lot about Scripting Games and decided this year to participate in them.
I was excited to see myself Script among other Beginners. This year they had done some changes such as One cannot participate in both Advanced and Beginner Section. One has to submit the script in 7 days after the Event goes online.

The first problem can be read here: Beginner Event 1

Summary: Beginner Event 1 of the 2012 Scripting Games uses Windows PowerShell to identify a working set of processes.

This was a bit easy for me as I had already read few blogs and books on PowerShell.
Below is my script and I got 4.5 star rating for it.
Though the event asked for one-liner , I wrote it this way. The key to get 5 Star rating is to keep focus on the design points and take your time to submit the script , copy paste what you have tested at least thrice .
The Scripting Wife hints at Scripting Guy blog will give you a bit of idea as how to approach the problem.
Some of the things I learned from participating in Scripting Games :) 

Things Learned :

1. For each Event read the comments too on the page, People ask the Scripting Guy a lot of questions that'll help you clarify a lot of things.

2.  Do a little bit of research before giving the final solution

3. Submit only what is asked for. Read the comments from judges


#takes care of the default condition
param (
        $computername = $env:computername
)
#gets the top 10 processes running on a Computer
Get-Process -ComputerName $computername |
 sort -Property workingset -Descending |
 select -First 10

Sunday, February 05, 2012

Powershell + Facebook

This post i stumbled @Twitter by M$ MVP Don Jones. And this is really awesome stuff......Managing Facebook from Powershell ( a command line ) although i have heard of using Facebook from command line in Linux (using fbcmd) .


Here it is the page for the PS module
http://facebookpsmodule.codeplex.com

The Author of this Module has done a really great job and given so many functionality at an alpha stage...Hoping for more.

Steps :

1. Install the Module by clicking on it.

2. Then Open a Powershell ISE or Powershell in STA mode..as the STA mode is needed.

3.  Then Import-Module facebook inside the console ( see below pic)


4. Then issue the command "New-FBConnection" and it pops-up the Connection Box

5. I face some error trying directly to set status after this...so did this issue
"Show-FBConnectionDialog" and in pop-up grant access.

6. Now to take a loot at what you can do just key-in "get-command -module facebook". Heck a lot of things you can do.

To just show you a feel of it here's a screenshot....really cool from Enterprise point of view to allow Facebook in their Environment. ;)




Sunday, January 22, 2012

GUI Editors for Powershell

What !!!!......I thought Powershell was a CLI Environment.

Well the problem with the huge user base of Windows is that all the users (even those calling themselves as Admins) are a slave of Graphical Interfaces.

Pop up a Powershell to a Windows Admin (experienced ones) and he has no idea what to do.....
So the big guys at M$ came up with the Powershell ISE to ease the learning curve for those users and there are many GUIs now available for PoSh (who saw that coming :P ).


Powershell Integrated Scripting Environment

Go to Start and type "powershell ise" click on the top result and you are presented with a following screen.

Now this GUI has a Ouput, Command, and Script pane. Read the help for more info.


PowerGUI 

Another great GUI tool for Powershell is PowerGUI from Quest Software. This GUI beats the Powershell ISE any day. I personally use this as it is the best free and has a huge community support.

Go to http://www.powergui.org to get yourself  one.
The PowerGUI comes with a Administrative Console and a Script Editor. The Administrative console is very cool and can be customized by using the powerpacks . The script editor is pretty cool as it drops a list of cmdlets as you type in and also the variable defined up to that point. Really cool.

See the snapshot below.

PrimalScript

This is yet another great tool for not only Powershell scripting but it has huge functionality and is really for professionals. PrimalScript is from Sapien Technologies and you have to buy it. Well there is a free trail period of about 46 days. You can try if you script in many environments as VBScript, C# etc.
I am not a pro at this so haven't really given it a try but from what i hear.....this is a tool worth to buy.




But what i feel really is the Users/Admins should give the command line a try before going into GUI stuff. I get it we all want ease but this PowerShell with Shell appended to Power and once you are comfortable with CLI...GUI is a piece of cake, right ?  :)

The offline key to learning Powershell

 get-help


I have been reading a lot about Powershell and Powershell Community has helped me a lot in various problems that I faced. There are lots of books and blogs available. But what if i have just powershell installed and no Internet connectivity...........then the only thing that comes to rescue is the

"get-help" cmdlet ( commands referred as cmdlets in PoSh )

Now, it is pretty basic and has helped a beginner like me a lot. So how do i know how to use get-help ?
Well the answer is simple, key in this
get-help get-help


Now try this

get-help about*

This lists all the about examples shipped with Powershell. These examples are very informative.

Now, if you read the get-help's help then you know what to do...when you want to know about a new cmdlet...but wait how you discover all cmdlets in Powershell


Key in this to  know how to discover new cmdlets.

get-help get-command


Few useful links:

www.powershellpro.com  --- has got great tutorials for beginners
www.bsonposh.com  --- this one i read for citrix + powershell stuff MVP & CTP Brandon's blog
http://www.windowsitpro.com/blogcontent/powershell-with-a-purpose-blog-36  --- MVP Don Jones' blog
http://blogs.technet.com/b/heyscriptingguy/ --- hey! scripting guy's blog


Powershellcommunity.org
powergui.org -- try this free GUI for PoSh
sapien.com

Monday, January 09, 2012

Real PowerShell lies in Objects

The very first thing about Powershell which takes geeks by awe is that every cmdlet (same as command) in PS returns Object based ouput rather than text-based.

Though this is the major reason for the success of Powershell but i think that Microsoft has done a great job integrating all the best things available as of now , just to name a few piplining, interpolation from Unix and programmatic constructs of Perl, Python and many more.

Powershell gives geek a way to finally be free of the GUI but the question is do we really want to be free of the Graphical UI ?

Another thing that is worth appreciating is that finally Microsoft is able to give users (say admins) the well documented help....Ohh! that was a long wait. Key in "get-help get-help -detailed" for how to use get-help.

The commands referred to as cmdlets in Powershell are of a standard naming convention "verb-noun" now this is simple but is pretty awesome feature.....suppose i wanted to get the list of all the services running then verb is get and noun is service, so the cmdlet is get-service.

More to come ...


Disclaimer -- these are a Powershell enthusiasts views. Don't feel offended.

Wednesday, January 04, 2012

This is the #1 post for "Powershell for Freedom" blog.
There's a reason for this name to blog.

Hoping PS sets me free.