Start-Process does not parse argumentlist

1k views Asked by At

I have created a PowerShell script, but for some reason the "Start-Process"-cmdlet does not seem to be behaving correctly. Here is my code:

[string]$ListOfProjectFiles = "project_file*."
[string]$arg   = "project_file"
[string]$log   = "C:\Work\output.log"
[string]$error = "C:\Work\error.log"

Get-ChildItem $PSScriptRoot -filter $ListOfProjectFiles | `
    ForEach-Object {
        [string]$OldFileName = $_.Name
        [string]$Identifier = ($_.Name).Substring(($_.Name).LastIndexOf("_") + 1)

        Rename-Item $PSScriptRoot\$_ -NewName "project_file"

        Start-Process "$PSScriptRoot\MyExecutable.exe" ` #This line causes my headaches.
                        -ArgumentList $arg `
                        -RedirectStandardError $error `
                        -RedirectStandardOutput $log `
                        -Wait
        Remove-Item "C:\Work\output.log", "C:\Work\error.log"

        Rename-Item "$PSScriptRoot\project_file" -NewName $OldFileName
        }

The main issue is, is that on my machine the program runs, but only after I added the -Wait switch. I found out that if I stepped through my code in the PowerShell-ISE, MyExecutable.exe did recognise the argument and ran the program properly, while if I just ran the script without breakpoints, it would error as if it could not parse the $arg value. Adding the -Wait switch seemed to solve the problem on my machine.

On the machine of my colleague, MyExecutable.exe does not recognise the output of the -ArgumentList $arg part: it just quits with an error stating that the required argument (which should be "project_file") could not be found.

I have tried to hard-code the "project_file" part, but that is no success. I have also been playing around with the other switches for the Start-Process-cmdlet, but nothing works. I am a bit at a loss, quite new to PowerShell, but totally confused why it behaves differently on different computers.

What am I doing wrong?

1

There are 1 answers

0
user4003407 On

If you does not use -Wait switch, then your script continue to run while MyExecutable.exe still executing. In particular you can rename file back (Rename-Item "$PSScriptRoot\project_file" -NewName $OldFileName) before you program open it.

You pass plain project_file as argument to your program. What if current working directory is not a $PSScriptRoot? Does MyExecutable.exe designed to look for files in the exe location directory in addition to/instead of current working directory? I recommend to supply full path instead:

[string]$arg   = "`"$PSScriptRoot\project_file`""

Do not just convert FileInfo or DirectoryInfo objects to string. It does not guaranteed to return full path or just file name. Explicitly ask for Name or FullName property value, depending of what you want.

Rename-Item $_.FullName -NewName "project_file"