Индекс массива оценивается как ноль - Найти номер белья и использовать его в качестве номера индекса - PullRequest
0 голосов
/ 14 апреля 2019

Мой входной файл выглядит так:

#EXTM3U
#EXTI NF:-1 tvg-name="Das Erste HD" tvg-id="ARD.de" group-title="Vollprogramm" tvg-logo="https://raw.githubusercontent.com/jnk22/kodinerds-iptv/master/logos/tv/daserstehd.png",Das Erste HD
https://daserstehdde-lh.akamaihd.net/i/daserstehd_de@625196/index_2739_av-p.m3u8
#EXTINF:-1 tvg-name="Das Erste" tvg-id="ARD.de" group-title="Vollprogramm" tvg-logo="https://raw.githubusercontent.com/jnk22/kodinerds-iptv/master/logos/tv/daserste.png",Das Erste
https://daserstelive-lh.akamaihd.net/i/daserste_de@28289/index_3776_av-p.m3u8
..

Я хочу заменить поток моей переменной $newRtsp и записать его обратно в файл. Что у меня сейчас есть:

# Getting the file
$inFile = Get-Content "iptv.m3u"

# Linenumber where a specific channel name $chanName exists
$line = ($inFile | Select-String "tvg-name=`"$chanName`"").LineNumber                                                                                          #`# dummy comment to fix code highlighting for SO

# Use actual Linenumber as Index, to override the following line
$inFile[$line] = $newRtsp

# Write back to file
$inFile | Set-Content "iptv.m3u"

Проблема: Почему-то я не могу использовать найденное белье в качестве индекса:

Index operation failed; the array index evaluated to null.
At E:\merge-fritzbox.ps1:17 char:5
+     $inFile[$line] = $newRtsp
+     ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArrayIndex

1 Ответ

1 голос
/ 14 апреля 2019

Номер строки, возвращаемый Select-String начинает отсчет с 1.Индексы массива отсчитываются от 0, поэтому вы должны учитывать это.

Это должно работать:

$chanName = "Das Erste HD"
$newRtsp  = "the new content for the line"

# Getting the file
$inFile = Get-Content "iptv.m3u"

# Linenumber where a specific channel name $chanName perhaps exists?
# SimpleMatch is an optional parameter and specifies that 
# the string in the pattern is not interpreted as a regular expression.
$line = ($inFile | Select-String "tvg-name=`"$chanName`"" -SimpleMatch).LineNumber               #`# dummy comment to fix code highlighting for SO

# $line will be $null if Select-String did not find the string to look for
if ($line) {
    # Use actual Linenumber minus 1 as Index, to override the following line
    $inFile[$line - 1] = $newRtsp

    # Write back to file
    $inFile | Set-Content "iptv.m3u"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...