1

I want to know if this command can be written without the pipelines(vertical lines)?

$u=gwmi Win32_Volume|?{$_.Label -eq'_'}|select name;cd $u.name;.\d.cmd
1
  • Your keyboard doesn't have the pipe symbol? (This post is on Technet too.) That's very limiting. There's always copy and paste.
    – js2010
    Commented Dec 3, 2019 at 18:14

3 Answers 3

1

So to start you should always try to move the filters left, so if the cmdlet in question has a filtering capability try to use it. In this case it will spare you the | Where-Object.

$Vols = gwmi -Query "SELECT Name FROM Win32_Volume WHERE Label = '_'"

At this point I think you're in good shape, but the subsequent commands:

cd $Vols.name
.\d.cmd

These may not work if $Vols returns multiple objects.

I don't know what the real intent is, but strictly speaking you can still avoid the pipeline with something like:

ForEach($Vol in $Vols){ 
    cd $Vol.name
    .\d.cmd
}

That's why I changed $u to $Vols...

If you only wanted to work with the name property you can focus on is with automatic variable unrolling like:

$Vols = (gwmi -Query "SELECT Name FROM Win32_Volume WHERE Label ='_'" ).Name

ForEach($Vol in $Vols){ 
    cd $Vol
    .\d.cmd
}

Let me know what you think we can work further on it.

0

The ? block can be replaced by a WMI filter and the select statement can be replaced with the member reference (.) operator.

Finally, you can join the result of that operation directly to the file name and skip cd:

& (Join-Path (gwmi Win32_Volume -Filter "Label = '_'").Name 'd.cmd')
0
$u=gwmi Win32_Volume|?{$_.Label -eq '_'}|select name

and

$u = foreach ( $a in (gwmi Win32_Volume) ) { if ($a.Label -eq '_') { [PSCustomObject]@{Name = $a.Name}} }

Above commands are equivalent however both could result to one of the following:

  • a PSCustomObject (then $u.Name gives a string), or
  • an array (then $u.Name gives an array as well so that cd $u.Name would fail), or
  • $null value (then $u.Name throws an error and cd $u.Name would fail as well).

Not the answer you're looking for? Browse other questions tagged or ask your own question.