Archive

Archive for the ‘Scripting’ Category

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: How to assign the output to a variable and print on console at same time

November 22, 2011 Leave a comment

We want to assign output of a cmdlet/function to a variable so that we can use it in further processing. In scripts it is very inconvenient to debug a issue if the output is going to a variable and not to console. In such cases we can do nothing other than printing the variable value to the console by inserting extra lines of code.

To avoid such inconvenience, powershell has got a way to assign the output to a variable and print to console at the same time. This helped me in quick debugging of my scripts and oneliners.

Ok. Enough explaining about the usage and all and here is how it works.

($service = Get-Service -Name spooler)

Execute the command and you will understand what exactly it is doing. All we need to do it embed the whole command into into brackets like shown above.

Hope this little one helps you. Happy learning.

 

 

PowerShell: Convert your VB scripts to PowerShell

November 12, 2011 Leave a comment

The popularity of PowerShell is increasing day-to-day and now every System administrator want to say bye to their VB scripts and enter the powerful powershell world. A system administrator who is familiar with VB script(or has in home grown scripts in VB) want to try powershell, the first question he gets into mind is, “how to do xyz task in powershell”. Of course, we can ask our big brother google.com but it will take little long to find the powershell way of coding a task.

For those kind of admins, MS has published a long list of converting xyz from VB script to PowerShell. This pretty much enough for a person who wants to convert their VB scripts into powershell code. For your easy reference I am posting the content from MS technet site to here.

Hope this helps…

