【问题标题】:Powershell - Output to screen AND logfilePowershell - 输出到屏幕和日志文件
【发布时间】: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


【解决方案1】:

尝试将您的代码修改为以下内容:

foreach($line in Get-Content .\Alltables.txt) {
    if($line -match $regex) {
        $bcp_command = "bcp $database" + '.' + $schema '.' + $line + ' out ' + $line + '.dat -T -c')
        Tee-Object -FilePath $LogFile -InputObject $bcp_command -Append
        $bcp_results = Invoke-Expression $bcp_command
        Tee-Object -FilePath $LogFile -InputObject $bcp_results -Append
    }
}

【讨论】:

  • 是的,非常好。谢谢你。我更新了答案以反映您的建议。
猜你喜欢
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 2013-12-10
  • 2022-11-22
  • 2011-09-02
  • 1970-01-01
  • 2015-04-12
  • 2020-11-06
相关资源
最近更新 更多