Erik Hörmann
Erik Hörmann

Reputation: 1

Q: Basic PowerShell Script Issue: “Expressions are only allowed as the first element of a pipeline”

I know well, this issue has already been discussed a lot. But even though I am unable to solve it myself, since I only use powershell scripting rarely...

I have the following commands, that I need to execute as a ".bat" file. If I just execute it within a command window, all works fine. But if I execute it within a ".bat" file, I get the error from the title...

powershell -Command "&{$devices = gwmi Win32_USBControllerDevice |%{[wmi] ($_.Dependent)}|select DeviceID;$devices.DeviceID | %{Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Enum\$_"}| select FriendlyName,HardwareID}"

Within the ".bat" file I added an additional line with "pause", that seems not to be the cause of the problem...

I would be very happy if someone more advanced in scripting could tell me what 1 to 10 chars need to be added/changed in the command to make it work ;-)

Big thanks in advance!!!

Regards, Erik

Upvotes: 0

Views: 1304

Answers (1)

Compo
Compo

Reputation: 38622

Based upon your response to my initial comment, the reason for that error is that you're using the % alias for ForEach-Object, and in a batch file, the % character needs to be escaped using another % character.

Including the nested double-quote escaping with backward slashes, I've already advised, your resulting command would therefore be:

powershell -Command "&{$devices = gwmi Win32_USBControllerDevice |%%{[wmi] ($_.Dependent)}|select DeviceID;$devices.DeviceID | %%{Get-ItemProperty -Path \"HKLM:\SYSTEM\CurrentControlSet\Enum\$_\"}| select FriendlyName,HardwareID}"

Tested result example:

enter image description here


If I was doing this I'd probably have done it a little differently:

%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command^
 "((Get-CimInstance Win32_USBControllerDevice).Dependent).DeviceID |"^
 "ForEach-Object {"^
    "Get-ItemProperty -Path \"HKLM:\SYSTEM\CurrentControlSet\Enum\$_\""^
 "} | Select-Object FriendlyName, HardwareID"

And using shortened commands/aliases:

PowerShell -NoP "((gcim Win32_USBControllerDevice).Dependent).DeviceID|%%{gp \"HKLM:\SYSTEM\CurrentControlSet\Enum\$_\"}|Select FriendlyName,HardwareID"

Upvotes: 3

Related Questions