简体   繁体   English

在Linux(Ubuntu pwsh)上运行的PowerShell脚本,但在Windows上不运行

[英]PowerShell script working on Linux (Ubuntu pwsh) but not on Windows

The following powershell script is arranging the files by their extension in appropriate directory. 以下Powershell脚本按扩展名在相应目录中排列文件。 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. 我要做的是首先在目标文件夹中找到所有唯一的扩展名,并为所有这些扩展名叫copy,但是在Windows上不起作用。我为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"

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 位置:1
Default value: None 默认值:无
Accept pipeline input: True (ByPropertyName, ByValue) 接受管道输入:True(ByPropertyName,ByValue)
Accept wildcard characters: False 接受通配符:False

Meaning paths like /home/shubham/ps/*.docx are not supported by Copy-Item . Copy-Item不支持/home/shubham/ps/*.docx类的含义路径。 It probably works on Linux because the shell already expands the wildcard to a list of absolute paths before Copy-Item sees it. 它可能在Linux上有效,因为Shell在Copy-Item看到通配符之前已经将通配符扩展到了绝对路径列表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM