Get-ChildItem RuntimeException: Cannot index into null array

后端 未结 1 1073
陌清茗
陌清茗 2021-01-23 15:05

I\'m trying to replace a line in several files and multiple folders with a PowerShell script:

Get-ChildItem -Filter \'*.txt\' | ForEach-Object {
    $content = G         


        
相关标签:
1条回答
  • 2021-01-23 15:39

    Try replacing the

    $content = Get-Content $_
    

    with

    $content = Get-Content $_.FullName
    

    When you're running in a different location, Get-Content using only the $_ will resolve to the filename and not the full path, hence it cannot find the file it's trying to fetch the content from. Using FullName will give it the full path instead. The reason why it worked when the files were in the same folder was because it would search from the working directory.

    I would also consider safeguarding your statement to make sure it has more than 8 lines, just to avoid potential errors as for a good practice.

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