Hey, Scripting Guy! Quick-Hits Friday: The Scripting Guys Respond to a Bunch of Questions (2/26/10)

Hey, Scripting Guy! Quick-Hits Friday: The Scripting Guys Respond to a Bunch of Questions (2/26/10)

  • Comments 1
  • Likes

Bookmark and Share

In this post:

 

Can I Retrieve the Version of Installed Java Applications?

Hey, Scripting Guy! Question

Hey, Scripting Guy! I'm wondering how to determine what are good values to type right before ".Application" like in this line below:

CreateObject("Excel.Application")

I was trying to customize a script to retrieve the version of Java applications. I did this but it won't work.

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colApps = objWMIService.ExecQuery _
    ("Select * from Win32_Product Where Caption Like '%java%'") For Each objApp in colApps
    Wscript.Echo objApp.Caption, objApp.Version Next

 

-- EZ

 

Hey, Scripting Guy! AnswerHello EZ,

The answer to the first question is a bit complicated. Applications are registered in the HKEY_CLASSES_ROOT registry hive, so you can explore there to find objects you can use. Useful objects are documented on MSDN. The problem is that the number of objects that are available varies from machine to machine depending on what applications have been installed, what version of the operating system, and even what service pack level the operating system is running. There is no master list of COM objects, and never will be due to its dynamic and changeable nature.

Your second question is easier to answer: The Win32_Product WMI class only reports on products that have been installed via the Windows Installer technology. This is because the class itself is part of the WMI Windows Installer provider. It does a great job on MSI installed applications, but unfortunately, not all applications use this type of an installer. I would hazard a guess that Java apps fall into that category. There is a registry key that contains information about all installed applications, and in many cases their uninstall keya script that reads that keymay be more profitable for you to use. Here is a link to a script that should get you started.



How Can I Run a Function Based on What Is or Is Not Entered on the Command Line?

Hey, Scripting Guy! Question

Okay, I am trying to write a function to allow either a computer name or a file name (to build an array of computer names) and then perform a function. I am trying to figure out how to test to make sure one (not both) parameter is entered and then perform actions based on that. Where I am struggling is how to deal with a situation where either both parameters or neither parameter is entered at the command line. I could use PrimalForms or something, but thinking I am just missing a step. 

Param(
    [String[]]$computername,
    [String[]]$Filename
)
$args.length
If ($computername -ne $Null) {"Computer name was entered"}
if ($filename -ne $Null) {"File name was entered"}

-- JK

 

Hey, Scripting Guy! AnswerHello JK,

I use the mandatory parameter qualifier (new in Windows PowerShell 2.0). Here is a script I wrote for the Windows 7 Resource Kit that illustrates using mandatory parameters.

CreateLocalGroup.ps1

<#
   .Synopsis
    Creates a local group on either a local or remote machine.
   .Description
    This script creates a local group on either a local or a remote computer.
    Requires admin rights to create a group.
     PARAMETERS:
     -computer Specifies the name of the computer upon which to run the script
     -group    Name of group to create
     -description
   .Example
    CreateLocalGroup.ps1 -computer MunichServer -group MyGroup
    Creates a local group called MyGroup on a computer named MunichServer
   .Example
    CreateLocalGroup.ps1 -group Mygroup
    Creates a local group called MyGroup on local computer
   .Inputs
    [string]
   .OutPuts
    [string]
   .Notes
    NAME:  Windows 7 Resource Kit
    AUTHOR: Ed Wilson
    LASTEDIT: 5/20/2009
    KEYWORDS:
   .Link
    
Http://www.ScriptingGuys.com
#Requires -Version 2.0
#>
Param(
  [Parameter(Position=0,ValuefromPipeline=$true)]
  [string]
  [alias("cn")]
  $computer=$env:computername,
  [Parameter(Mandatory=$true)]
  [string]
  $group,
  [string]
  $description = "created by script"
) #end param

# Begin Functions
function New-Underline
{
<#
.Synopsis
Creates an underline the length of the input string
.Example
New-Underline -strIN "Hello world"
.Example
New-Underline -strIn "Morgen welt" -char "-" -sColor "blue" -uColor "yellow"
.Example
"this is a string" | New-Underline
.Notes
NAME:
AUTHOR: Ed Wilson
LASTEDIT: 5/20/2009
KEYWORDS:
.Link
Http://www.ScriptingGuys.com
#>
[CmdletBinding()]
param(
      [Parameter(Mandatory = $true,Position = 0,valueFromPipeline=$true)]
      [string]
      $strIN,
      [string]
      $char = "=",
      [string]
      $sColor = "Green",
      [string]
      $uColor = "darkGreen",
      [switch]
      $pipe
) #end param
$strLine= $char * $strIn.length
if(-not $pipe)
  {
   Write-Host -ForegroundColor $sColor $strIN
   Write-Host -ForegroundColor $uColor $strLine
  }
  Else
  {
  $strIn
  $strLine
  }
} #end function New-Underline

