≡ Menu

how to ping computers using powershell

I have written a small function for myself which I am using in all my scripts to check the availability of computer before acting on it. Here it is…

function ping-host {
param($computer)
$status = Get-WmiObject -Class Win32_PingStatus -Filter “Address=’$computer'”
if( $status.statuscode -eq 0) {
    return 1
}
else {
    return 0
 }
}

So, basically what this does is, returns 1 when the given computer is reachable or “0” if it is not. Below is a small example to demonstrate the functionality.

if (ping-host mycomp) {

write-host “reachable”

}

else {

write-host “unreachable”

}

Let me know if you know any other simple way…

{ 2 comments }

I recently read a article in Microsoft DS blog about the change in the way GPOs processes startup/logon scripts in Windows 7 and Windows 2008. The thing here is that, till XP/2003 days, computer startup/user logon scrips used to get executed in synchronous manner. That means, if you have more than a script configured in computer startup/user logon via GPOs, those scripts will get executed one after another. This behavior is changed in Windows 7/2008. In these latest operating systems, computer startup/logon scrips are asynchronous…means, execution of scripts starts at the same time. The big advantage I am seeing with this approach is, faster start/logon times in Windows 7/2008. Considering the hardware that we use to run Windows 7/2008, running scripts simultaniously will not tamper any of the computer resources and it’s a good move by Microsoft to increase the logon/startup speeds.

However, for some customers, running scripts synchronously might be a requirement. Output of one script might become inout to next script. In such a cases, you can always make Windows 7/2008 to process startup/logon scripts synchrounouly by altering registry key values.

Logoff/shutdown scripts are always Asynchronous and there is no tweak available for it to make synchronous.

Registry keys to create are…

Computer Preference
Key: HKEY_LOCAL_MACHINESoftwareMicrosoftWindows NTCurrentVersionWinlogon
ValueName: RunStartupScriptSync

Computer Policy Key: HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystem
ValueName: RunStartupScriptSync

User Preference
Key: HKEY_CURRENT_USERSoftwareMicrosoftWindows NTCurrentVersionWinlogon
ValueName: RunLogonScriptSync

User Policy Key: HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionPoliciesSystem
ValueName: RunLogonScriptSync

[ Source:ASKDS Blog]

{ 2 comments }

Removing items from arrays in PowerShell

Arrays are powerful in PowerShell and makes many system administration tasks easy. The built-in array controls works great for most of the scenarios, but it lags in capability of easy removal of items from it. Well, don’t worry. Still you can do that easily in powershell by leveraging dotnet component system.collections.ArrayList.

To make array operations more flexible, you need to define your array with this particular dotnet component.

To initialize array..

$myarray = New-Object System.Collections.ArrayList

To add a item to it..

$myarray.add(“item1”)

To add another item..

$myarray.add(“item2”)

and so on…Now to remove a item from it…

$myarray.remove(“item1”)

If you don’t know the value and has just index number, still you can remove..

$myarray.removerange(1,1)

Here, 1 is the index number, that means, you are removing item from $myarray[1]

Reference :

  1. http://technet.microsoft.com/en-us/library/ee692802.aspx (using dotnet module)
  2. http://technet.microsoft.com/en-us/library/ee692798.aspx (using built-in powershell arrays)

Do you know any way to remove items from array without using a second one? 🙂

{ 0 comments }

Disabling IE ESC(Internet Explorer Enhanced Security Configuration) is one of the fist thing I do whenever I built a Windows 2003 machine. It will be little bit frustrating when you work on any web apps from a windows 2003 computer. Always you need to click on either close or add to safe list to browse through a site. I am not much bothered about it because mostly I use IE from server for accessing intranet applications which are safe in all ways for me.

Now in this Windows 2008 era, I am facing the same old problem again, and it took some time to figure out where the option for disabling IE ESC.  Procedure is very simple compared to Windows 2003 provided you figure out where is the option to do it 🙂

Follow the below steps for disabling IE ESC:

  • Logon to the windows 2008 with admin account.
  • Open server Manger from administrator tools via start, programs
  • In server manger MMC, select the root(sever manager(yourmachine)) in left navigation pane and look at the Security Information section.
  • You will see a option to configure IE ESC in security section.
  • Click on it and it will give options to disable/enable for administrators/users.
  • Make your choice and click OK

You are done with your task.

{ 0 comments }

Getting local time using powershell is very easy. You can get it with “Get-Date” cmdlet. But how do you get time of remote machine using PowerShell? You have to rely on WMI objects to get this information.

$rtime = Get-WmiObject -Class Win32_OperatingSystem -ComputerName <yourCompName>

write-host $rtime.ConvertToDateTime($rtime.LocalDateTime)

Let me know if you figureout any other easy way.

{ 7 comments }

A Software to easily swich between two physical computer consoles

