Archive

Archive for the ‘PowerShell’ Category

How to Get SCOM Root Management server name using Powershell

December 20, 2011 Leave a comment

In this post you will learn how to query SCOM RMS server name of a specific SCOM group using powershell script.

In all my SCOM scripts that I wrote so far, I hardcoded the SCOM RMS server name. Recently I came across a situation where RMS role is moved to another management server in same SCOM group. With this change, obviously all my scripts will fail because the hard coded server is not a RMS server anymore and it has no intelligence to redirect my query to the current RMS sever.

That means we should have a dynamic way using which we can get RMS server automatically from some reliable source. SCOM installations creates a SCP(Service Connection Point) in Active directory for each SCOM group. So now I will show you how to query this SCP using powershell and get the RMS server name.

We can either choose to use build-in Activedirectory module or Quest AD Cmdlets to get information. The below code is based on activedirectory module which is available with Windows 2008 and Windows 7.

function Get-ScomRMSServer {            

Import-Module ActiveDirectory
$Domainname = (Get-ADDomain).DistinguishedName.tostring()
$SCOMObj = Get-ADObject -Filter "Name -eq 'SDKServiceSCP'" -SearchBase $domainname `
-Properties ServiceDNSName, ServiceClassName
$SCOMObj | select serviceclassname, serviceDNSName            

}

Thanks to my colleague(Deepesh) who helped with finding this.

 

How to create temp files using powershell script.

December 16, 2011 Leave a comment

I just came across a interesting tip that might help in your powershell scripting. It is about creating the temp file. In your script, if you want to create some temp file for processing and then it is right choice. The advantage with this approach is, it directly creates a file in %temp% of user profile and returns the path. Another good thing is, if you run it multiple times, it returns a new temp file each time.

[System.IO.Path]::GetTempFileName()

 

Hope this tiny one helps…

PowerShell: How to get BIOS details of remote computer

December 16, 2011 Leave a comment

In today’s post, let us see how to get the BIOS details of remote computer. When I say BIOS details, the most important parameters one will look for is, version and serial number. These are the most two parameters System administrators often want to know. To get this information, I have written a little function which makes a WMI query to remote computer using Get-WMIObject cmdlet for Win32_BIOS class to get the required details.

Here you go for the script. Hope this helps…

function Get-BIOSDetails {
param($Computer)            

$output = "" | select ComputerName, BIOSVersion, SerialNumber
$obj = Get-WMIObject -Class Win32_BIOS -ComputerName $Computer
$output.ComputerName = $Computer.ToUpper()
$output.BIOSVersion = $obj.SMBIOSBIOSVersion
$output.SerialNumber = $obj.SerialNumber            

$output            

}

I will continue writing more and more when I find some time.

PowerShell: How to change text to Title Case(first letter to upper case and remaining lower case)

December 6, 2011 1 comment

We all know how to change a string to lower case or upper case. It is as good as invoking .Toupper() or .Tolower() methods of the string variable.

For example…

PS C:\> “TechiBee”.toupper()
TECHIBEE
PS C:\> “TechiBee”.tolower()
techibee
PS C:\>

But when it comes to changing to Title case where first letter of the word is in capital and remaining letter in world in lower case, people are using variety methods. Some people are using substring method to identify the first character to upper and remaining to lower case and then combining them to get the title case of original word/string.

Actually, It is not that hard. PowerShell has very powerfull features and you should be doing it with very easy procedures. Let us see how to do it.

PS C:\> (Get-Culture).textinfo.totitlecase(“TechiBee.com”.tolower())
Techibee.Com
PS C:\>

In the above example, I am using the ToTitleCase method that is available with Get-Culture cmdlet. All we need to do is pass the string as argument to this function to get it converted to title case. I passed “TechiBee.com” for demonstration and you can see the output. You might have noticed that “com” in “TechiBee.com” also got changed it to title case as this is also a different word in the given string. You might want to ask why we need to change it to lower case before performing the conversion. I too don’t have a answer for it but the thing is, if the given string/word has all capital letters, then this method is not changing the string to title case. Hence I used ToLower() method. You can see the below demonstration for clarity.

Hope this helps…

PowerShell: How to get logon account of services on remote computer

Well, I explored Win32_Service WMI class a bit more and found some more concepts which are useful to Windows Administrators. In this article, I will show you how to get the list of services which are running with a specific windows account. You can get this information from both local and remote computers with the code that I am going to provide.

CODE:

function Get-ServiceLogonAccount {
[cmdletbinding()]            

param (
$ComputerName = $env:computername,
$LogonAccount
)            

    if($logonAccount) {
        Get-WmiObject -Class Win32_Service -ComputerName $ComputerName |` 
? { $_.StartName -match $LogonAccount } | select DisplayName, StartName, State            

    } else {            

        Get-WmiObject -Class Win32_Service -ComputerName $ComputerName | `         
select DisplayName, StartName, State
    }            

}

So it is clear what the above function does. It takes two parameters, computername and logonaccount. You should provide computer name if you would like to query the services on remote computer otherwise just ignore it. By default it queries local computer. Similarly, -LogonAccount is also optional parameters and you need to pass the account name that you are looking for. For example, if you are looking for DOMAIN\Useracct1 account, just pass useracc1 as parameter value.

Below are some usage examples…

Example 1: Query logon account of all services in local computer

Example 2: Get services running with “NT Authority\LocalService” account on remote computer

Hope this helps.

 

PowerShell: Test port connectivity

November 30, 2011 Leave a comment

We being system administrators come across requirements to see if a port is open for connections or not. For example, to see if a web service is working, the first thing I do is, “telnet webservername 80″. Similarly every client/server application some or other port for establishing connection and communication. Since the port connectivity verification is pretty much part of system administrator’s life, I want to do it with my favorite programming language, “PowerShell”.

Below is the function that tests the port connection and returns the status.

Code:

function Test-PortConnection {
[cmdletbinding()]
param(                        

[parameter(mandatory=$true)]
[string]$TargetHost,                        

[parameter(mandatory=$true)]
[int32]$TargetPort,                        

[int32] $Timeout = 10000                        

)                        

$outputobj = New-Object -TypeName PSobject            

$outputobj | Add-Member -MemberType NoteProperty -Name TargetHostName -Value $TargetHost            

if(test-Connection -ComputerName $TargetHost -count 2) {
    $outputobj | Add-Member -MemberType NoteProperty -Name TargetHostStatus -Value "ONLINE"
} else {
    $outputobj | Add-Member -MemberType NoteProperty -Name TargetHostStatus -Value "OFFLINE"
}            

$outputobj | Add-Member -MemberType NoteProperty -Name PortNumber -Value $targetport            

$Socket = New-Object System.Net.Sockets.TCPClient
$Connection = $Socket.BeginConnect($Targethost,$TargetPort,$null,$null)
$Connection.AsyncWaitHandle.WaitOne($timeout,$false)  | Out-Null            

if($Socket.Connected -eq $true) {
    $outputobj | Add-Member -MemberType NoteProperty -Name ConnectionStatus -Value "Success"
} else {
    $outputobj | Add-Member -MemberType NoteProperty -Name ConnectionStatus -Value "Failed"
}            

$Socket.Close | Out-Null
$outputobj | select TargetHostName, TargetHostStatus, PortNumber, Connectionstatus | ft -AutoSize            

}

In this code, I am using “System.Net.Socket.TCPClient” dotnet object to verify the connection. One the script tries to establish the connection it waits for at least 10 seconds to see if the other party is responding or not on the port I am querying. It is because, based on the server responsiveness and other factors, you may get some delayed response. To facilitate such incidents, I am using 10 seconds default delay. However, if you wish you can change it to the value you want by simply passing the value through -TimeOut parameter. The script takes other two mandatory parameters. One is -TargetHost  and another is -TargetPort. The “TargetHost” parameter accepts the remote server name on which you want to test the port connectivity and Targetport is the actual port number you want to query.

Usage example:

Hope this information helps…

 

PowerShell: Is Windows Powers Hell?

November 24, 2011 Leave a comment

“Did you mean windows powers hell ?” is message you get when you search for “Windows PowerShell” in download.microsoft.com. Isn’t this funny? One of my friends noticed this. I feel MS should look at their search algorithm and make PowerShell as known word and don’t recommend “Powers hell”.

If any MVPs or Microsoft Persons happens to look at this post, please inform respective team in Microsoft to get this corrected. After all it is the first thing any one would do if they want to learn powershell.

Here is the screenshot of it.

Categories: PowerShell, Scripting Tags:

PowerShell: Expand virtual machine hard disk size in Vmware ESX

November 22, 2011 Leave a comment

Expanding the Virtual machine hard disk is most common administration task for VMware(or Hyper-V) administrator. The general process is connecting to virtual center console, locate the VM, go to properties, identify the hard disk for which you want to increase the space and enter new hard disk size in the “Provisioned Size” box and click OK. This complete the task. For example, you have 10 such VMs on which you have to increase the space, then repeating the above steps for all VMs is a cumbersome task. So, let us see how we can easily do it with powershell.

Today I got a requirement to expand a VM hard disk. Since I am exploring VMware PowerCLI these days, I thought of using PowerShell for this operation to see how quickly I can do this. Once I figureout the cmdlet to use, I felt it is too easy.

Here is the one liner I used to expand hard disk 1 in a VM.

Get-VM VMServer1 | Get-HardDisk | ? {$_.name -eq "Hard disk 1" } | Set-HardDisk -CapacityKB 52428800

You need to execute this from VMware PowerShell CLI where Get-VM, Get-Harddisk cmdlets are available. Also before executing the above, you need to ensure that you already established a connect to Virtual Center Server from your powershell window. You can do it by simply running “Connect-VIServer -Server VCSERVER1″ where VCSERVER1 is the name of the virtual center server.

In this one liner, I am using Get-VM to get a virtual machine reference for which I want to increase the space and using Get-Harddisk cmdlet to read the disks information of the returned VM. From there I am filtering out the disks for which I want to expand the space. Since I am just interested in expanding “Hard disk 1″, I created a where-object to filter the disks with the given name. And finally expanding the disk by using set-HardDisk cmdlet which takes the target size in KBs.

From my readings, I understood that, Set-Harddisk also expands the disk in guest OS provided you are passing the credentials to it. I did that for a VM which is running windows 2003 but it didn’t work. May be this is applicable only to Windows 7/2008 computers which are having in-built GUI option to extend the hard disks from disk management. No need to use disk part tool in that case. If it is a windows 2003/XP guest OS, then you should use diskpart tool to expand it.

Hope this information helps…

 

PowerShell: How to use SCOM cmdlets from normal powershell window

November 22, 2011 Leave a comment

SCOM 2007 offers a customized poweshell console from where you can run all cmdlets related to SCOM. This powershell consoles comes along with SCOM management console installation. The only problem with this is it’s flakiness. I somehow don’t like this console and never felt like working on a powershell console. If you type “Get-” and press TAB, it should show all the cmdlets which starts with GET- but this console hangs and never gives me control back. There I realized the need for running these commands from normal powershell consoles so that everything works as expected and scripts also can make use of this environment. By default, if you launch a normal poweshell window from SCOM server where SCOM powershell console installed, you won’t get SCOM cmdlets by default. You need to load them explicitly.

So, in this post I will give you the list of steps required to load SCOM module into normal powershell window.

  1. Go to Start->RUN-> type “powershell.exe”
  2. In powershell window, type Add-PSSnapin Microsoft.EnterpriseManagement.OperationsManager.Client
  3. Now connect to SCOM server by typing New-ManagementGroupConnection -ConnectionString:MYSCOMSRV1 where MYSCOMSRV1 is your SCOM RMS server.
  4. Now let us set the path for SCOM by typing Set-Location ‘OperationsManagerMonitoring::’

 

This completes the import process of SCOM module into normal powershell windows and now you can use alll SCOM cmdlets from this console. Similarly if you have any scripts which uses powershell module, just  prefix your code with above steps so that SCOM module will get imported before the code in your scripts starts using any SCOM cmdlet.

I guess no need to say that you can import the SCOM module into normal powershell console only computer where SCOM management tools are installed.

Hope this halpe.. Happy learning..

 

 

 

PowerShell: Get Windows Cluster instances status

November 22, 2011 Leave a comment

Using powershell, we can query the status of a given windows cluster and instances inside it. With Windows 2008, MS is offering this ability. You need to import the failoverclusters  module to use the cmdlets available to manage windows cluster.

Import cluster module:

Import-module failoverclusters

Using this module you can do variety of things in cluster like adding and deleting disk, adding and deleting network interfaces, adding and deleting any other cluster resources, what not, you can do majority of operations with this powershell module.

Now I will give you a little example about how to connect to a cluster and get instances hosted on it.

Get-Cluster -Name cluster1.domain.com | Get-ClusterGroup

The above will connect to cluster1.domain.com and returns the status of groups/instances hosted on this cluster. You can also see preferred nodes, fail-over, fail-back settings for a given group, etc. I will try to post about them when I get a changes.

For your quick reference, I am posting the cluster cmdlets (source: technet)

Add-ClusterDisk Make a new disk available for use in a failover cluster. The disk (LUN) must be exposed to all nodes in the failover cluster, and should not be exposed to any other servers.
Add-ClusterFileServerRole Create a clustered file server (resource group that includes one or more disks, on which you can create shared folders for users).
Add-ClusterGenericApplicationRole Configure high availability for an application that was not originally designed to run in a failover cluster.
Add-ClusterGenericScriptRole Configure an application controlled by a script that runs in Windows Script Host, within a failover cluster.
Add-ClusterGenericServiceRole Configure high availability for a service that was not originally designed to run in a failover cluster.
Add-ClusterGroup Add an empty resource group to the failover cluster configuration, in preparation for adding clustered resources to the group.
Add-ClusterNode Add a node (server) to a failover cluster. Before adding the new node, you should run validation tests on the existing nodes together with the proposed new node.
Add-ClusterPrintServerRole Create a clustered print server (a resource group that includes a printer and a disk for storing print job information and printer drivers).
Add-ClusterResource Add a resource to a clustered service or application (resource group) in a failover cluster.
Add-ClusterResourceDependency Add a resource to the list of resources that a particular resource depends on (using AND as the connector) within a failover cluster. Existing dependencies will remain in the list.
Add-ClusterResourceType Add a resource type to a failover cluster, and specify information such as the dynamic-link library (DLL) to use with that resource type.
Add-ClusterServerRole Add a group containing only a client access point and storage to the failover cluster configuration.
Add-ClusterSharedVolume Make a volume available in Cluster Shared Volumes in a failover cluster.
Add-ClusterVirtualMachineRole Create a clustered virtual machine, that is, a virtual machine that can be failed over if necessary to a different server in the failover cluster.
Block-ClusterAccess Prevent the specified user or users from accessing a failover cluster.
Clear-ClusterDiskReservation Clear the persistent reservation on a disk in a failover cluster.
Clear-ClusterNode Clear the cluster configuration from a node that was evicted from a failover cluster.
Get-Cluster Get information about one or more failover clusters in a given domain.
Get-ClusterAccess Get information about permissions that control access to a failover cluster.
Get-ClusterAvailableDisk Get information about the disks that can support failover clustering and are visible to all nodes, but are not yet part of the set of clustered disks.
Get-ClusterGroup Get information about one or more clustered services or applications (resource groups) in a failover cluster.
Get-ClusterLog Create a log file for all nodes (or a specific node) in a failover cluster.
Get-ClusterNetwork Get information about one or more networks in a failover cluster.
Get-ClusterNetworkInterface Get information about one or more network adapters in a failover cluster.
Get-ClusterNode Get information about one or more nodes (servers) in a failover cluster.
Get-ClusterOwnerNode For a resource in a failover cluster, get information about which nodes can own the resource. For a clustered service or application (a resource group), get information about the order of preference among owner nodes.
Get-ClusterParameter Get detailed information about an object in a failover cluster, such as a cluster resource. This cmdlet is used to manage private properties for a cluster object.
Get-ClusterQuorum Get information about the quorum configuration of a failover cluster.
Get-ClusterResource Get information about one or more resources in a failover cluster.
Get-ClusterResourceDependency Get information about the dependencies that have been configured between clustered resources in a failover cluster.
Get-ClusterResourceDependencyReport Generate a report that lists the dependencies between resources in a failover cluster.
Get-ClusterResourceType Get information about one or more resource types in a failover cluster.
Get-ClusterSharedVolume Get information about Cluster Shared Volumes in a failover cluster.
Grant-ClusterAccess Grant access to a failover cluster, either full access or read-only access.
Move-ClusterGroup Move a clustered service or application (a resource group) from one node to another in a failover cluster.
Move-ClusterResource Move a clustered resource from one clustered service or application to another within a failover cluster.
Move-ClusterSharedVolume Move a Cluster Shared Volume to ownership by a different node in a failover cluster.
Move-ClusterVirtualMachineRole Move the ownership of a clustered virtual machine to a different node.
New-Cluster Create a new failover cluster. Before you can create a cluster, you must connect the hardware (servers, networks, and storage), and run the validation tests.
Remove-Cluster Destroy an existing failover cluster. The affected servers will no longer function together as a cluster.
Remove-ClusterAccess Remove a user from the access list on the cluster.
Remove-ClusterGroup Remove a clustered service or application (also called a resource group) from a failover cluster.
Remove-ClusterNode Remove a node from a failover cluster. After the node is removed, it no longer functions as part of the cluster unless you add it back to the cluster.
Remove-ClusterResource Remove a clustered resource from the failover cluster.
Remove-ClusterResourceDependency Remove a dependency between two resources in a clustered service or application within a failover cluster.
Remove-ClusterResourceType Remove a resource type from a failover cluster.
Remove-ClusterSharedVolume Remove a volume from the Cluster Shared Volumes in a failover cluster, and place it in Available Storage in the cluster.
Repair-ClusterSharedVolume Run repair tools on a Cluster Shared Volume locally on a cluster node.
Resume-ClusterNode Resume activity on a failover cluster node after you have suspended it (that is, paused it).
Resume-ClusterResource Turn off maintenance for a disk resource or Cluster Shared Volume within a failover cluster.
Set-ClusterLog Set the size and level of detail for the cluster log.
Set-ClusterOwnerNode For a resource in a failover cluster, specify which nodes can own the resource. For a clustered service or application (a resource group), specify information about the order of preference among owner nodes.
Set-ClusterParameter Control specific properties of an object in a failover cluster, such as a resource, a group, or a network.
Set-ClusterQuorum Configure quorum options for a failover cluster.
Set-ClusterResourceDependency Specify the resources that a particular resource depends on within a failover cluster. Existing dependencies will be overwritten by the dependencies that you specify.
Start-Cluster Start the Cluster service on all nodes of the cluster on which it is not yet started.
Start-ClusterGroup Bring one or more clustered services and applications (also known as resource groups) online on a failover cluster.
Start-ClusterNode Start the Cluster service on a node in a failover cluster.
Start-ClusterResource Bring a resource online in a failover cluster.
Stop-Cluster Stop the Cluster service on all nodes in a failover cluster, which will stop all services and applications configured in the cluster.
Stop-ClusterGroup Take one or more clustered services and applications (also known as resource groups) offline on a failover cluster.
Stop-ClusterNode Stop the Cluster service on a node in a failover cluster.
Stop-ClusterResource Take a resource offline in a failover cluster.
Suspend-ClusterNode Suspend activity on a failover cluster node, that is, pause the node.
Suspend-ClusterResource Turn on maintenance for a disk resource or Cluster Shared Volume so that you can run a disk maintenance tool without triggering failover.
Test-Cluster Run validation tests for failover cluster hardware and settings. Tests can be run both before and after a cluster is set up.
Test-ClusterResourceFailure Simulate a failure of a cluster resource.
Update-ClusterIPResource Renew or release the DHCP lease for an IP address resource in a failover cluster.
Update-ClusterVirtualMachineConfiguration Refresh the configuration of a clustered virtual machine within a failover cluster.