PowerShell 详细参数
PowerShell Verbose-Parameter
我有几个关于详细参数的问题。
示例脚本:
try {
New-Item -Path "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose
}
catch {
Write-Host $Error[0]
}
输出:
VERBOSE: Execute the "Create file" operation for the target "Target: C:\Test.txt".
Access to the path "C: \ Test.txt" was denied.
如何将详细消息保存在变量中?
是否可以在将 PowerShell 自动生成的详细消息保存到日志文件之前对其进行编辑(添加日期和时间)?
示例脚本(无效):
try {
New-Item -Path "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose *> $LogFile
}
catch {
Write-Host $Error[0]
}
是否有更好的建议来编写 "success" 日志文件,而不是使用参数 verbose 且无需手动编写?
谢谢!
如果将 Verbose
流合并到标准输出流 (4>&1
),则可以将详细输出分配给变量:
$output = New-Item "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose 4>&1
由于 New-Item
也是 returns 新创建的文件,您需要再次将输出拆分为详细与正常:
$verboseOutput,$normalOutput = $output.Where({$_ -is [System.Management.Automation.VerboseRecord]}, 'Split')
现在您可以在 $verboseOutput
中的记录前添加时间戳,然后再将它们写入磁盘
我有几个关于详细参数的问题。 示例脚本:
try {
New-Item -Path "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose
}
catch {
Write-Host $Error[0]
}
输出:
VERBOSE: Execute the "Create file" operation for the target "Target: C:\Test.txt".
Access to the path "C: \ Test.txt" was denied.
如何将详细消息保存在变量中?
是否可以在将 PowerShell 自动生成的详细消息保存到日志文件之前对其进行编辑(添加日期和时间)? 示例脚本(无效):
try {
New-Item -Path "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose *> $LogFile
}
catch {
Write-Host $Error[0]
}
是否有更好的建议来编写 "success" 日志文件,而不是使用参数 verbose 且无需手动编写?
谢谢!
如果将 Verbose
流合并到标准输出流 (4>&1
),则可以将详细输出分配给变量:
$output = New-Item "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose 4>&1
由于 New-Item
也是 returns 新创建的文件,您需要再次将输出拆分为详细与正常:
$verboseOutput,$normalOutput = $output.Where({$_ -is [System.Management.Automation.VerboseRecord]}, 'Split')
现在您可以在 $verboseOutput
中的记录前添加时间戳,然后再将它们写入磁盘