Powershell 字符串工作

Powershell string work

这是我的第一个问题,我是 powershell 的新手。

我有一个文件夹 $home\Devoluciones\,其中有几个名为 DtoXXXYYYYMM.dat 的文件,其中 XXX 是公司编号,YYYY 是当前年份,MM 代表当前月份。

我需要做的是将这些文件复制到以公司编号命名的文件夹中,例如,如果我有 Dto509201506.dat 和 Dto908201506.dat,我需要将这些文件复制到 $destination9\$destination8\ 分别。

到目前为止我有以下代码:

#List the items and send to a.txt
ls $home\Devoluciones\Dto*.dat | select -exp Name > $home\a.txt
#From a.txt keep first 6 characters and send to b.txt
Get-Content $home\a.txt | foreach {$_.remove(6)} | Add-Content $home\b.txt
#From b.txt replace Dto with "" and send to c.txt
Get-Content $home\b.txt | foreach {$_ -replace "Dto",""} | Add-Content $home\c.txt
#From c.txt copy the files to destination
Get-Content $home\c.txt | foreach {copy-item $home\Devoluciones\*$_*.dat $Destination$_\}
#Clean temp files
Remove-Item -ErrorAction Ignore $home\a.txt -Force
Remove-Item -ErrorAction Ignore $home\b.txt -Force
Remove-Item -ErrorAction Ignore $home\c.txt -Force

我想达到与此相同的结果"cleaner",我想学习如何在一行中操作字符串,是否可以只用一个命令复制所有内容。

谢谢,内斯特。

这是一个简单的实现,应该是不言自明的。我相信有人也会添加更简洁的一行答案。

$Files = Get-Childitem -path "$home\Devoluciones\*" -include *.dat
foreach ($file in $files) {
    $company = $file.Name.Substring(3,3)
    copy-item $file.FullName (join-path (join-path $Destination $company) $file.Name)
}

编辑:修复了目标路径中的错误

EDIT2:Get-ChildItem"The Include parameter is effective only when the command includes the Recurse parameter or the path leads to the contents of a directory, such as C:\Windows*, where the wildcard character is specified"

如果您愿意,所有 PowerShell 都可以写成一行,但这里有一些非常简洁的内容。

$path = "$home\Devoluciones\"
$destination = "C:\temp"
Get-ChildItem "$path\dto*.dat" | Copy-Item  -Destination {[System.IO.Path]::Combine($destination,($_.Name).Substring(3,3),$_.Name)} -Force

这将在此处执行的操作正是您想要的。获取所有过滤后的文件,并将每个文件复制到与其中包含的第 3-6 个字母代码对应的文件夹中。如果目标文件夹不存在,那么我们使用 -Force 来创建它。有助于新的公司代码。我们使用 [System.IO.Path]::Combine 来制作目标文件路径,它由管道中的目标文件夹、公司文件夹和当前文件组成。