如何创建事件记录和错误记录

时间:2019-06-19 12:47:36

标签: powershell logging error-handling

Powershell的新手,没有经验,下面是一个将文件从一个位置移动到另一个位置的简单脚本,我想记录该操作以及我在某处所做的操作(例如另一个文件Logging.txt),但是还会如果脚本由于任何原因未运行,则希望错误记录日志。

搜索了StackOverflow,但找不到合适的答案

##########################################################################################################################################
 #Copies a single file from from one location to another location
 #Copy-item never delete extra files or folders in destination, but with -force it will overwrite if file already exists

#Copies the contents of COde_mapping.txt in the LNAT folder in a local location onto a test location on the I drive

[string]$sourceDirectory = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
 [string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
 Copy-item -Force -Recurse -Verbose $sourceDirectory -Destination $destinationDirectory

要针对脚本运行的每个实例将所有字段输出/附加到单个CSV / TXT中

OR

是否可以将在“开始记录”中创建的特定输出附加到CSV文件中,例如我希望将以下字段附加到csv或txt文件中。

开始时间:

用户名:

机器:

详细信息:

这些全部都存在于“开始-脚本”-“停止-脚本”中,但是每次运行脚本时,我希望结果只附加到1个txt中,而不是每次运行脚本时都包含多个txt文件。

##########################################################################################################################################
#Copies a single file from from one location to another location
#Copy-item never delete extra files or folders in destination, but with  -force it will overwrite if file already exists

#Copies the contents of COde_mapping.txt in the LNAT folder in a local location onto a test location on the I drive

$datevar = get-date -Format ("yyyyMMdd") 
$timevar = Get-date -Format ("hhmmss")
$varfullpath = "C:\Users\Simon.Evans\Documents\ReferenceData_logfile_$datevar_$timevar.txt"

Start-Transcript -Path $varfullpath

Write-Output $datevar
Write-Output $timevar
write-output $varfullpath

[string]$sourceDirectory  = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
[string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
Copy-item -Force -Recurse -Verbose $sourceDirectory -Destination $destinationDirectory

Stop-Transcript 

*************更新21/06/2019 9:22 am(UK)*************

这是我现在拥有的并且可以正常工作,但是现在我想尝试添加一个TRY CATCH并在失败的情况下显示Error事务,并成功地按以下说明进行操作,这又有可能吗,我将如何处理关于此操作

$varfullpath = "C:\Users\Simon.Evans\Documents\ReferenceData__logfile.txt" 
Start-Transcript -Path $varfullpath -Append                                                            
write-output $varfullpath
[string]$sourceDirectory  = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
[string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
Copy-item -Force  -Verbose $sourceDirectory -Destination $destinationDirectory
Stop-Transcript 

1 个答案:

答案 0 :(得分:1)

使用start-transcript小命令中的-append参数附加日志文件,而不是创建一个新文件。

相关问题