Matthew North
Matthew North

Reputation: 555

Exception handing using SWbemLocator on different architectures

I have the following bit of Powershell within a script that will need to run many machines and add a registry key. On an x64 machine this key needs adding to both the 32-bit and 64-bit section of the registry.

    $objswbem = New-Object -ComObject "WbemScripting.SWbemNamedValueSet"            
    $objswbem.Add("__ProviderArchitecture", $Arch) | Out-null            
    $objswbem.Add("__RequiredArchitecture", $True) | Out-null            
    $ObjLocator = New-Object -ComObject "Wbemscripting.SWbemLocator"            
    $objServices = $objLocator.ConnectServer($Computer,"root\Default",$null,$null,$null,$null,$null,$objswbem)            
    $objReg = $objServices.Get("stdRegProv")

This will have both the values 32 and 64 passed to it separately.

What I am unsure about is what exception would be thrown on a 32bit machine when $Arch is set to 64 as I need to handle this and allow the script to continue without running the 64 bit operations, else throw the exception. I have tested with an invalid number such as 128 and it throws an invalid number exception at $objLocator.ConnectServer. I'm just not sure if it would be the same exception with the valid number 64 passed.

I don't have access to a 32 bit machine to test the script on myself and haven't found the relevant documentation online.

Upvotes: 0

Views: 374

Answers (1)

Ranadip Dutta
Ranadip Dutta

Reputation: 9163

I am giving you the logic how to proceed with it. I have made the script according to your requirement and I have also added comments on each line for your understanding and reference. Add the codes what ever you are doing based on that

$Input_file= Get-Content D:\Serverlist.txt # Getting list of servers from the text file

foreach($Input in $Input_file) # Iterating each server
{
  $OS_Architecture=(Get-WmiObject Win32_OperatingSystem -ComputerName $Input ).OSArchitecture # Getting the OS Architecture for each server
  if($OS_Architecture -eq '64-bit')
    {
    # write the code for 64 bit OS Architecture
    <#
    $objswbem = New-Object -ComObject "WbemScripting.SWbemNamedValueSet"            
    $objswbem.Add("__ProviderArchitecture", $Arch) | Out-null            
    $objswbem.Add("__RequiredArchitecture", $True) | Out-null            
    $ObjLocator = New-Object -ComObject "Wbemscripting.SWbemLocator"            
    $objServices = $objLocator.ConnectServer($Computer,"root\Default",$null,$null,$null,$null,$null,$objswbem)            
    $objReg = $objServices.Get("stdRegProv")
    #>
    }
   else 
   {
   # Write the code for 32 Bit OS Architecture
   }

Note: If you are running all the commands remotely then use scriptblock and Invoke-command passing the computernames as parameter.

Hope it helps you in understanding the logic.

Upvotes: 1

Related Questions