Cmdlets and Add-ons
Converting Dictionary Object to Windows PowerShell Commands
Converting VBScript Commands to Windows PowerShell Commands
Converting VBScript’s Abs Function
Converting VBScript’s Addition Operator
Converting VBScript’s And Operator
Converting VBScript’s Array Function
Converting VBScript’s Asc Function
Converting VBScript’s Assignment Operator
Converting VBScript’s Atn Function
Converting VBScript’s CBool Function
Converting VBScript’s CByte Function
Converting VBScript’s CCur Function
Converting VBScript’s CDate Function
Converting VBScript’s CDbl Function
Converting VBScript’s CInt Function
Converting VBScript’s CLng Function
Converting VBScript’s CSng Function
Converting VBScript’s CStr Function
Converting VBScript’s Call Statement
Converting VBScript’s Chr Function
Converting VBScript’s Class Statement
Converting VBScript’s Clear Method
Converting VBScript’s Concatenation Operator
Converting VBScript’s Const Statement
Converting VBScript’s Cos Function
Converting VBScript’s CreateObject Function
Converting VBScript’s Date Function
Converting VBScript’s DateAdd Function
Converting VBScript’s DateDiff Function
Converting VBScript’s DatePart Function
Converting VBScript’s DateSerial Function
Converting VBScript’s DateValue Function
Converting VBScript’s Day Function
Converting VBScript’s Dim Statement
Converting VBScript’s Division Operator
Converting VBScript’s Do…Loop Statement
Converting VBScript’s Eqv Operator
Converting VBScript’s Erase Statement
Converting VBScript’s Err Object Description Property
Converting VBScript’s Err Object HelpContext Property
Converting VBScript’s Err Object HelpFile Property
Converting VBScript’s Err Object Number Property
Converting VBScript’s Err Object Source Property
Converting VBScript’s Escape Function
Converting VBScript’s Eval Function
Converting VBScript’s Execute Statement
Converting VBScript’s ExecuteGlobal Statement
Converting VBScript’s Exit Statement
Converting VBScript’s Exp Function
Converting VBScript’s Exponentiation Operator
Converting VBScript’s Filter Function
Converting VBScript’s Fix Function
Converting VBScript’s For Each…Next Statement
Converting VBScript’s For…Next Statement
Converting VBScript’s FormatCurrency Function
Converting VBScript’s FormatDateTime Function
Converting VBScript’s FormatNumber Function
Converting VBScript’s FormatPercent Function
Converting VBScript’s Function Statement
Converting VBScript’s GetLocale Function
Converting VBScript’s GetObject Function
Converting VBScript’s GetRef Function
Converting VBScript’s Hex Function
Converting VBScript’s Hour Function
Converting VBScript’s If…Then…Else Statement
Converting VBScript’s Imp Operator
Converting VBScript’s InStr Function
Converting VBScript’s InStrRev Function
Converting VBScript’s InputBox Function
Converting VBScript’s Int Function
Converting VBScript’s Integer Division Operator
Converting VBScript’s Is Operator
Converting VBScript’s IsArray Function
Converting VBScript’s IsDate Function
Converting VBScript’s IsEmpty Function
Converting VBScript’s IsNull Function
Converting VBScript’s IsNumeric Function
Converting VBScript’s IsObject Function
Converting VBScript’s Join Function
Converting VBScript’s LBound Function
Converting VBScript’s LCase Function
Converting VBScript’s LTrim Function
Converting VBScript’s Left Function
Converting VBScript’s Len Function
Converting VBScript’s LoadPicture Function
Converting VBScript’s Log Function
Converting VBScript’s Mid Function
Converting VBScript’s Minute Function
Converting VBScript’s Mod Operator
Converting VBScript’s Month Function
Converting VBScript’s MonthName Function
Converting VBScript’s MsgBox Function
Converting VBScript’s Multiplication Operator
Converting VBScript’s Not Operator
Converting VBScript’s Now Function
Converting VBScript’s Oct Function
Converting VBScript’s On Error Statement
Converting VBScript’s Option Explicit Statement
Converting VBScript’s Or Operator
Converting VBScript’s Property Get Statement
Converting VBScript’s Property Let Statement
Converting VBScript’s Property Set Statement
Converting VBScript’s Public Statement
Converting VBScript’s RGB Function
Converting VBScript’s RTrim Function
Converting VBScript’s Raise Method
Converting VBScript’s Randomize Statement
Converting VBScript’s ReDim Statement
Converting VBScript’s Rem Statement
Converting VBScript’s Replace Function
Converting VBScript’s Right Function
Converting VBScript’s Rnd Function
Converting VBScript’s Round Function
Converting VBScript’s ScriptEngine Function
Converting VBScript’s ScriptEngineBuildVersion Function
Converting VBScript’s ScriptEngineMajorVersion Function
Converting VBScript’s ScriptEngineMinorVersion Function
Converting VBScript’s Second Function
Converting VBScript’s Select Case Statement
Converting VBScript’s Set Statement
Converting VBScript’s SetLocale Function
Converting VBScript’s Sgn Function
Converting VBScript’s Sin Function
Converting VBScript’s Space Function
Converting VBScript’s Split Function
Converting VBScript’s Sqr Function
Converting VBScript’s Stop Statement
Converting VBScript’s StrComp Function
Converting VBScript’s StrReverse Function
Converting VBScript’s String Function
Converting VBScript’s Sub Statement
Converting VBScript’s Subtraction Operator
Converting VBScript’s Tan Function
Converting VBScript’s Tan Function
Converting VBScript’s Time Function
Converting VBScript’s TimeSerial Function
Converting VBScript’s TimeValue Function
Converting VBScript’s Timer Function
Converting VBScript’s Trim Function
Converting VBScript’s TypeName Function
Converting VBScript’s UBound Function
Converting VBScript’s UCase Function
Converting VBScript’s Unescape Function
Converting VBScript’s Vartype Function
Converting VBScript’s Weekday Function
Converting VBScript’s WeekdayName Function
Converting VBScript’s While…Wend Statement
Converting VBScript’s With Statement
Converting VBScript’s Xor Operator
Converting VBScript’s Year Function
Converting Windows Script Host Methods to Windows PowerShell Commands
Converting the Dictionary Object’s Add Method
Converting the Dictionary Object’s CompareMode Property
Converting the Dictionary Object’s Exists Method
Converting the Dictionary Object’s Item Property
Converting the Dictionary Object’s Items Method
Converting the Dictionary Object’s Key Property
Converting the Dictionary Object’s Keys Method
Converting the Dictionary Object’s Remove Method
Converting the Dictionary Object’s RemoveAll Method
Converting the FileSystemObject to Windows PowerShell Commands
Converting the FileSystemObject’s Add Method
Converting the FileSystemObject’s AtEndOfLine Property
Converting the FileSystemObject’s AtEndOfStream Property
Converting the FileSystemObject’s AvailableSpace Property
Converting the FileSystemObject’s BuildPath Method
Converting the FileSystemObject’s Close Method
Converting the FileSystemObject’s Column Property
Converting the FileSystemObject’s Copy Method
Converting the FileSystemObject’s CopyFile Method
Converting the FileSystemObject’s CopyFolder Method
Converting the FileSystemObject’s CreateFolder Method
Converting the FileSystemObject’s CreateTextFile Method
Converting the FileSystemObject’s DateCreated Property
Converting the FileSystemObject’s DateLastAccessed Property
Converting the FileSystemObject’s DateLastModified Property
Converting the FileSystemObject’s Delete Method
Converting the FileSystemObject’s DeleteFile Method
Converting the FileSystemObject’s DeleteFolder Method
Converting the FileSystemObject’s Drive Property
Converting the FileSystemObject’s DriveExists Method
Converting the FileSystemObject’s DriveLetter Property
Converting the FileSystemObject’s DriveType Property
Converting the FileSystemObject’s Drives Property
Converting the FileSystemObject’s FileExists Method
Converting the FileSystemObject’s FileSystem Property
Converting the FileSystemObject’s Files Property
Converting the FileSystemObject’s FolderExists Method
Converting the FileSystemObject’s FreeSpace Property
Converting the FileSystemObject’s GetAbsolutePathName Method
Converting the FileSystemObject’s GetBaseName Method
Converting the FileSystemObject’s GetDrive Method
Converting the FileSystemObject’s GetDriveName Method
Converting the FileSystemObject’s GetExtensionName Method
Converting the FileSystemObject’s GetFile Method
Converting the FileSystemObject’s GetFileName Method
Converting the FileSystemObject’s GetFileVersion Method
Converting the FileSystemObject’s GetFolder Method
Converting the FileSystemObject’s GetParentFolderName Method
Converting the FileSystemObject’s GetSpecialFolder Method
Converting the FileSystemObject’s GetStandardStream Method
Converting the FileSystemObject’s GetTempName Method
Converting the FileSystemObject’s IsReady Property
Converting the FileSystemObject’s IsRootFolder Property
Converting the FileSystemObject’s Line Property
Converting the FileSystemObject’s Move Method
Converting the FileSystemObject’s MoveFile Method
Converting the FileSystemObject’s MoveFolder Method
Converting the FileSystemObject’s Name Property
Converting the FileSystemObject’s OpenAsTextStream Method
Converting the FileSystemObject’s OpenTextFile Method
Converting the FileSystemObject’s ParentFolder Property
Converting the FileSystemObject’s Path Property
Converting the FileSystemObject’s Read Method
Converting the FileSystemObject’s ReadAll Method
Converting the FileSystemObject’s ReadLine Method
Converting the FileSystemObject’s RootFolder Property
Converting the FileSystemObject’s SerialNumber Property
Converting the FileSystemObject’s ShareName Property
Converting the FileSystemObject’s ShortName Property
Converting the FileSystemObject’s ShortPath Property
Converting the FileSystemObject’s Size Property
Converting the FileSystemObject’s Skip Method
Converting the FileSystemObject’s SkipLine Method
Converting the FileSystemObject’s SubFolders Property
Converting the FileSystemObject’s TotalSize Property
Converting the FileSystemObject’s Type Property
Converting the FileSystemObject’s VolumeName Property
Converting the FileSystemObject’s Write Method
Converting the FileSystemObject’s WriteBlankLines Method
Converting the FileSystemObject’s WriteLine Method
Converting the Windows Script Host AddWindowsPrinterConnection Method
Converting the Windows Script Host AppActivate Method
Converting the Windows Script Host Close Method
Converting the Windows Script Host ConnectObject Method
Converting the Windows Script Host Count Method
Converting the Windows Script Host CreateObject Method
Converting the Windows Script Host DisconnectObject Method
Converting the Windows Script Host Echo Method
Converting the Windows Script Host EnumNetworkDrives Method
Converting the Windows Script Host EnumPrinterConnections Method
Converting the Windows Script Host Exec Method
Converting the Windows Script Host Execute Method
Converting the Windows Script Host Exists Method
Converting the Windows Script Host ExpandEnvironmentStrings Method
Converting the Windows Script Host GetObject Method
Converting the Windows Script Host GetResource Method
Converting the Windows Script Host LogEvent Method
Converting the Windows Script Host MapNetworkDrive Method
Converting the Windows Script Host Popup Method
Converting the Windows Script Host Quit Method
Converting the Windows Script Host Read Method
Converting the Windows Script Host ReadAll Method
Converting the Windows Script Host ReadLine Method
Converting the Windows Script Host RegDelete Method
Converting the Windows Script Host RegRead Method
Converting the Windows Script Host RegWrite Method
Converting the Windows Script Host Remove Method
Converting the Windows Script Host RemoveNetworkDrive Method
Converting the Windows Script Host RemovePrinterConnection Method
Converting the Windows Script Host Run Method
Converting the Windows Script Host Save Method
Converting the Windows Script Host SendKeys Method
Converting the Windows Script Host SetDefaultPrinter Method
Converting the Windows Script Host ShowUsage Method
Converting the Windows Script Host SignFile Method
Converting the Windows Script Host Skip Method
Converting the Windows Script Host SkipLine Method
Converting the Windows Script Host Sleep Method
Converting the Windows Script Host Terminate Method
Converting the Windows Script Host VerifyFile Method
Converting the Windows Script Host Write Method
Converting the Windows Script Host WriteBlankLines Method
Converting the Windows Script Host WriteLine Method
Introduction to Windows PowerShell Transactions
Introduction to Windows PowerShell 2.0 CTP v2
Join the Social
Remoting Quoting
Script Editors
Searching Active Directory with Windows PowerShell
Select-String Cmdlet Updates
Specops Command
The Get-Random Cmdlet
The Out-GridView Cmdlet: Displaying Information in a Data Grid
The Out-Gridview Cmdlet: Filter With Out-GridView
The Set-StrictMode Cmdlet
The Windows PowerShell Debugger
WMI Enhancements in Windows PowerShell 2.0 CTP
WMI Event Monitoring
Workflow Studio