function Test-IsAdministrator
{
    <#
    .Synopsis
        Tests if the user is an administrator
    .Description
        Returns true if a user is an administrator, false if the user is not an administrator       
    .Example
        Test-IsAdministrator
    #>  
    param()
    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    (New-Object Security.Principal.WindowsPrincipal $currentUser).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
} #end function Test-IsAdministrator

# *** Entry point to script ***
If(-not (Test-IsAdministrator)) { New-Underline "Admin rights are required for this script" ; exit }
Try
{
  $error.Clear()
  $adsi = [ADSI]"WinNT://$computer"
  $objgroup = $adsi.Create("Group", $group)
  $objgroup.SetInfo()
  $objgroup.description = $description
  $objgroup.SetInfo()
  }
Catch {"an error occurred"}
Finally

  if($error.count -eq 0)
   { New-Underline("Created $group with description $description on $computer") }
   ELSE
   {
    New-Underline("Unable to create $group with description $description on $computer")
    New-Underline("Please ensure you are running with admin rights")
   } #end else
} #end finally


 

How Can I Properly Use Double Quotation Marks for Expansion?

Hey, Scripting Guy! Question

Hey, Scripting Guy!

I have just upgraded to Windows 7 and am working on some scripting at the moment. When I put a variable in a string enclosed by double quotation marks, the variable is not being expanded. Instead of passing the value, it passes the literal $variablename.

-- AU

 

Hey, Scripting Guy! AnswerHello AU,

Strange. Double quotation marks should automatically expand. On my Windows 7 box, this works:

PS C:\> $a = "this is a string"
PS C:\> "This is the value of $a"
This is the value of this is a string
PS C:\> 'This is the literal value $a'
This is the literal value $a
PS C:\>


When using double quotation marks, if you want to suppress expansion, escape the dollar sign as seen here:

PS C:\> $a = "this is a string"
PS C:\> "Use the back tick to escape the variable: `$a"
Use the back tick to escape the variable: $a
PS C:\>


This is seen in the following image:

Image of suppressing expansion 


It is possible that you may be copying code that has “smart” or curly quotation marks instead of straight quotation marks. Windows PowerShell does not know how to interpret smart quotation marks properly.
 

 

Does Windows 7 Support Scripting Registry Changes? 

Hey, Scripting Guy! Question

Hey, Scripting Guy!

Why would Windows 7 not support scripting registry changes? This script works on Windows XP and on Windows Server 2003; however, it won't work on Windows 7. I also see on the Script Center in the script examples similar scripts are not listed as supported. Did you guys remove the registry calls?

-- MC

Hey, Scripting Guy! AnswerHello MC,

The reason scripts on the script repository are not checked for Windows 7 simply means they were written before Windows 7. It does not necessarily mean they will not work; it means we have not tested them on Windows 7. There are thousands of scripts on the Script Repository, and though we test the scripts we post at the time they are posted, we do not have time or bandwidth to go back and revisit scripts to update the boxes. If we did that, we would not have time to write new scripts.

Having said that, I can tell you that most of the scripts should in fact work. There are issues in trying to access 32-bit and 64-bit portions of the registry, but the FileSystem object and the WMI classes do still work with the registry on Windows 7. You could also be running into registry permission issues because we changed many security settings between Windows XP and Windows 7.

 

Well, this concludes another edition of Quick-Hits Friday. Join us tomorrow for Weekend Scripter. We will be talking about…well, we will let that remain a mystery for now.

If you want to know exactly what we will be looking at tomorrow, follow us on Twitter or Facebook. If you have any questions, send e-mail to us at scripter@microsoft.com or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

 

Ed Wilson and Craig Liebendorfer, Scripting Guys

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • I had the same problem with my old scripts not working in Vista or Windows 7.  A nice guy like you gave me the code to add.  Add Part 1 to the beginning and End If to the very end it will run in Windows 7.  That also helps if you want to run a script as an admin on a Windows XP system running a restricted profile.

    1)  If you add this to the beginning of your code ....

    ' This adds the Admin Run Function for Windows Vista and 7

    ' You must put this at the top below computer and End If at the

    ' very end of the script

    If WScript.Arguments.length = 0 Then

    Set objShell = CreateObject("Shell.Application")

    objShell.ShellExecute "wscript.exe", """" & _

    WScript.ScriptFullName & """" &_

    " RunAsAdministrator", , "runas", 1

    Else

    And at the very end....

    End If