Tehc
Tehc

Reputation: 689

Get-ChildItem RuntimeException: Cannot index into null array

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

Get-ChildItem -Filter '*.txt' | ForEach-Object {
    $content = Get-Content $_
    $content[7] = '    rel_nr    constant "{0}"' -f $releasenr
    $content | Set-Content -Path $_.FullName
}

The script works fine if the files are in the same folder as the script, but as soon as I try to implement

Get-ChildItem -Path C:\sample -Filter '*.txt' | ForEach-Object {

The script returns a RuntimeException:

Cannot index into a null array.
In C:\Users\mosermich\Desktop\Import-Daten-Uploader\Uploader.ps1:158 Char:9
+         $content[7] = '    rel_nr    constant "{0}"' -f $releasenr
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

What am I doing wrong?

Upvotes: 1

Views: 662

Answers (1)

Harald F.
Harald F.

Reputation: 4793

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.

Upvotes: 2

Related Questions