how to wait the process has been done before executing the next task

hi, all,

I am very new on the PowerShell, but about 20 years s/w development experience mostly with .Net, and variety other lang including Javascript(Typescript), and little bit of Python or PERL. I am recently working as IT admin task.

I have written the Powershell script(say, DownloadReplaceCharsCopy.ps1) which execute the PERL script with the following pesudo code, and all works each block of command, but when I execute DownloadReplaceCharsCopy.ps1 using the Window Task Schedule, the replacing Character part does not do its job.

---- Code (simplified) DownloadReplaceCharsCopy.ps1---

# Step 1. Find and set the input parameters for PERL script to download file from the remote server (omit some logic)

$localFilename = 'c:\wf\localfile.txt'

$remoteFilename = 'remotefile.txt'

# Step 2. Execute PERL script which takes the local file name to store, and the remote file name to download

perl.exe  c:\wf\  $remoteFilename   $localFilename

# Step 3. Replace the Hex (1C) to Window CarriageReturn and LineFeed on the downloaded file

$ModifiedFileName = $localFilename + "_" + $timestamp + ".txt"

Get-Content $localFilename | Foreach-Object {$_ -replace "\x1c", "`r`n"} | set-content $ModifiedFileName -Force

# Step 4. Copy to the backup folder the original file download and to move the final file to the destination folder (simplify the filename)

Copy-Item -Path $localFilename-Destination  'c:\destination\backup.txt'

Move-Item -Path $ModifiedFileName -Destination 'c:\destination\target.txt'

*** Questions is below

The step 3 to replace character does not work when it executes via Window Task Scheduler, which mean no replacement.

But when execute one command by one command, all works fine.

Appreciate any help/comment to resolve this in advance.

from Moon 1

is it ‘\x1C’ or just ‘1C’ for replace. Can you try $_ -replace “1c”, “`r`n”

Thank you for your feedback.

Though, it is \x1c since it is hex. and that line itself (Get-Content $localFilename | Foreach-Object {$_ -replace “\x1c”, “`r`n”} | set-content $ModifiedFileName -Force) works as I expected when it is executed that line only.

However, it takes a quite of time depending on the size of file to loop through, and does not work ‘Replacing character’ when it runs through Window Task Schedule in a way the original input file is save to $modifiedFileName…


This could be a permissions issue. In Windows Task Scheduler, is it your own user account that is set to execute the script, or is it a system or general user account? Does the WTS account have permission to execute your script, and does it have access to the necessary directories? (e.g. c:\wf)

You say that when you execute the commands one by one everything works fine, but not when the script is executed by WTS. What happens when you execute the whole script manually? does it still perform as expected? What happens if a different user executes the script?