在 Powershell 中使用 Copy-item 命令时,我看到在目标文件夹中创建了空源目录以及文件

I am seeing the empty source directory being created in the destination folder along with the file while using Copy-item command in Powershell

$InputFile = "C:\InfoWorkflows.txt"

$fileText = Get-Content $InputFile

foreach ($LineText in $fileText){
    echo "LineText is $LineText"
    $containsWord = $LineText | %{$_ -match "test_control.xml"}
    if($containsWord -eq $false)
    {
        $SplitText = $LineText -split' '
        $Change = $SplitText[0]
        $fileName = $SplitText[1]
        echo "fileName is $fileName"
        echo "Copy-Item -Path C:\mb\INFO$fileName -Destination C:\BackOrder\INFOT"
    }
}

在目标文件夹 C:\BackOrder\INFOT 中,在执行 inputFile 中提到的 PS 时,我能够看到 "test_Control.xml" 以外的文件以及一个空白文件夹(INFO) 是从源路径创建的,我从未提供任何 instruction.Can 有人调查它并帮助我?

您的代码不检查输出文件夹 'C:\BackOrder\INFOT' 是否存在,也不检查 'C:\mb\INFO$fileName' 是否存在。 除此之外,我不明白你为什么要对 Copy-Item cmdlet 进行字符串化..

另一件事是,您在包含句点 (.) 字符的文件名上使用正则表达式 -match 运算符,而没有将其转义。在正则表达式中,点有特殊含义,即'any character.'

下面的代码使用字符串对象方法 .Contains 来过滤 Where-Object{} 子句中不包含 "test_control.xml" 的字符串。如果您想继续使用 -match.

,您可以在代码注释中阅读如何使用 [Regex]::Escape()
$InputFile = 'C:\InfoWorkflows.txt'
$OutputDir = 'C:\BackOrder\INFOT'

# test if output folder exists and if not create it first
if (!(Test-Path -Path $OutputDir -PathType Container)) {
    Write-Host "Creating folder $OutputDir"
    $null = New-Item -Path $OutputDir -ItemType Directory
}
# read the input file as string array and filter the lines that do not contain "test_control.xml")
# if you want to do that with the regex -match operator, you should escape it first:
#   [Regex]::Escape("test_control.xml")  --> "test_control\.xml"
$fileText  = Get-Content $InputFile | Where-Object { !$_.Contains("test_control.xml") } | ForEach-Object {
    $fileName = ($_ -split ' ')[1]
    Write-Host "FileName is $fileName"
    # combine the path and file name for the file to copy
    $sourceFile = Join-Path -Path 'C:\mb\INFO' -ChildPath $fileName
    if (Test-Path -Path $sourceFile -PathType Leaf) {
        Copy-Item -Path $sourceFile -Destination $OutputDir
    }
    else {
        Write-Warning "File '$sourceFile' could not be found."
    }
}

希望对您有所帮助