Pass folder path dynamically when running powershell script from CMD

Hi Team,

In the below script, I’m excluding few folders from the scan but when I observed total time taken to replace files in folders, actually it is also scanning exclude folders.

So I want pass the path dynamically to $directory when executing the script from command line. So that we can explicitly provide 2 folder paths

Actually, I have 3 folders under $directory and would like to scan(replace string) only 2 folders.

Or is there a way to modify the below script ? I mean instead of creating 2 if blocks and reuse the existing code with only change in folder path when running

@Anil_G Could you please assist us on this issue?

$directory = “C:\Users\Desktop\powershell”
$searchpattern = “.
$oldstring1 = ‘runAs=“India”’
$newstring1 = ‘runAs=“America”’
$oldstring2 = ‘runAsGuid=“India”’
$newstring2 = ‘runAsGuid=“America”’
$modifiedfiles = @()

$SUBST Z: $directory

Get-ChildItem -LiteralPath “Z:” -Filter $searchpattern -Recurse | ForEach-Object {
if ($.GetType().Name -eq “FileInfo” -and $.Extension -ne “.atr” -and $_.DirectoryName -notin @(“Z:\exclude-folder1”, “Z:\exclude-folder2”)) {
$content = Get-Content -LiteralPath $.FullName
if ($content -match $oldstring1 -or $content -match $oldstring2) {
$modifiedcontent = $content -replace [regex]::Escape($oldstring1), $newstring1 -replace [regex]::Escape($oldstring2), $newstring2
Set-Content -LiteralPath $.FullName -Value $modifiedcontent
$modifiedfiles += $
.FullName
}
}
}

$modifiedfiles | Out-String -Stream