Reputation: 13
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
Upvotes: 1
Views: 139
Reputation: 7057
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.
Upvotes: 1
Reputation: 30103
$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:
PSCustomObject
(then $u.Name
gives a string), or$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).Upvotes: 0
Reputation: 174435
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')
Upvotes: 0