Learning PowerShell: Part 2

Standard

In my previous post I looked at some of the very basics of PowerShell but now its time to create some scripts.

I’m always building new virtual machines on my laptop and I’m fed up having to add IP Address and how I have click so many times to add this and type in a new computer name.

So thought PowerShell can solve this problem for me.

The first issue I had was that there are some security issues to stop you from just running scripts that change computer settings like this.  First run the command before to change the execution policy on your computer.  You then have to confirm that you want to do this.


image

Firstly I want the script to prompt me what computer name I want and then the different IP settings for the server.  I type in $NewName=Read-Host “Computer Name”.  If we break this down a little you’ll see the different settings you’ll need for your script.

The $NewName is your variable to store what you have typed.  Later in your script where you type $NewName it will be replaced with what you type when you were prompted.  Where you can see “Computer Name” is the text that will show up on screen as the descriptions of your prompt.

If we run this simple command below it will prompt me for the new computer name and then display it on the screen




image

Here on the 3rd line you can see it has displayed what we typed when prompted.

To actually change the computer name we need to run 2 lines of PowerShell in our script.

Have a look at the code below and you will notice on the second line it has $newname which is from the prompt earlier.




When adding this to what we already have we the script will change the computer name to what we were prompted.  The computer will then change name after a restart.

A new command line tool that I have started to use in recent weeks since I started looking at Window Server 2008 Core is netsh.exe.  Netsh allows you to control the behaviour of the networking on your windows device.  I change change the IP Address, change the name from Local Area Connection to what ever you want it to be.  I can also change the firewall settings as well.

We’re going to add a few more prompts for the IP Address, Subnet Mask, Default Gateway and DNS Server and these will be used during the netsh commands.

All together we have 3 netsh commands in this script, one will set the IP, Subnet and Default Gateway, one will set the DNS Server and other will turn the firewall off (in my development areas I turn my firewall off).

Below is the full script to change the computer and it will have ask for prompts and add the right information into the script.














































2 thoughts on “Learning PowerShell: Part 2

Leave a Reply

Your email address will not be published. Required fields are marked *