Как я могу прочитать внутренние значения файла и создать каталог, а затем переместить файл PowerShell? - PullRequest
0 голосов
/ 04 сентября 2018

Мне нужно прочитать из файла, и, исходя из значения в первой строке, переместить файл в имя значения.

Например, если написано type = item, переместите этот файл в каталог, который мне может потребоваться создать с именем item, а затем перейдите к следующим файлам.

Как я могу выполнить эту задачу?

1 Ответ

0 голосов
/ 05 сентября 2018

через ваш комментарий против оригинального сообщения. Что касается этого ...

get-childitem "<SourceFolder>" -filter 7*.txt - recurse | select-string -list -pattern "test" | move -dest "<DestinationFolder>"

… это никогда не будет работать, потому что это возвращает полное имя файла плюс строку, которую вы искали как коллекцию. Таким образом, то, что вы делаете, может потребовать цикла и очистки всех случайных вещей.

Пример - использование вашего комментария как есть и извлечение материала о переезде / повторении:

Get-ChildItem 'd:\temp' -filter '*.txt' | 
Select-String -list -pattern 'test' | %{ $_ }

# Results

D:\temp\TestFile0.txt:1:test
D:\temp\TestFile1.txt:1:test
D:\temp\TestFile2.txt:1:test

Итак, исходя из вышесказанного, вы можете видеть, что вы не передаете законное полное имя файла по конвейеру, хотя вы соответствуете строке. Итак, вы хотите использовать другой подход или использовать то, что у вас есть, и очистить результаты, но обрезая ненужные вещи.

Обновление согласно предложению Ansgar

Вот один из вариантов, и, как вы говорите, вы новичок, проходите процесс. Обратите внимание, что всегда есть разные опции / методы для этого.

# Get the target files
Get-ChildItem -Path 'd:\temp' -filter '*.txt' | Format-Table -AutoSize

# Results

    Directory: D:\temp

Mode          LastWriteTime Length Name                    
----          ------------- ------ ----                    
-a----   7/6/2018  10:16 PM     24 1 passwordchangelog.txt 
-a----   7/6/2018  10:16 PM     24 10 passwordchangelog.txt
-a----   7/6/2018  10:16 PM     24 11 passwordchangelog.txt
-a----   9/4/2018   5:20 PM     26 TestFile0.txt           
-a----   9/4/2018   5:20 PM     26 TestFile1.txt           
-a----   9/4/2018   5:20 PM     26 TestFile2.txt 




# Get the target files, matching the string filter
Get-ChildItem -Path 'd:\temp' -filter '*.txt' | 
Select-String -List -Pattern 'test'

# Results

D:\temp\TestFile0.txt:1:test
D:\temp\TestFile1.txt:1:test
D:\temp\TestFile2.txt:1:test


# Get the target files, matching the string filter, clearing the meta data
(Get-ChildItem -Path 'd:\temp' -filter '*.txt' | 
Select-String -list -pattern 'test') -replace (':\d.*')

# Results

D:\temp\TestFile0.txt
D:\temp\TestFile1.txt
D:\temp\TestFile2.txt


# Get the target files, matching the string filter, clearing the meta data, test direcory create and file action
(Get-ChildItem -Path 'd:\temp' -filter '*.txt' | 
Select-String -list -pattern 'test') -replace (':\d.*') |
Move-Item -Destination (New-Item -Type Directory -Verbose -Force ('D:\temp\NewFiles') -WhatIf) -Verbose -WhatIf

# Results

Move-Item : Cannot process argument because the value of argument "destination" is null. Change the value of argument "destination" to a non-null value.
At line:3 char:1
+ Move-Item -dest (New-Item -Type Directory -Verbose -Force ('D:\temp\N ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Move-Item], PSArgumentNullException
    + FullyQualifiedErrorId : ArgumentNull,Microsoft.PowerShell.Commands.MoveItemCommand




# Get the target files, matching the string filter, clearing the meta data, force direcory create if it does not exist and execute the file action
(Get-ChildItem -Path 'd:\temp' -filter '*.txt' | 
Select-String -List -Pattern 'test') -replace (':\d.*') |
Move-Item -Destination (New-Item -Type Directory -Verbose -Force ('D:\temp\NewFiles')) -Verbose -Force

# Results

VERBOSE: Performing the operation "Create Directory" on target "Destination: D:\temp\NewFiles".
VERBOSE: Performing the operation "Move File" on target "Item: D:\temp\TestFile0.txt Destination: D:\temp\NewFiles\TestFile0.txt".
VERBOSE: Performing the operation "Move File" on target "Item: D:\temp\TestFile1.txt Destination: D:\temp\NewFiles\TestFile1.txt".
VERBOSE: Performing the operation "Move File" on target "Item: D:\temp\TestFile2.txt Destination: D:\temp\NewFiles\TestFile2.txt".


Get-ChildItem -Path 'D:\temp\NewFiles' | Format-Table -AutoSize

# Results

    Directory: D:\temp\NewFiles

Mode          LastWriteTime Length Name         
----          ------------- ------ ----         
-a----   9/4/2018   5:20 PM     26 TestFile0.txt
-a----   9/4/2018   5:20 PM     26 TestFile1.txt
-a----   9/4/2018   5:20 PM     26 TestFile2.txt
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...