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 solutio开发者_如何学编程n to the issue
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
}
}
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.
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
精彩评论