1

I am writing a powershell script but having a problem evaluating a boolean expression.

This is the line of code I am having a problem with:

if (Get-Content .\Process2Periods.xmla | Select-String ((Get-Date) | Get-Date -Format "yyyyMM") -quiet -ne True)

I am getting this error message when trying to run:

Select-String : A parameter cannot be found that matches parameter name 'ne'.

Please help me understand the issue.

Also for a little context, I am searching a file for a string and if it doesn't exist I want to execute what is in the if block. I didn't paste the code in the if statement because I don't believe it is relevant but please let me know if you would like to see it.

2 Answers2

4

PowerShell is interpreting the -ne as being a parameter for Select-String. To fix the problem, you can remove the -ne True part and use the -not operator instead:

if (-not (Get-Content .\Process2Periods.xmla | Select-String ((Get-Date) | Get-Date -Format "yyyyMM") -quiet))

Note that ! would also work if you prefer it over -not:

if (!(Get-Content .\Process2Periods.xmla | Select-String ((Get-Date) | Get-Date -Format "yyyyMM") -quiet))

Also, the (Get-Date) | Get-Date -Format "yyyyMM" part of the line above is unnecessary. You can instead just do Get-Date -Format "yyyyMM". See below:

PS > (Get-Date) | Get-Date -Format "yyyyMM"
201502
PS > Get-Date -Format "yyyyMM"
201502
PS > 
  • You sir\ma'am are a God. Will check this answer in 6 minutes. Thank you very much. – powershelluser Feb 18 '15 at 21:18
  • @powershelluser Would like to mention that `(Get-Date) | Get-Date -Format "yyyyMM"` looks redundant and `Get-Date -Format "yyyyMM"` on its own would work just as well. – Matt Feb 18 '15 at 21:28
  • @Matt - I added that to my answer for you. I only had the other version because I copied it from the OP's code. –  Feb 18 '15 at 21:40
  • @Matt - Nice, thank you Matt. One thing, I tried shortening the following line but was unable to get it to work: $monthMinus1 = (Get-Date).AddMonths(-1) | Get-Date -Format "yyyyMM" to $monthMinus1 = (Get-Date).AddMonths(-1) -Format "yyyyMM". Do you know if there to pull this off? Thank you. – powershelluser Feb 19 '15 at 15:03
  • @powershelluser If you are going to do date manipulation then just leave it the way you had it. Your example in the question was redundant but the example in your comment requires something like what you already have. Leave it alone for you case. – Matt Feb 19 '15 at 15:22
1

Your parenthesizing is off.

The -quiet and -ne arguments are being see as arguments to Select-String.

I'm unsure what command you wanted -quiet to apply to (I expect Select-String) but you need to wrap the entire Get-Content ... | Select-String ... bit in () and then use -ne "True" or -ne $True (depending on whether you want string or boolean true).

if ((Get-Content .\Process2Periods.xmla | Select-String ((Get-Date) | Get-Date -Format "yyyyMM") -quiet) -ne $True)
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148