我获取内容并从目录中的多个文件中选择字符串 所以我为文件夹中的每个文件都得到这样的行,我得到了主机和用户的行,然后是下一个文件。
Host: blah.blah
OS: "Windows 7"
"Windows User","bc","btfr1","Internal user for"
"Windows User","bc3","btfr2","user for"
"Windows User","bc8","btfr3","user"
"Windows User","bc2","btfr4","something"
Host: bleh.bleh
OS: "Windows 8.1"
"Windows User","cb5","frtb5","External user for"
"Windows User","cb2","frtb2","user"
"Windows User","cb6","frtb1","add files for"
我想要下一个这样的表格:
"blah.blah","Windows 7","Windows User","bc","btfr1","Internal user for"
"blah.blah","Windows 7","Windows User","bc3","btfr2","user for"
"blah.blah","Windows 7","Windows User","bc8","btfr3","user"
"blah.blah","Windows 7","Windows User","bc2","btfr4","something"
"bleh.bleh","Windows 8.1","Windows User","cb5","frtb5","External user for"
"bleh.bleh","Windows 8.1","Windows User","cb2","frtb2","user"
"bleh.bleh","Windows 8.1","Windows User","cb6","frtb1","add files for"
或:
"Windows 7","blah.blah","Windows User","bc","btfr1","Internal user for"
"Windows 7","blah.blah","Windows User","bc3","btfr2","user for"
"Windows 7","blah.blah","Windows User","bc8","btfr3","user"
"Windows 7","blah.blah","Windows User","bc2","btfr4","something"
"Windows 8.1","bleh.bleh","Windows User","cb5","frtb5","External user for"
"Windows 8.1","bleh.bleh","Windows User","cb2","frtb2","user"
"Windows 8.1","bleh.bleh","Windows User","cb6","frtb1","add files for"
代码如下。
Set-Location c:/mine
Get-Content *.csv `
| Select-String -pattern 'OS|Host|"Windows User"'| Set-Content results.csv
$text = Get-Content results.csv
$OutData = foreach ($str in $text) {
if ($str -match '^Host:\s.*$') {
# get prefix
$prefix = $str -replace '^Host:\s?(.*)$','$1'
}
elseif ([string]::IsNullOrEmpty($str)) {
# Do not touch empty strings!
}
else {
# generate out string with matched prefix
$outString = "`"$prefix`",$str"
Write-Output $outString
}
}
$OutData | Out-File results.csv -Force -Encoding utf8
我想在工作之后再获得一个“if”,但是这个表还有一行总是根据主机名改变,所以我不能把它作为字符串。
答案 0 :(得分:1)
这样的事情:
$text = Get-Content *.csv
$OutData = foreach ($str in $text) {
if ($str -match '^Host:\s.*$') {
# get prefix
$prefix = $str -replace '^Host:\s?(.*)$','$1'
}
elseif ([string]::IsNullOrEmpty($str)) {
# Do not touch empty strings!
}
else {
# generate out string with matched prefix
$outString = "`"$prefix`",$str"
Write-Output $outString
}
}
$OutData | Out-File results.csv -Force -Encoding utf8
答案 1 :(得分:0)
最后完成它,foreach中的代码必须更改为:
foreach ($str in $text) {
if ($str -match '^Host:\s.*$') {
# get prefix
$prefix = $str -replace '^Host:\s?(.*)$','$1'
}
elseif ($str -match '^OS:\s.*$') {
# get prefix2
$prefix2 = $str -replace '^OS:\s?(.*)$','$1'
}
elseif ([string]::IsNullOrEmpty($str)) {
# Do not touch empty strings!
}
else {
# generate out string with matched prefix
$outString = "$prefix2`"$prefix`",$str"
Write-Output $outString
}
}