【问题标题】:Error: You must provide a value expression on the right hand side of the '-' operator错误:您必须在“-”运算符的右侧提供值表达式
【发布时间】:2015-02-15 03:12:57
【问题描述】:

你可以试试这个:

function setConfig( $file) {
    $content = Get-Content $file
    $content -remove '$content[1..14]'
    Set-Content $file     
}

我想创建一个函数,通过它我可以通过文件删除特定的行或一堆行

【问题讨论】:

  • 如果你真的问一个问题会更干净。您是在询问错误消息的含义,如何更正该错误消息,或者如何更改代码以使其执行您想要的操作?所有这些可能性都有不同的答案,并且需要您提供不同数量的上下文信息。

标签: powershell functional-programming


【解决方案1】:

我不记得 -remove 是 PowerShell 操作员,我应该认为您会遇到的错误:

表达式或语句中出现意外的标记“-remove”。

您还阻止 PowerShell 在单引号中扩展代码,因此它被视为文字字符串“$content[1..14]”。

我冒昧地假设您正在尝试从文件中删除前 14 行代码,同时保留第一个是?

我使用以下代码创建了一个包含 30 行的测试文件。

1..30 | Set-Content C:\temp\30lines.txt

然后我们使用你的函数的这个更新版本

function setConfig($file){
    $content = Get-Content $file
    $content | Select-Object -Index (,0 + (14..$($content.Count))) | Set-Content $file     
}

使用Select-Object-Index 我们得到第一行,0,然后在第14 行(14..$($content.Count))) 之后添加剩余的行。 0 中的 from 中需要逗号,因为我们将两个数字数组组合在一起。更新后的文件内容如下所示。更改 -Index 值以满足您的需要。

1
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多