Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top