0

powershell newb here. I am having some difficulty trying log my output to a file. I have tried two tactics, both of which do not work for me. The first is using the Start/Stop-Transcript cmdlet. This works great in testing on my local machine, but doesn't seem to work at all in a script that I deploy to workstations.

$path1 = Test-Path ($env:ProgramFiles + "\Sophos\Sophos Anti-Virus\SavService.exe")
$path2 = Test-Path (${env:ProgramFiles(x86)} + "\Sophos\Sophos Anti-Virus\SavService.exe")
$shareloc = '\\SERVER1\NETLOGON\SophosPackages\SophosInstall_wFW_Silent.exe'
$logpath = '\\SERVER1\NETLOGON\si_sophos_log.txt'


if (($path1 -eq $true) -or ($path2 -eq $true)) {} ELSE {
& $shareloc
Start-Transcript -Append -Path $logpath | Out-Null
Write-Output ""
Get-Date
Write-Output "Sophos has been installed on `"$env:COMPUTERNAME`""
Write-Output ""
Stop-Transcript
}

The way I would prefer to do it, is using: | Out-File -Append -FilePath $logpath I think this would be the preferred method because it would catch any error that might occur in the log, as apposed to Start-Transcript. When I try to use this method however, I get an error at the pipeline "An empty pipeline element is not allowed."

$path1 = Test-Path ($env:ProgramFiles + "\Sophos\Sophos Anti-Virus\SavService.exe")
$path2 = Test-Path (${env:ProgramFiles(x86)} + "\Sophos\Sophos Anti-Virus\SavService.exe")
$shareloc = '\\SERVER1\NETLOGON\SophosPackages\SophosInstall_wFW_Silent.exe'
$logpath = '\\SERVER1\NETLOGON\si_sophos_log.txt'


if (($path1 -eq $true) -or ($path2 -eq $true)) {} ELSE {
& $shareloc
Write-Output ""
Get-Date
Write-Output "Sophos has been installed on `"$env:COMPUTERNAME`""
Write-Output ""
} | Out-File -Append -FilePath $logpath

Thank you in advance for any assistance!

sqone2
  • 31
  • 1
  • 1
  • 5

2 Answers2

1

If you write the following :

if ($true) {Write-Output "titi"} else {Write-Output "toto"} | Out-File -Append c:\temp\titi

You will get the same error, because the if condition is not evaluated when you pipe.

You can try to force ti evaluate it

$(if ($true) {Write-Output "titi"} else {Write-Output "toto"}) | Out-File -Append c:\temp\titi
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
0

When the if condition evaluates as true, the empty scriptblock gets piped to Out-File which causes your error. i.e. the following throws the error you specified:

if($true) { } else { Write-Output "Something" } | Out-File -Append -FilePath C:\temp\myfile.txt

AHowgego
  • 592
  • 6
  • 20
  • It is giving the me the error when I add something to the $true scriptblock. Am I misunderstanding you? – sqone2 Jan 20 '14 at 23:52
  • Ah ok see @JPBlanc - if ($false) actually produces the same behaviour. I stand corrected! – AHowgego Jan 21 '14 at 09:08