Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negation in cmd and powershell

Tags:

powershell

cmd

Is there a way to do negation in cmd or powershell? In other words, what I want is to find all files that do not meet a certain criteria (other than attribute where negation is specified as "-") say in the name. It would be helpful if there was a generic negation that could be used in other contexts as well. In addition, for powershell, is there a way to get the list of file names and then store it as an array that can be sorted etc?

Apologies for asking something that seems so basic.

like image 339
soandos Avatar asked May 23 '11 23:05

soandos


People also ask

What does @() mean in PowerShell?

Array subexpression operator @( )Returns the result of one or more statements as an array. The result is always an array of 0 or more objects. PowerShell Copy.

What is @{} in PowerShell?

@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'


1 Answers

With PowerShell there are many ways to negate a set of criteria, but the best way depends on the situation. Using a single negation method in every situation could be very inefficient at times. If you wanted to return all items that were not DLLs older than 05/01/2011, you could run:

#This will collect the files/directories to negate
$NotWanted = Get-ChildItem *.dll| Where-Object {$_.CreationTime -lt '05/01/2011'}
#This will negate the collection of items
Get-ChildItem | Where-Object {$NotWanted -notcontains $_}

This could be very inefficient since every item passing through the pipeline will be compared to another set of items. A more efficient way to get the same result would be to do:

Get-ChildItem | 
  Where-Object {($_.Name -notlike *.dll) -or ($_.CreationTime -ge '05/01/2011')}

As @riknik said, check out:

get-help about_operators
get-help about_comparison_operators

Also, many cmdlets have an "Exclude" parameter.

# This returns items that do not begin with "old"
Get-ChildItem -Exclude Old*

To store the results in an array that you can sort, filter, reuse, etc.:

# Wrapping the command in "@()" ensures that an array is returned
# in the event that only one item is returned.
$NotOld = @(Get-ChildItem -Exclude Old*)

# Sort by name
$NotOld| Sort-Object
# Sort by LastWriteTime
$NotOld| Sort-Object LastWriteTime

# Index into the array
$NotOld[0]
like image 78
Rynant Avatar answered Oct 05 '22 16:10

Rynant