Powershell - 替换对象

时间:2021-03-16 22:32:08

标签: powershell regexp-replace

我有一个 powershell 对象/变量,如下所示:

enter image description here

对于这些“行”中的每一行,我想用新字符串替换第一个数字/字母字符串,即正则表达式 ForEach-Object( { ($_ -replace '^.+',"") })

但这似乎不起作用 - 我做错了什么??

更新 1:

特别是 var 中的 LINE 项:

$copypaths | Get-Member



   TypeName: Microsoft.PowerShell.Commands.MatchInfo

Name         MemberType Definition
----         ---------- ----------
Equals       Method     bool Equals(System.Object obj)
GetHashCode  Method     int GetHashCode()
GetType      Method     type GetType()
RelativePath Method     string RelativePath(string directory)
ToString     Method     string ToString(), string ToString(string directory)
Context      Property   Microsoft.PowerShell.Commands.MatchInfoContext Context {get;set;}
Filename     Property   string Filename {get;}
IgnoreCase   Property   bool IgnoreCase {get;set;}
Line         Property   string Line {get;set;}
LineNumber   Property   int LineNumber {get;set;}
Matches      Property   System.Text.RegularExpressions.Match[] Matches {get;set;}
Path         Property   string Path {get;set;}
Pattern      Property   string Pattern {get;set;}

这是我要操作的行字符串,所以我的代码可能需要 $_.Line?

enter image description here

1 个答案:

答案 0 :(得分:0)

这样做就行了:

    foreach ($path in $copypath){
        $path.list = ($path.list).replace("old string", "New string")
    }

如果您不确定旧字符串将是什么,但您知道它的长度或其他特征,您可以对其执行任意数量的操作,而不仅仅是替换。

相关问题