One way to achieve this would be to write an "outer" script that passes the directory-to-be-cleaned, into the "inner" script, as a parameter.
For your "outer" script, have something like this:
$DirectoryList = Get-Content -Path $PSScriptRoot\DirList;
foreach ($Directory in $DirectoryList) {
Start-Process -FilePath powershell.exe -ArgumentList ('"{0}\InnerScript.ps1" -Path "{1}"' -f $PSScriptRoot, $Directory);
}
Note: Using Start-Process
kicks off a new process that is, by default, asynchronous. If you use the -Wait
parameter, then the process will run synchronously. Since you want things to run more quickly and asynchronously, omitting the -Wait
parameter should achieve the desired results.
Invoke-Command
Alternatively, you could use Invoke-Command
to kick off a PowerShell script, using the parameters: -File
, -ArgumentList
, -ThrottleLimit
, and -AsJob
. The Invoke-Command
command relies on PowerShell Remoting, so that must enabled, at least on the local machine.
Add a parameter block to the top of your "inner" script (the one you posted above), like so:
param (
[Parameter(Mandatory = $true)]
[string] $Path
)
That way, your "outer" script can pass in the directory path, using the -Path
parameter for the "inner" script.