문제

I'm attempting to write a PowerShell script to move files from one directory to another based on a few conditions. For example:

  1. An example of a file name: testingcenter123456-testtype-222-412014.pdf.

  2. The script should look for "testingcenter123456" before the first dash ("-") and then refer to a hash table for a matching key. All the files follow the format shown above.

  3. Once its finds that key, it should use that key's corresponding value (example: "c:\temp\destination\customer7890") as the destination file path and copy the file there.

I looked around StackOverflow and found a few Q&As that seemed to answer parts of similar questions but the fact that I'm very new to this has led to the script I pieced together not working at all.

Here's what I have so far:

$hashTable = ConvertFrom-StringData ([IO.File]::ReadAllText("c:\temp\filepaths.txt"))
$directory = "c:\temp\source"
Get-ChildItem $directory |
    where {!($_.PsIsContainer)} |
    Foreach-Object {
    Foreach ($key in $hashTable.GetEnumerator()){
       if ($_.Name.Substring(0,$_.Name.IndexOf("-")) -eq $key.Name){
       Copy-Item -Path $_.fullname -Destination $key.Value
       }
    }
    }

If anyone can help me get un-stuck and hopefully learn a little something about PowerShell in the process, I'd appreciate it.

도움이 되었습니까?

해결책

Honestly, I'm not seeing why this shouldn't work. It would be helpful if you told us which line was generating an error.

Foreach ($key in $hashTable.GetEnumerator()) {
   if ($_.Name.Substring(0,$_.Name.IndexOf("-")) -eq $key.Name) {
   Copy-Item -Path $_.fullname -Destination $key.Value
   }
}

That said, you're missing the point of using hashtable by looping through its entries, manually matching on key. With a hashtable, you don't need to loop e.g.

$hashTable = ConvertFrom-StringData ([IO.File]::ReadAllText("c:\temp\filepaths.txt"))
Get-ChildItem c:\temp\source |
Where {!($_.PsIsContainer)} |
Foreach-Object {
    $key =  $_.Name.Substring(0,$_.Name.IndexOf("-"))
    $val = $hashtable.$key
    if ($val) {
        $_ | Copy-Item -Dest $val -WhatIf
    }
    else {
        Write-Warning "No entry for $key"
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top