Powershell 在Foreach对象外部使用var

Powershell 在Foreach对象外部使用var,powershell,variables,for-loop,Powershell,Variables,For Loop,我有这样一个代码,它可以正常工作: Get-Content $path\$newName -Encoding OEM |ForEach-Object {$_ -replace '<Num:(\d{8,20})>$','$1'}| Set-Content $path\$txtName -Encoding UTF8 比如说。但如果我这样做,没有什么是输出。 有什么建议吗 谢谢。一种方法是将$1分配给这样的数组- $array = @() Get-Content $path\$newNa

我有这样一个代码,它可以正常工作:

Get-Content $path\$newName -Encoding OEM |ForEach-Object {$_ -replace '<Num:(\d{8,20})>$','$1'}| Set-Content $path\$txtName -Encoding UTF8
比如说。但如果我这样做,没有什么是输出。 有什么建议吗


谢谢。

一种方法是将
$1
分配给这样的数组-

$array = @()
Get-Content $path\$newName -Encoding OEM | ForEach-Object {$_ -replace '<Num:(\d{8,20})>$','$1'; $array += $1 } | Set-Content $path\$txtName -Encoding UTF8
$array=@()
获取内容$path\$newName-编码OEM | ForEach对象{$\$u-替换'$','$1';$array+=$1}|设置内容$path\$txtName-编码UTF8
您可以使用
$1
的值,如
$array[0]
$array[1]
$array[2]
。。等等。

基于s脚本

$infle='.\test.txt'
$OutFile='.\test2.txt'
$RegEx=“$”
$array=@()
获取内容$infle-编码OEM | ForEach对象{
如果($\匹配$RegEx){$array+=$matches[1]}
$\替换$RegEx,“`1”
}|设置内容$OutFile-编码UTF8
$array

gc.\test.txt >.\SO_50579315.ps1 1234567890 23456789101112 >gc.\test2.txt 1234567890 23456789101112
谢谢。t这说明:无法验证参数“To”上的参数。参数为null或为空。请提供一个不为null或空的参数,然后重试该命令。如果我写入主机$array[0],则不会打印任何内容。这主意不错,但是
$1
捕获组仅在替换中有效。
$matches
集合更持久。@LotPings-这是真的。
$matches
将更有效地捕获正则表达式。再次感谢你的精彩提示。这很有效,谢谢。但在$array中似乎有一个换行符。类似于:$array+'rrr'这是可以预防的吗?这实际上是有效的:$faxnr=`$array=$array-replace“
n”,但给出了一个错误:
:术语“
”不能识别为cmdlet、函数、脚本文件或可操作程序的名称。请检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。在C:\FaxOut\fax.ps1:31 char:18+$faxnr=`$array=$array-replace“
n”,“`+~~+CategoryInfo:ObjectNotFound:(`:String)[],CommandNotFoundException+FullyQualifiedErrorId:CommandNotFoundException我不确定是否使用单引号
或双引号
。backtick
`
用于转义字符串中的行尾或特殊字符。上面的正则表达式应该只替换/匹配数字。我通过这样做解决了这个问题:$faxnr=$array[0]。现在效果很好。谢谢
$array = @()
Get-Content $path\$newName -Encoding OEM | ForEach-Object {$_ -replace '<Num:(\d{8,20})>$','$1'; $array += $1 } | Set-Content $path\$txtName -Encoding UTF8
$InFile = '.\test.txt'
$OutFile= '.\test2.txt'
$RegEx = "<Num:(\d{8,20})>$"
$array = @()
Get-Content $InFile -Encoding OEM | ForEach-Object {
    if ($_ -match $RegEx ){$array += $matches[1]}
        $_ -replace $RegEx,"`$1"
} | Set-Content $OutFile -Encoding UTF8
$array
> gc .\test.txt
<Num:1234567890>
<Num:23456789101112>

> .\SO_50579315.ps1
1234567890
23456789101112

> gc .\test2.txt
1234567890
23456789101112