having problems with null value?

I have a simple script to rename some files 

#cls
cd e:\scripts\br
Get-ChildItem -Filter "13615*.pdf" -Recurse | Rename-Item -NewName {$_.name -replace '136150','0' }
Get-ChildItem -Filter "11111*.pdf" -Recurse | Rename-Item -NewName {$_.name -replace '111110','0' }
#Write-Output  -Recurse |  {$_.name}
if ( $_.name.contains("-01") -ne "True" ) {
 Get-ChildItem -Filter "*.1.pdf" -Recurse | Rename-Item -NewName {$_.name -replace '.1.pdf','-01x.1.pdf' }
 }
Write-Output Done

what i get when i run it is 

Done
PS E:\scripts\br> powershell.exe .\renamer.ps1
You cannot call a method on a null-valued expression.
At E:\scripts\br\renamer.ps1:6 char:6
+ if ( $_.name.contains("-01") -ne "True" ) {
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

so clearly $_name.contains("-01") isnt working the way I expect...any ideas on where I am going wrong?

July 21st, 2015 2:48pm

if ( $name -match '01') {

You cannot use pipe variables because you have no pipeline.  What you are trying to do looks very confused.

We do not match with the string 'True' for truth value as this will fail in many cases so don't start a bad habit so soon.  The results of a test are always $true or $false and an "if" always succeeds when the value is $true.

$_ is null in your code. It is only valid in a pipeline.

Go back and rethink what you are doing.  Revue the learning materials.  If you still are confused than as a specific question.

Free Windows Admin Tool Kit Click here and download it now
July 21st, 2015 3:15pm

OK what I am trying to do is get inside this recursion and before doing the replace 

Get-ChildItem -Filter "*.1.pdf" -Recurse | Rename-Item -NewName {$_.name -replace '.1.pdf','-01.1.pdf' }

check if the $_.name  has the characters "-01.1.pdf" in it 

July 21st, 2015 3:23pm

It still doesn't make any sense but here it is:

Get-ChildItem -Filter "*.1.pdf" -Recurse | 
     Where{$_.Name -notmatch '-01.1.pdf'} |
     ForEach-Object{
          Rename-Item -NewName ($_.name -replace '.1.pdf','-01.1.pdf')
     }
Free Windows Admin Tool Kit Click here and download it now
July 21st, 2015 3:48pm

You can also do this:

Get-ChildItem -Filter "*.1.pdf" -Exclude *-01.1.pdf -Recurse | 
     ForEach-Object{
          Rename-Item -NewName ($_.name -replace '.1.pdf','-01.1.pdf')
     }

July 21st, 2015 3:51pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics