How to run the powershell code against each subfol

2019-08-30 00:18发布

问题:

I would like to run the powershell code below, against each sub-folder that is in the IIS root directory. The output should be separate .htm file for each sub-folder contents (containing only the files in that sub-folder). If you need me to clarify my question, just ask.

$basedir = 'c:\inetpub\wwwroot'
$exp     = [regex]::Escape($basedir)
$server  = 'http://172.16.246.76'

function Create-HtmlList($fldr) {
  Get-ChildItem $fldr -Force |
    select ...
    ...
  } | Set-Content "$fldr.htm"
}

# list files in $basedir:
Create-HtmlList $basedir

# list files in all subfolders of $basedir:
Get-ChildItem $basedir -Recurse -Force |
  ? { $_.PSIsContainer } |
  % {
    Create-HtmlList $_.FullName
  }

回答1:

You need to separate folder-traversal (recursive) from file processing (non-recursive), e.g. like this:

$basedir = 'c:\inetpub\wwwroot'
$exp     = [regex]::Escape($basedir)
$server  = 'http://172.16.x.x'

function Create-HtmlList($fldr) {
  Get-ChildItem $fldr -Force |
    ? { -not $_.PSIsContainer } |
    select ...
    ...
  } | Set-Content "$fldr.htm"
}

# list files in $basedir:
Create-HtmlList $basedir

# list files in all subfolders of $basedir:
Get-ChildItem $basedir -Recurse -Force |
  ? { $_.PSIsContainer } |
  % {
    Create-HtmlList $_.FullName
  }

The output files will be put into the respective folder (named after the folder with the extension .htm appended). If you want a different name or location for the output files, you need to adjust the Set-Content line in the function Create-HtmlList.