trying to test for existance of a string in a file name before renaming

This topic contains 1 reply, has 2 voices, and was last updated by  Don Jones 2 years, 11 months ago.

  • Author
  • #27735

    rob merritt

    I have a simple script to rename some files
    cd e:\scripts\br
    Get-ChildItem -Filter "13615*.pdf" -Recurse | Rename-Item -NewName {$ -replace '136150','0' }
    Get-ChildItem -Filter "11111*.pdf" -Recurse | Rename-Item -NewName {$ -replace '111110','0' }
    #Write-Output -Recurse | {$}
    if ( $"-01") -ne "True" ) {
    Get-ChildItem -Filter "*.1.pdf" -Recurse | Rename-Item -NewName {$ -replace '.1.pdf','-01x.1.pdf' }
    Write-Output Done

    what i get when i run it is
    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 ( $"-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?

  • #27736

    Don Jones

    You're misusing $_.

    You've probably seen it used in commands like ForEach-Object and Where-Object, which is where it's made to be used (mostly). But $_ can only be used in specific situations where PowerShell knows to look for it, and you're not in one of those situations.

    For example, what you're doing with -NewName is also not legal. Write-Output doesn't have a -Recurse parameter. In the specific place where you're getting the error, $_ has literally no meaning. Therefore, it doesn't have a Name property, therefore, the Contains() method is being called for a null-valued expression, which is the error.

    You might be able to rewrite things.

    Get-ChildItem -Filter "13615*.pdf" -Recurse | ForEach-Object {
      Rename-Item -NewName ($_.Name -replace '136150','0′)
      if ($"-01")) {

    Within those outermost {} of ForEach-Object, PowerShell will replace $_ with the current pipeline object.

You must be logged in to reply to this topic.