Powershell code works in editor but not in Powershell cmd it self?

0

When i run this code in the editor it works perfectly: (not a single error)

$vm = 0
$vpc=new-object –com VirtualPC.Application –Strict
foreach ($vm in $vpc.VirtualMachines){}
$broken = Get-WmiObject Win32_PnPEntity | where {$_.ConfigManagerErrorCode -ne 0}
$usbDevice = $vpc.USBDeviceCollection | ? {$_.DeviceString -eq $usb} | select -first 1
$vm.AttachUSBDevice($usbDevice)

when i put this code in one line with ; at the end:

$vm = 0; $vpc=new-object –com VirtualPC.Application –Strict; foreach ($vm in $vpc.VirtualMachines){}; $broken = Get-WmiObject Win32_PnPEntity | where {$_.ConfigManagerErrorCode -ne 0}; $usbDevice = $vpc.USBDeviceCollection | ? {$_.DeviceString -eq $usb} | select -first 1; $vm.AttachUSBDevice($usbDevice)

it gives me the 0×80020005 error:

Exception calling "AttachUSBDevice" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_T
YPEMISMATCH))"
At line:1 char:293
+ $vpc=new-object -com VirtualPC.Application -Strict; $vm = $vpc.findVirtualMachine("Windows XP Mode"); $broken = Get-W
miObject Win32_PnPEntity | where {$_.ConfigManagerErrorCode -ne 0}; $usbDevice = $vpc.USBDeviceCollection | ? {$_.Devic
eString -eq $usb} | select -first 1; $vm.AttachUSBDevice <<<< ($usbDevice)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

Someone knows how to solve this problem?

(I know the code is a bit weird but thats not the point :))

powershell
cmd
xp-mode
asked on Stack Overflow Oct 15, 2011 by Freddy

1 Answer

1

There are many problems with your code and it may just be working in your editor because of some variable etc. set in your editor runspace which are not there in the code. And even when it supposedly worked in editor, it may not be what you wanted to happen or what you expected it to do.

For example $usb is not defined anywhere in your code. So basically $usbDevice will come out empty and in the next command you are bound to get a type mismatch.

Other corrections / suggestions:

$vm = 0 - You don't have to "declare" variables. Powershell is a dynamic language.

foreach ($vm in $vpc.VirtualMachines){} - what is the point of this line? Finally you will end up with $vm having the last virtual machine from $vpc.VirtualMachines

Why do you want to have them in a single line? You can copy the lines and paste in the console if you want. Or, you can put these in a script and run the script.

answered on Stack Overflow Oct 15, 2011 by manojlds

User contributions licensed under CC BY-SA 3.0