'I need to symbolically link every directory and file in a target directory

Directories and files could change in the target, so the script needs to parse the directory on each run. Say c:\PS\ contains all of the targets and c:\DS contains all the links. I have tried something like

$files = Get-ChildItem "c:\ps"
foreach ($file in $files){
New-Item -ItemType SymbolicLink -Path "C:\DS\" -Target $file.FullName
}

My attempts are falling short.



Solution 1:[1]

There are mainly 2 issues with your code, the first one, $path is not defined and the second one, double-quotes in "c:\DS\$d.Name" are not allowing $d.Name to expand, you can use Subexpression operator $( ) for this.

$dir = Get-ChildItem c:\ps\
foreach($d in $dir) {
    New-Item -ItemType SymbolicLink -Path "c:\DS\$($d.Name)" -Target $d.FullName
}

Above should create a symlink in the C:\DS\ directory where each link has the name of their target folder. One thing to consider, this could require you to run PowerShell with admin permissions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1