[已解决]Powershell脚本将多个文件从源文件夹硬链接到目标文件夹

问题描述 投票:0回答:1

我无法理解我是否需要一个数组,如何在 Powershell 中设置它,以及我是否需要 for 之类的东西,因为我不是开发人员,也从未深入研究过它。 所以我想要实现的目标是从源文件夹中的文件创建硬链接到目标文件夹,然后将其作为 powershell 脚本。 由于我想要保护磁盘空间,因此我更愿意创建硬链接而不是复制粘贴并让文件占用磁盘空间。 例如: 源文件夹有 -N 个文件 所有内容都应读入数组(?)以自动创建硬链接。 我已经尝试使用 New-Item 元素创建硬链接,如下所示,但我总是收到错误,尽管路径存在,但找不到路径...

我一无所知,希望有人能帮助我。

$source = "C:\temp1"
$target = "C:\temp2"
$filename = "" #Array filled variable with content from $source folder

Array.....

New-Item -Type HardLink -Path "$source\$filename" -Value "$target\$filename #Tried it and ends with Errors in Path not found. Don't understand why

如有必要,在Win 10 Pro 22H2上进行测试

尝试创建 powershell 命令来创建硬链接,但失败。

如果更容易生成和理解,我也会接受 cmd commandlet。

powershell arraylist hardlink
1个回答
0
投票

更新,因为 chatgpt 不再需要我的电话号码(很高兴),我要求人工智能生成脚本。 如果有人能看一下,那就太好了

# Define source and target folders
$sourceFolder = "C:\a"
$targetFolder = "C:\b"

# Function to create hardlinks
function Create-Hardlink {
    param(
        [string]$sourceFile,
        [string]$targetFile
    )
    $null = New-Item -ItemType HardLink -Path $targetFile -Value $sourceFile
}

# Function to index source folder and create hardlinks
function Index-And-Create-Hardlinks {
    param(
        [string]$sourceFolder,
        [string]$targetFolder
    )

    # Get all files in source folder recursively
    $files = Get-ChildItem -Path $sourceFolder -Recurse -File

    # Create hardlinks for each file in target folder
    foreach ($file in $files) {
        $relativePath = $file.FullName.Substring($sourceFolder.Length + 1)
        $targetPath = Join-Path -Path $targetFolder -ChildPath $relativePath
        $targetDirectory = Split-Path -Path $targetPath -Parent
        
        # Create target directory if it doesn't exist
        if (-not (Test-Path -Path $targetDirectory)) {
            $null = New-Item -Path $targetDirectory -ItemType Directory
        }
        
        # Create hardlink
        Create-Hardlink -sourceFile $file.FullName -targetFile $targetPath
    }
}

# Index and create hardlinks
Index-And-Create-Hardlinks -sourceFolder $sourceFolder -targetFolder $targetFolder
© www.soinside.com 2019 - 2024. All rights reserved.