0
votes

The following powershell script is arranging the files by their extension in appropriate directory. What I did is first find all the unique extensions in the target folder and called copy for all those extensions but it doesn't work on Windows .I have used correct path for Windows.

Currently folders are being created but the file is not being copied from source folder to destination folder.

$source = "/home/shubham/ps/" #location of starting directory
$destination = "/home/shubham/ps/check"; #location where files will be   `copied to`
$extensionArray = @(Get-ChildItem ($source) |
                  Select-Object Extension |
                  Sort-Object Extension |
                  Get-Unique -AsString)
echo ($extensionArray[3])
[string[]]$l_array = ($extensionArray | Out-String -Stream) -notmatch '^$' |
                     select -Skip 2

for ($i=0; $i -lt $extensionArray.Length; $i++) {
    $x = $l_array[$i]

    $ext = "*" + "$x"

    #foreach ($x in $extension_array){
    echo ("*" + ($x))
    $newsrc = ($source) + "/" + ($ext)
    $files = @("", "*" + ($x)) #edit .xlsx to your desired extension
    $outputPath = ($destination) + "_" + ($x)

    New-Item -ItemType Directory -Force -Path ($outputpath);
    Copy-Item -Path $newsrc -Filter ($ext) -Destination $outputPath -Container 
}
echo "end"
1
What defines doesn't work? Are you getting error messages or is something else happening? - trebleCode
Edit provided currently the files are not being copied from one folder to another on windows but it works fine on ubuntu. - subham kumar
Have you tried using the -Force and -Debug parameters with Move-Item when on Windows to see what's happening? Also, have you tried stepping through your code in the PS ISE on Windows to view variables values? - trebleCode
Please stop that weird "putting parentheses around variables" thing. - Ansgar Wiechers

1 Answers

0
votes

When in doubt, read the documentation (emphasis mine):

-Path
Specifies, as a string array, the path to the items to copy.
Type: String[]
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False

Meaning paths like /home/shubham/ps/*.docx are not supported by Copy-Item. It probably works on Linux because the shell already expands the wildcard to a list of absolute paths before Copy-Item sees it.

Not to mention that your code is overly complicated. Something like this should suffice:

$src = '/home/shubham/ps/'
$dst = '/home/shubham/ps/check'

$files = Get-ChildItem $src

$files |
    Select-Object -Expand Extension -Unique |
    New-Item -Path $dst -Name {'_' + $_.TrimStart('.')} -Type Directory |
    Out-Null

$files | Copy-Item -Destination {Join-Path $dst ('_' + $_.Extension.TrimStart('.')} -Container