Home > OS >  Problems writing to file inside cmdlet?
Problems writing to file inside cmdlet?

Time:01-31

I only dabble in PS so I'm probably missing something obvious, but this seems like it should work lol

I've got a filewatcher, looks for a specific file in a specific folder, when found it triggers an action. The action first writes to screen, then to logfile then triggers a follow-up script.

Writing to screen works, writing to logfile doesn't, triggering follow up script works too. I actually tried the writing to logfile a few different ways, even building a function before this part and calling it, like a Write-Log instead of Write-Host but it doesn't work either.

Is there a special means to write to log in the manner I'm trying?

$folder = 'D:\InputFiles\'
$filter = 'data.csv'
$LogFile = "D:\APIRead\logs\master.log"

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier PaymentsMKFileCreated -Action { 
$name = $Event.SourceEventArgs.Name 
$changeType = $Event.SourceEventArgs.ChangeType 
$timeStamp = $Event.TimeGenerated 
$Output = "The file '$name' was $changeType at $timeStamp"
Write-Host $Output
Out-File -FilePath $LogFile -InputObject $Output -Append**
#Invoke-Item 'D:\APIRead\scripts\process.bat'
}

CodePudding user response:

removed the ** after append and make sure you have permissions to the directory you are writing to.

Adding -Force makes it create the file if it doesn't exist.

Out-File -FilePath $LogFile -InputObject $Output -Append -Force

CodePudding user response:

$LogFile = "D:\APIRead\logs\master.log"

Try moving this line inside of your Event -Action

It could be trying to expand $LogFile, but it is not defined in the Action's scope.

  • Related