Search code examples
powershellpowershell-4.0bcp

Powershell - Output to screen AND logfile


I am trying to write ALL the output to a logfile, and I seem to be doing something wrong. I also need the output on the screen.

Here is what I have so far:

#  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
    }
}

When I want to write out the command to the logfile so I know which table is processed, I get an error: Here is the code:

#  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
    }
}

And the error:

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

I am obviously not very good with Powershell and I please need your advise on how I should code this the best possible way. Maybe the above way is completely wrong, I do appreciate your guidance.

Thank you


Solution

  • Try modifying your code to something like this:

    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
        }
    }