【发布时间】:2017-06-30 15:31:37
【问题描述】:
我正在尝试将所有输出写入日志文件,但我似乎做错了什么。我还需要屏幕上的输出。
这是我目前所拥有的:
# Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
# Log file name:
$LogFile = "EXPORTLOG_"+$LogTime+".log"
$database = "DB"
$schema = "dbo"
$table = "TableName"
foreach($line in Get-Content .\Alltables.txt) {
if($line -match $regex){
$bcp = "bcp $($database).$($schema).$($line) out $line.dat -T -c"
Invoke-Expression $bcp | Out-File $LogFile -Append -Force
}
}
当我想将命令写入日志文件以便知道处理了哪个表时,我收到错误消息: 代码如下:
# Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
# Log file name:
$LogFile = "EXPORTLOG_"+$LogTime+".log"
$database = "DB"
$schema = "dbo"
$table = "TableName"
foreach($line in Get-Content .\Alltables.txt) {
if($line -match $regex){
$bcp = "bcp $($database).$($schema).$($line) out $line.dat -T -c" | Out-File $LogFile -Append -Force
Invoke-Expression $bcp | Out-File $LogFile -Append -Force
}
}
还有错误:
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is null.
At C:\Temp\AFLAC\export.ps1:16 char:21
+ Invoke-Expression $bcp | Out-File $LogFile -Append -Force
+ ~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
我显然不太擅长使用 Powershell,我需要您就如何以最佳方式编写代码提出建议。 可能上面的方法是完全错误的,非常感谢您的指导。
谢谢
【问题讨论】:
-
在您添加管道和 Out-File cmdlet 后,您的 $bcp 变量不再被分配任何值。制作这两个单独的命令。一个分配值,就像在第一个示例中一样,然后将 $bcp 作为单独的命令传递给 Out-File: $bcp |文件外...
-
你可以看看
Tee-Object。
标签: powershell powershell-4.0 bcp