首页 > 解决方案 > PowerShell,从“Foreach”中的结果到日志文件的详细输出

问题描述

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

我已经在循环内尝试了 out-file 并在开始时使用 var 退出循环,就像这里建议的项目一样。如何将 foreach 循环输出转储到 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

标签: powershellforeachoutputverbose

解决方案


看看重定向。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)


推荐阅读