PowerShell,详细输出到“ Foreach”结果中的日志文件

时间:2018-10-08 02:05:19

标签: powershell foreach output verbose

我想在脚本完成后将每个“详细写入”和“写入警告”保存到文本/日志文件中。

我在循环内尝试了文件外循环,并在循环开始时尝试了var,就像这里建议的项目一样。 How to dump the foreach loop output into a file in PowerShell?

编辑:从Measure-Command捕获输出也很方便。

但这不适用于我的脚本。 任何帮助将不胜感激。

#initialisation
CLS
$ErrorActionPreference = 'Stop'
$VerbosePreference = "continue"

#Settings
$SubFolder = ".\_Orphan"
$FileListFile = ".\DirtoMove.csv"



#Retrieve List with folders to move from current folder.
Try { [Array]$FilesToMove = Get-Content $FileListFile }
Catch {Write-Warning "could not load $($FileListFile)"; Start-Sleep -S 3 ; Exit}

#If subfolder does not exist then create it.
If (!(Test-Path $SubFolder)) {
    Try { New-Item $SubFolder -ItemType Directory | Out-Null}
    Catch {Write-Warning "Could not create subfolder $($SubFolder)"; Start-Sleep -S 3 ; Exit}
}
Measure-Command{
#Try to moving the folders from the list to the the specified subfolder.
Foreach ($File in $FilesToMove) {



    #If folder does not exist then skip.
    If (!(Test-Path $File)) {
        Write-Verbose "File $($File) Does not exist, skipping"; 
        Continue
    }

    # Check if folder already exist in the sub folder.
    If (Test-Path (Join-Path -Path $SubFolder -ChildPath $File)){
        Write-Verbose "File $($File) exists already in the subfolder, skipping";
        Continue    
    }


    #try moving the folder.
    Try {
        $File | Move-Item -Destination $SubFolder;
        Write-Verbose "File $($File) succesfully moved." ;
    }
    Catch {Write-Warning "Could not move file $($File), Skipping" ; Continue}        
}

}

Write-Verbose "Script finished, waiting for 5 seconds before closing."

Start-Sleep  -Seconds 5

2 个答案:

答案 0 :(得分:0)

您可以在脚本的第一行使用Start-Transcript,并在末尾使用Stop-Transcript。该脚本所做的全部操作都会自动记录在日志文件中。

Start-Transcript

答案 1 :(得分:0)

看看重定向。 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-6

在这种情况下,适用于此的示例3。

运行脚本时,请按以下方式调用它:

./Script.ps1 3>&1 4>&1 > C:\result.log

这会将警告流(3>&1)和详细流(4>&1)重定向到成功流,然后将其重定向到文件(> C:\ result.log)