powershell - 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
解决方案
在这种情况下,示例 3 将适用于此。
运行脚本时,这样调用它:
./Script.ps1 3>&1 4>&1 > C:\result.log
这会将警告流 (3>&1) 和详细流 (4>&1) 重定向到成功流,然后将其重定向到文件 (> C:\result.log)
推荐阅读
- java - 在android studio中使用kotlin从字符串中获取文本
- vb.net - 与 PowerShell 相比,进程运行速度非常慢
- c# - 评估函数“System.Diagnostics.TraceInternal.Listeners.get”超时,需要以不安全的方式中止
- azure - 如何在 Azure 静态 Web 应用程序的 API(Azure 函数)中获取当前用户的角色
- javascript - 带有角度的打字稿通用http服务
- javascript - 如何删除旧表格以停止重复提交
- javascript - 如何重置单击 href 时处于活动状态的切换?
- elasticsearch - Logstash - 将使用 Grok 过滤的字段拆分为更多字段
- c - 将值打印到控制台,避免使用标准库
- dart - 每当我使用 Dartdoc 时,它都会引发错误