Helped needed in For loop

Hi, all.

Apologies if this is a newbie issue, I have been working with PS for some time to perform basic tasks like starting/stopping servers, etc and recently I started to learn how to leverage PS to perform build and deploy tasks in Azure DevOps.

I have been trying to wire up some webtests (397!!!) in an Azure DevOps pipeline and I can’t seem to get past an annoying issue. Here’s my script:

[CmdletBinding()]
param ( 
$tool = "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\MSTest.exe", 
$path, 
$include = "*.webtest", 
$results, 
$testsettings)

$rootFolders = Get-ChildItem -Path $path -Directory
Write-Host "Root folders: $rootFolders"
foreach($directory in $rootFolders)
{
    $web_tests = Get-ChildItem -Path $directory -Recurse -Include $include
    foreach ($item in $web_tests)
    {
        $args += "/TestContainer:$item "
    }

    Write-Host "Command: $args"

    $resultsFile = $results.Replace(".trx", ($directory.ToString() + ".trx"))
    Write-Host "ResultsFile: $resultsFile"

    & $tool $args /resultsfile:$resultsFile /testsettings:$testsettings
}

The problem I’m having is in resetting the ‘$args’ variable. I tried using ‘Clear-Variable’ after the invoke (&) command but it fails in the next iteration as it seems to loose the ‘$tool’ variable value.

What is the correct way to reset the ‘$args’ variable?

 

Cheers

 

$args in an automatic variable and should not be used like normal user defined variables. Change it to $Arguments or some other name.
See more about automatic variables
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-6

Have you tried setting $args = “” at the start of the first foreach?

E.g.

[pre]
foreach($directory in $rootFolders)
{
$args = “”

$web_tests = Get-ChildItem -Path $directory -Recurse -Include $include
foreach ($item in $web_tests)
{
    $args += "/TestContainer:$item "
}

Write-Host "Command: $args"

$resultsFile = $results.Replace(".trx", ($directory.ToString() + ".trx"))
Write-Host "ResultsFile: $resultsFile"

& $tool $args /resultsfile:$resultsFile /testsettings:$testsettings

}
[/pre]

That should clear the args variable before it’s used again.

plus what kvprasoon said :slight_smile: