power shell is giving file not found error when renaming a folder

后端 未结 1 1229
南方客
南方客 2021-01-28 02:03

What I am trying to do is change the name of a folder if any file in it contains contains string \"ErrorCode :value\" where the value can be anything other than zero. I have old

相关标签:
1条回答
  • 2021-01-28 02:28

    If there are multiple *.data-files in the same folder you code will rename the folder after it found the first file that does NOT contain "ErrorCode": 0. When it tries to get the next file or to rename the folder again, it won't be able to find it since it has been renamed.

    You wrote you want to rename the folder if the file -match '"ErrorCode": 0' but if this condition is fulfilled you execute {} (nothing). However if the condition is not fulfilled you execute your code else{...}

    To prevent your code from renaming the folder multiple times while working in the folder, collect the foldernames first in an array an rename them later:

    $fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.data
    $FoldersToRename = @() #initialize as array
    
    foreach ($file in $fileNames) {
        If (Get-Content $file | %{$_ -match '"ErrorCode": 0'}) 
        {
            $FoldersToRename += Split-Path $file
        }
    }
    
    $SingelFolders = $FoldersToRename | Select-Object -Unique #Select every folder just once
    $SingelFolders | ForEach-Object { 
        $newPath=$_ + "Error"
        Rename-Item $_ $newPath
    }
    

    edit: Matching anything BUT '"ErrorCode": 0'

    -match uses regular expressions (regex) wich comes very handy in here.
    Any single-digit number but 0 would be [1-9] in regex. If your ErrorCode can have multiple digits, you can use \d{2,} to match 2 or more ({2,}) numbers (\d). Combined these would look like this: ([1-9]|\d{2,}) (| = or)
    And here is it in the code from above:

    foreach ($file in $fileNames) {
        If (Get-Content $file | %{$_ -match '"ErrorCode": ([1-9]|\d{2,})'}) 
        {
            $FoldersToRename += Split-Path $file
        }
    }
    

    edit2: Ignoring whitespaces /tabs:

    regex for anykind of whitespace is \s. * means 0 or more: the string would be '"ErrorCode":\s*([1-9]|\d{2,})'

    edit3: "Code" optional:

    Here is the ultimate regex string to match ay kind of Error with optional quotation marks, "Code" and the colon:
    "?Error(Code)?"?:?\s*([1-9]|\d{2,}) > {$_ -match '"?Error(Code)?"?:?\s*([1-9]|\d{2,})'}
    Matchingexamples:

    "ErrorCode": 404

    "ErrorCode": 5

    "ErrorCode": 0404

    "ErrorCode":0404

    Error:1

    Error1

    test it yourself at regex101.com

    0 讨论(0)
提交回复
热议问题