PowerShell: Get network adapter connection status

This powershell function helps you to get the network status of all network adapters in a given computer. Using this script it is easy to determine the status of all network connections in remote computer to see whether it is connected/disconnected/media disconnected/and different other statuses. This script queries Win32_NetworkAdapter WMI class for list of network adapters and then fetches the status of each adapter by querying “netconnectionstatus” parameter. This is a uint16 data type which returns any value ranging from 0-12. Each value from 0 to 12 has it’s own meaning. See the below table for details(source: MSDN)

Value Meaning
0 (0×0)
Disconnected
1 (0×1)
Connecting
2 (0×2)
Connected
3 (0×3)
Disconnecting
4 (0×4)
Hardware not present
5 (0×5)
Hardware disabled
6 (0×6)
Hardware malfunction
7 (0×7)
Media disconnected
8 (0×8)
Authenticating
9 (0×9)
Authentication succeeded
10 (0xA)
Authentication failed
11 (0xB)
Invalid address
12 (0xC)
Credentials required

So, here is the script which lists the network adapter name and its status.

Script:

function Get-NetworkConnectionStatus {
param(
$ComputerName=$env:computername
)
$statushash = @{
0 = "Disconnected"
1 = "Connecting"
2 = "Connected"
3 = "Disconnecting"
4 = "Hardware not present"
5 = "Hardware disabled"
6 = "Hardware malfunction"
7 = "Media Disconnected"
8 = "Authenticating"
9 = "Authentication Succeeded"
10 = "Authentication Failed"
11 = "Invalid Address"
12 = "Credentials Required"
}
$networks = Gwmi -Class Win32_NetworkAdapter -ComputerName $computername
$networkName = @{name="NetworkName";Expression={$_.Name}}
$networkStatus = @{name="Networkstatus";Expression=`
{$statushash[[int32]$($_.NetConnectionStatus)]}}
foreach ($network in $networks) {
  $network | select $networkName, $Networkstatus
  }
}

Usage:

Get-NetworkConnectionStatus -ComputerName PC1

Hope this helps…

Powershell: Check laptop battery status

June 30, 2011 1 comment

In this post, I will show you how to pragmatically query battery status in laptops using powershell. It is important to check batter status before performing some critical tasks like patch updates or service pack updates via some automation(s). If the laptop charging drains down in middle of the upgrade, it can corrupt the operating system.

You can use below one liner to check the percentage of charging left in the battery:

(Get-WmiObject -Class Win32_Battery).estimatedchargeremaining

Similarly, if you want to how many more minutes this charging comes, you can use below code:

(Get-WmiObject -Class Win32_Battery).EstimatedRunTime

Hope this helps and you will have crash free upgrades on laptops.

PowerShell: Get CPU architecture on windows 7 computer

I wrote on the similar topic before. My earlier attempt was to determine OS architecture but this time, I am going to talk about querying CPU architecture using powershell code. It is needless to explain the difference between these two things. :-)

So, below is the code which helps you determine CPU architecture of a computer.

function Get-CPUArchitecture {
if (($ENV:Processor_Architecture -eq "x86" -and (test-path env:PROCESSOR_ARCHITEW6432)) -or ($ENV:Processor_Architecture -eq "AMD64")) {
write-host "Detected 64-bit CPU architecture"
} elseif ($ENV:Processor_Architecture -eq 'x86') {
write-host "Detected 32-bit CPU architecture"
} else {
write-host "Unable to determine CPU architecture"
}
}

Hope this helps…

Tip: Get the domain controller details using PowerShell

September 2, 2010 Leave a comment

 

This small powershell command helps you to get the domain controller name currently in use.

PS C:> ([ADSI]“LDAP://RootDSE”).dnshostname
DC1.Techibee.com
PS C:>

You can also know to which site this DC belongs to.

PS C:> ([ADSI]“LDAP://RootDSE”).servername.tostring().split(“,”)[2].Split(“=”)[
1]
SITE1
PS C:>

Isn’t it looking a bit complex to query the site name? Any alternatives? Yes, we do have one. Below helps you to query the Site name of DC you connected.

import-module ActiveDirectory

Get-ADDomainController -Discover | select Site

Site
—–
SITE1

Note that above command requries ActiveDirectory PowerShell module which is generally available in Windows 7. One more requirement to make ActiveDirectory Module work agaist your Active Directory is, your DCs should have ADWS(active directory web services) installed. These services comes by default with windows 2008 servers but on windows 2003 servers you need to install this additional components.

Refer to my old article about Active Directory Administrative Center where I talked about ADWS for windows 2003.

Lock your workstation using PowerShell

One other nice thing I found with PowerShell is it’s ability of using APIs by importing DLLs. Below is one example, where user32.dll is imported and LockWorkstation Function is invoked to lock the desktop. Btw, I grabbed this script from TechNet Library

Function Lock-WorkStation {
$signature = @”
[DllImport("user32.dll", SetLastError = true)]
public static extern bool LockWorkStation();
“@

$LockWorkStation = Add-Type -memberDefinition $signature -name “Win32LockWorkStation” -namespace Win32Functions -passthru
$LockWorkStation::LockWorkStation() | Out-Null
}

After executing above code, invoking “Lock-WorkStation” command from PowerShell window will lock your PC.

Happy Learning..,
Sitaram Pamarthi

Categories: PowerShell, Scripting

Script to ping machines part of Active Directory Security Group

November 19, 2009 1 comment
Today I want to turn my some of the scripting efforts to public.
Sometimes I get requirements to see how many machines are online which are part of a AD security group. I worst method I used to follow was dumping the group member list to some text file and making use of a batch script to ping the machine and check the status. This is pretty good but consuming some of my time for dumping and analyzing. So why below script is born….
You just need to give the group DN in the script and execute it with cscript. That shows the machine status if it is online or not. Feel free to modify the script to match your requirements and let me know if I can be of any help.
‘##########################################################################
‘# Purpose : To check the ping status of computers part of a security group
‘# Author  : Sitaram Pamarthi
‘#
‘##########################################################################
‘On Error Resume Next

‘ Replace with your group DN
GroupDN=”ldap://CN=Your/ Group Name,OU=Your OU name,DC=domain,DC=com”

Set objGroup = GetObject(GroupDN)
objGroup.GetInfo
arrMemberOf = objGroup.GetEx(“member”)
For Each strMember in arrMemberOf
  Set objGroup1 = GetObject(“LDAP://” & strMember)
  strHost=trim(objGroup1.dNSHostName)
  set objPing = GetObject(“winmgmts:{impersonationLevel=impersonate}”).ExecQuery _
      (“select * from Win32_PingStatus where address = ‘” & strHost & “‘”)

  for each objRetStatus in objPing
    if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
        WScript.Echo strhost & “  ==> host not reachable”
    else
        Ping = True
        wscript.echo strhost & ” ==> Machine Reachable”
    end if
  next
Next

‘#End of script.

Happy Learning…,
Sitaram Pamarthi

Quick way to find hotfix installation status

I know there are varioud menthods for finding the hotfix installation status, but I felt this as very easy one.

To find the hotfix installation status on local machine:

wmic qfe where hotfixid=”KB958644″ list full

To find on a remote machine:

wmic /node: qfe where hotfixid=”KB958644″ list full

To find on list of machines:

o Place all machines into a text file(machine.txt)
o Run the below batch file

=== File name: get-hotfix-status.bat ===

echo off
for /f “tokens=* delims= ” %a in (test.txt) do wmic/Node:%a qfe where hotfixid=”KB958644″ list full

=== End of file ===

Please comment if you know any better way.

Happy Learning,
Sitaram Pamarthi,

Categories: Know your Shell, Scripting