File moving according to substring derived from file name

拟墨画扇 提交于 2019-12-14 01:14:03

问题


Ihave started a simple script in order to move files of a certain prefix to a folder of the same name eg: W100_11.jpg W100_12.jpg in to folder W100.

Thanks to help from the answers below I have progressed and have a successful loop which can iterate through the file sin the folder, I am having issues with the -filter switch and when trying to use the move-item cmdlet I am getting errors

The current code is:

$sourceDir = read-host "Please enter source Dir:"
$format = read-host "Format to look for with .  :"
#$length = read-host "length of folder name:"

gci -Path $sourceDir | % {
    If( -not $_.PSIsContainer)
    {
        $path = $sourceDir + "\" + $_.Name.substring(0, 3)
        $_
        if(-not (Test-Path $path))
        {
            mkdir $path

        }
        move $_.fullname $path

    }  
}

I am still having issues when using the -filter switch. This is a partial solution to the issue


回答1:


The code below shortens your for loop and shows an example of using substrings on file names. You get a FileInfo object from the Get-ChildItem (gci) call, so you need to use it's property Name to do substrings. See MSDN for more info on FileInfo.

$sourceDir = read-host Please enter source Dir
$format = read-host Format to look for with .  

gci -Path $sourceDir -filter $format | % {
    If( -not $_.PSIsContainer)
    {
        $path = $sourceDir + "\" + $_.Name.substring(0, 3)  
        if(-not (Test-Path $path))
        {
            mkdir $path
        }
        move $_ $path
    }  
}



回答2:


If files names are always with this prefix "W100" you can easily take a substring in this way:

$a = "w100_12.ps1"
$a.Substring(0,4) # give W100

if prefix is not fix give more sample to help you solve it.




回答3:


When piping use the built-in variable $_ to refer to the piped object, the '%' sign is an alias for 'for each':

get-childitem -Path $sourceDir -Filter $format -Recurse | % {If ($_.extension -eq ".ps1"){Write-Host $_.fullname}}

Answers above refer to substring, here is the MS Technet page that explains Powershell substring usage:

http://technet.microsoft.com/en-us/library/ee692804.aspx



来源:https://stackoverflow.com/questions/7316797/file-moving-according-to-substring-derived-from-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!