As part of one of my project, I have to work on two physical systems. So, I don’t have any option than connecting both of them at my desk maintain two keyboards and mouses. When ever I want to switch between computers, I have to swing my chair to reach other keyboard and mouse. This is really painful and I have to switch like this for more than 100 times a day. Initially I thought of of using a KVM. But I am afraid after looking at it’s cost. That too, I have multi monitors connected for one of my system, that means I have three monitors now. If I use a KVM, I can not make use of multi monitor.

That time, I dreamed about a application which easily takes your mouse control from monitor of one machine to monitor of other machine, when it reaches end of first one. My friends said, it is out of scope. I too felt that and days are rolling….and I have no option than to swing my chair every time.

But today I have seen something great which really helped me. I was reading Technet Magazine and in IT tool box section, they talked about Input Redirector. After reading it’s overview, I felt very happy and immediately tried on my machine.  It worked like a champ and I am able to change my KB and mouse control to second machine with just a mouse move. Amazing right?. I read completely about this tool and they have some more exciting features like, clipboard transfer between computers, Simultaneously locking all computers, and has hotkey option for faster switching between computers …many more…

Visit Product Site, if you want to give a try.

Let me know if you know any other tools which perform like this.

{ 0 comments }

While executing commands like Get-Mailbox, you often receive errors like identify is not found in default search scope. This you will see in a multi domain environment in general. In such cases, either you need to make the environment to look in whole forest for objects or ask powershell/cmdlet to ignore the scope. 

Here are the two ways I am talking about…

Set the search scope to forest level :- to do this, execute the below command

$AdminSessionADSettings.ViewEntireForest = $true

Make cmdlet to ignore the scope:- to do this, pass -ignoredefaultscope argument to cmdlet

Get-Mailbox -IgnoreDefaultScope -Identity “cn=username,ou=ouname,dc=domainname,dc=com”

Note that, incase of ignore default scope, you should parse only DN to -identity parameter.

Let me know if you figureout some other way.

{ 2 comments }

Customizing PowerShell Command prompt window

Powershell allows you to customize it’s command prompt window. You can,  set color of your choice from below list for foreground and back ground, set Windows Title,  Set buffer size,  Cursor size, etc.

Colors List : Black, Blue, DarkBlue, Cyan, DarkCyan, Gray, DarkGray, Green, DarkGreen, Magenta, DarkMagenta, Red, DarkRed, White, Yellow and DarkYellow.

Below examples will give a brief of how to customize some of the parameters.

Set background color 

$host.UI.rawui.foregroundcolor = “yellow” 

Set foreground color 

$host.UI.rawui.foregroundcolor = “<your_color” 

Set Window Title 

$host.UI.rawui.windowtitle = “My PowerShell Window”

Set Error Background Color

$host.Privatedata.ErrorBackGroundColor = “<your_color>”

Set Warning background color

$host.Privatedata.WarningBackgroundColor = “<your_color>”

Similarly, you can set DebugBackgroundColor, DebugForegroundColor, ErrorBackgroundColor, ErrorForegroundColor, ProgressBackgroundColor, ProgressForegroundColor, VerboseBackgroundColor, VerboseForegroundColor, WarningBackgroundColor, WarningForegroundColor

See the output of below command to know more about it.

$host.Provatedata | gm

Do you have any other customizations in mind? Do let me know by commenting here…

{ 0 comments }

I can not right away tell you the use cases of this procedure, but felt interesting. You can know the password entered through Get-Credential cmdlet.

$mycredentials = Get-Credential
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($mycredential.Password))

I got this from http://www.roelvanlisdonk.nl/?p=1150

Happy Learning..,
Sitaram Pamarthi

{ 0 comments }

Handling WMI errors in PowerShell

Today I worked on writing a script and in that I got a requirement to suppress errors. At the same time, I want to log the error description for my referrence. To achieve this, I made use of two parameters of Get-WmiObject cmdlet. They are, -ErrorVariable and -ErrorAction

In brief, the argument passed to -ErrorVariable stores the details of the error generated and -ErrorAction specifies what to do incase of errors, like whether to continue execution or stop or whatever action. Google search will make you to land in few beautiful sites which has more info about these two parameters. Alternately, you can run “Get-Help about_commonparameters”

OK, now lets see how we can suppress and capture the errors from WMI execution. Below command runs against a computer which doesn’t exists. I don’t want my script to fail there and it should continue by logging the error somewhere.

Get-WmiObject -Class Win32_Product -ComputerName nonexists -ErrorVariable myerror -ErrorAction SilentlyContinue

Above command will fail in real, but it will not show any error in screen. Error will be saved in $myerror object. To see the error, issue below command

$myerror[0].exception

To clear the error from object, use below

$myerror.clear()

To see how many errors are stored in this object, use below

$myerror.count
[/code]
You can use this in your scripts to avoid powershel printing errors in console and log to some file. Hope this helps.

{ 3 comments }