P. Grunder P. Grunder - 1 year ago 261
PowerShell Question

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?

Answer Source

Try replacing the

$content = Get-Content $_


$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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download