Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 如果行包含字符串,则向同一行添加内容_Powershell - Fatal编程技术网

Powershell 如果行包含字符串,则向同一行添加内容

Powershell 如果行包含字符串,则向同一行添加内容,powershell,Powershell,假设我有$file,$key用于匹配,还有$string要添加。 如果$file中有一行包含$key,请将$string添加到该行的末尾。 例如: $key=“b”,$string=“z” $file包含: a b c a b z c 新的$file包含: a b c a b z c 如何在PowerShell中以最简单的方式执行此操作? 注意$file是一个实际的文件,而不是程序中的某个数组您可能需要迭代每一行并检查该行是否包含键: $newContent = Get-Content

假设我有
$file
$key
用于匹配,还有
$string
要添加。 如果
$file
中有一行包含
$key
,请将
$string
添加到该行的末尾。 例如:
$key=“b”
$string=“z”

$file
包含:

a
b
c
a
b z
c
新的
$file
包含:

a
b
c
a
b z
c
如何在PowerShell中以最简单的方式执行此操作?
注意
$file
是一个实际的文件,而不是程序中的某个数组

您可能需要迭代每一行并检查该行是否包含键:

$newContent = Get-Content $file | Foreach {
    if ($_ -like "*$key*")
    {
        "$_ $string"
    }
    else
    {
        $_
    }
} 
$newContent | Set-Content $file

您可能需要遍历每一行,并检查该行是否包含键:

$newContent = Get-Content $file | Foreach {
    if ($_ -like "*$key*")
    {
        "$_ $string"
    }
    else
    {
        $_
    }
} 
$newContent | Set-Content $file

好的,如果
$file
包含以下内容:
a b c d e f
我想在包含
$key=“b”
的行的末尾添加“z”,如果
$file
包含以下内容:
a b c d e f
我想在包含
$key=“b”
Thx的行的末尾添加“z”,如您所说,使用“输出文件…”和“设置内容…”之间有什么区别?没有什么区别您可以使用两种解决方案;)Thx,如您所说,使用“输出文件…”和“设置内容…”之间有什么区别?没有什么区别您可以使用两种解决方案;)