Powershell输出格式化?

时间:2017-01-26 18:05:00

标签: powershell

我有一个脚本可以扫描用户AppData文件夹中的特定文件夹。如果找到该文件夹​​,则会返回txt文件的路径。因此,我们可以看到找到它的计算机名称和用户名。

我希望能够格式化实际写入文本文件的内容,因此它会从路径中删除除计算机和用户名之外的所有内容。

脚本:

foreach($computer in $computers){
    $BetterNet = "\\$computer\c$\users\*\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm"
    Get-ChildItem $BetterNet | ForEach-Object {
        $count++
        $betternetCount++
        write-host BetterNet found on: $computer
        Add-Content "\\SERVERNAME\PowershellScans\$date\$time\BetterNet.txt" $_`n
        write-host 
    }
}

文本文件包含这样的信息

\\computer-11-1004S10\c$\users\turtle\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm

\\computer-1004-24S\c$\users\camel\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm

\\computer-1004-23S\c$\users\rabbit\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm

2 个答案:

答案 0 :(得分:2)

如果将循环拆分为两个foreach循环,一个用于计算机和用户目录,则输出用户目录的名称会更容易。

$output = foreach($computer in $computers){

    $UserDirectories = Get-ChildItem "\\$computer\c$\users\" -Directory
    foreach ($Directory in $UserDirectories) {
        $BetterNet = Get-ChildItem (Join-Path $Directory.fullname "\AppData\Local\Google\Chrome\User Data\Default\Extensions\gjknjjomckknofjidppipffbpoekiipm")
        Add-Content "\\SERVERNAME\PowershellScans\$date\$time\BetterNet.txt" "$computer $($Directory.name)`r`n" 
        write-host BetterNet found on: $computer
        $BetterNet
    }
} 
$output.count

答案 1 :(得分:2)

如果每个行都以字符串$string_containing_path的形式存在,那么很容易使用split方法进行拆分,然后添加所需的index(1)和(4):

$afterSplit = $string_containing_path.Split('\')

$stringThatYouNeed = $afterSplit[1] + " " + $afterSplit[4] 

您还可以使用修复当前日志的简单脚本:

$path_in = "C:\temp\list.txt"
$path_out= "C:\temp\output.txt"

$reader = [System.IO.File]::OpenText($path_in)


 try {

    while($true){

        $line = $reader.ReadLine()

        if ($line -eq $null) { break }

        $line_after_split_method = $line.Split('\')

        $stringToOutput = $line_after_split_method[1] + " " +    $line_after_split_method[4] + "`r`n"

        add-content $path_out $stringToOutput 
    }

    add-content $path_out "End"

}

finally {

$reader.Close()

}