Powershell write output to local log with invoke-command

David Smith 21 Reputation points
2021-11-23T14:42:39.133+00:00

I have the following script, consisting two functions and some log writing.

All works well, with exception of the catch in the invoke-command, that will write a failure log but only to $failpath remote machine, which isnt really useful

function Get-TimeStamp {

return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)

}

$shareHD = {
$mydate=get-date

write-host "date is $mydate"

$goodDate=Get-Date -format "dd/MM/yyyy"

generate share name as a hidden

$share =$using:mySam+"$"
$shareperm=$using:mySam
$path=$using:PhysHD
$path="e:\swhome\swmcphersont1"
$remoteserver="rchome"

Write-Host "debug we are going to share $path as $share"

Create Share

IF (!(Get-SmbShare -Name $share -ErrorAction SilentlyContinue)) {
write-host "Creating share: " $share "`n" -ForegroundColor magenta


    try
    {
    #New-SmbShare –Name $share –Path $path –Description $share' home directory created '$mydate –FullAccess 'Domain Users' -ErrorAction stop
    New-SmbShare –Name $share –Path $path –Description $share' home directory created '$mydate –FullAccess $shareperm -ErrorAction stop
    write-host "The share  $share created successfully`n" -ForegroundColor green
    }
    catch
    {
   write-host "failed creating share on $remoteserver, try running creatADshare.ps1" -ForegroundColor red
  # write-host "failed creating share on $remoteserver, try running creatADshare.ps1" -ForegroundColor red
  #write this to the local path
  write-host "fail log path is $using:failpath"
   write-Output "$using:exectime Unable to create $share on $remoteserver" | Out-file $using:failpath -append
    }


} else {
write-host "The share already exists: " $share "`n" -ForegroundColor Yellow
}

}

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

set up logging

$currentscript=$MyInvocation.MyCommand

$logpath="$scriptpath\logs\ADsharerRun.log"
$failpath="$scriptpath\logs\fail.log"

$mySam="swmcphersont1"
$physHD="e:\swhome\swmcphersont1"

Write-Host "$(Get-TimeStamp) run log is $logpath"

Write-Host "fail log is $failpath"

Write-Output "$(Get-TimeStamp) started $currentscript" | Out-file $logpath -append

share it if necessary

make my timestamp

$exectime=$(Get-TimeStamp)

write-host "stamp is $exectime"

Invoke-Command -ComputerName VMSG-FSRCHOME -scriptblock $shareHD

Write-Output "$(Get-TimeStamp) completed $currentscript" | Out-file $logpath -append

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,389 questions
{count} votes

Accepted answer
  1. Rich Matheisen 45,096 Reputation points
    2021-11-23T15:44:21.017+00:00

    The best way to deal with this is to not write to the error log in the Invoke-Command's script block.

    In the "catch" block, just emit the variable "$<underbar>" (i.e. the error object) instead of using Write-Output. Check the object type of the object(s) returned by the Invoke-Command and, if it's an error object, do the recording of the error on the local machine.

    If you want a customized error then can use "Throw 'Unable to blah, blah, blah'" instead of returning the original error object.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. David Smith 21 Reputation points
    2021-11-23T17:02:33.64+00:00

    Thanks Rich, I used your logic to do the following

    in the catch, I used
    return "$using:exectime Unable to create $share on $remoteserver"

    and in the call for the invoke-command I used, so can grab the result whatever it is and bung it into my fail log

    $results=Invoke-Command -ComputerName VMSG-FSRCHOME -scriptblock $shareHD

    write-output $results | Out-file $failpath -append

    A result good enough for Govt business, or in this case local Govt

    0 comments No comments

  2. Limitless Technology 39,391 Reputation points
    2021-11-26T08:37:25.393+00:00

    Hi there,

    Additionally Invoke-Command returns all command output, so you could use Write-Output instead of Write-Host and pipe the returned output into a file. You could, write 'Info', 'Warn' and 'Error' level messages to the correct streams using Write-Output, Write-Warning and Write-Error. Also, you may want to suppress output to the required file.


    --If the reply is helpful, please Upvote and Accept it as an answer-

    0 comments No comments