Powershell - output to screen AND logfile

I am trying to write ALL the output to a log file and I seem to be doing something wrong. I also need screen output.

Here's 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 a command to a log file so that I know which table is being 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 at Powershell and please ask me for advice on how I should best sign this. Perhaps the above is completely wrong, I appreciate your guidance.

thank

+3


source to share


1 answer


Try changing your code 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
    }
}

      

+4


source







All Articles