适用于 1 个目录路径但不适用于多个目录路径的脚本

Script working for 1 directory path but not for multiple directory paths

我正在尝试

  1. 在每个WE*.MS目录下创建一个CD_TMP文件

  2. 通过处理AHD*.TPL和ADT*.TPL文件设置内容

  3. 将 AHD*.TPL 重命名为 AHD*.TPL.Done 并将 ADT*.TPL 重命名为 AHD*.TPL.Done.

当只有一个WE.20150408.MS目录时,脚本运行正常 但是当有多个目录时(即 WE.20150408.MS、WE.20151416.MS、WE.20140902.MS),它不起作用并给出错误信息:

Get-Content: An object at specified path AHD*TPL does not exist of has been filtered by the -Include or -Exclude parameter.
At C:\Temp\Script\Script.ps1:24 Char:14
+ $content = Get=Content -path $AHD
+ CatagoryInfo  :ObjectNotFound: (System.String[]:Strint[1) [Get-Content], Exception
+ FullyQualifiedErrorID:    ItemNotFound,Micorsoft.Powershell.Commands.GetContentCommand

脚本:

$SOURCE_DIR = "C:\Work"
$Work_DIR = "WE*MS"
$WE_DIR = "$SOURCE_DIR$Work_DIR"
$AHD = "AHD*TPL"
$ADT = "ADT*TPL"
$AHD_FILES = $SOURCE_DIR
$CD_TMP = "CD_TMP"
$Str1 = "TEMP"
##############
Set-Location $WE_DIR
New-Item -Path "CD_TMP" -type file  -force 
#############           
foreach ( $File in ( get-childitem -name $WE_DIR))
                {

        $content = Get-Content -path $AHD
           $content | foreach {

            If ($_.substring(0,4) -NotLike $Str1)
            {
            '0011' + '|' + 'HD' + '|' + 'AHD' + $_
             }
        } | Set-Content $CD_TMP
}

Get-ChildItem AHD*.TPL| ForEach {Move-Item $_ ($_.Name -replace ".TPL$",
".TPL.Done")}
##############
foreach ( $File in ( get-childitem -name $WE_DIR))
                {
        $content = Get-Content -path $ADT
           $content | foreach {

            If ($_.substring(0,4) -NotLike $Str1)
            {
            '0022' + '|' + 'DT' + '|' + 'ADT' + $_
             }
        } | Set-Content $CD_TMP
}

Get-ChildItem ADT*TPL| ForEach {Move-Item $_ ($_.Name -replace ".TPL$",
".TPL.Done")}

PAUSE

是不是先报错Set-Location : Cannot set the location because path 'C:\Work\WE*MS' resolved to multiple containers.?这就是我希望它在失败时说的话。

然后,由于无法进入文件夹,所以找不到任何AHD文件。

一个文件夹能正常使用吗?它为 AHD 文件写入 CD_TMP 文件,然后为 ADT 文件覆盖它。好像不太对。

您还可以通过更改使其更直接一些:

  • 在开始时将很多东西放入 $CAPITAL 变量中,然后使用它们一次,或者永远不会。
  • .substring() -notlike测试使用.startswith()
  • 字符串用++++拼成一个字符串
  • 使用 -NewName 脚本块重命名为 Rename-Item

我在想:

$folders = Get-ChildItem "C:\Work\WE*MS" -Directory

foreach ($folder in $folders) {

    # AHD files    
    $content = Get-Content "$folder\AHD*.TPL"
    $content = $content | where { -not $_.StartsWith('TEMP') } 
    $content | foreach {"0011|HD|AHD$_"} | Set-Content "$folder\CD_TMP" -Force

    Get-ChildItem "$folder\AHD*.TPL" | Rename-Item -NewName {$_.Name + '.Done'}

    # ADT files
    $content = Get-Content "$folder\ADT*.TPL"
    $content = $content | where { -not $_.StartsWith('TEMP') } 
    $content | foreach {"0011|HD|ADT$_"} | Add-Content "$folder\CD_TMP"

    Get-ChildItem "$folder\ADT*.TPL" | Rename-Item -NewName {$_.Name + '.Done'}

}

虽然不知道输入输出应该是什么,所以没法测试。注意。它现在 Add-Content 附加到 CD_TMP 文件,而不是覆盖它。

$content 仍然有很多冗余,但这些行大多像这样独立。