PowerShell, подробный вывод в файл журнала из результатов в «Foreach» - PullRequest
0 голосов
/ 08 октября 2018

Я хочу сохранить каждый 'write-verbose' и 'write-warning' в текстовом файле / файле журнала после завершения сценария.

Я пробовал out-file в цикле и outцикла с переменной в начале, как элементы, предложенные здесь. Как вывести вывод цикла foreach в файл в PowerShell?

edit: было бы удобно также захватить выходные данные из 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 голосов
/ 08 октября 2018

Посмотрите на перенаправление.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)

0 голосов
/ 08 октября 2018

Вы можете использовать Start-Transcript в самой первой строке вашего скрипта и Stop-Transcript в конце.Все, что делает скрипт, будет автоматически записываться в файл журнала.

Start-Transcript

...