【发布时间】:2016-10-18 10:53:52
【问题描述】:
我有一个 PowerShell 脚本,可以将所有文件从一个位置移动到另一个位置,这些文件的日期修改时间超过 3 年。我有它,所以文件在移动到新位置时也保持原来的文件结构。
我正在尝试这样做,一旦文件被移动到新位置,它会在原始目录中创建一个指向文件新位置的快捷方式。
以下是我目前的脚本,它完成了上述所有操作减去快捷方式。
$sourceDir = "C:\Users\bgough\Documents\powershell\docs"
$archiveTarget = "C:\Users\bgough\Documents\archive"
$dateToday = Get-Date
$date = $dateToday.AddYears(-3)
$items = Get-ChildItem $sourceDir -Recurse |
Where-Object {!$_.PSIsContainer -and $_.LastWriteTime -le $date}
foreach ($item in $items)
{
$withoutRoot = $item.FullName.Substring([System.IO.Path]::GetPathRoot($item.FullName).Length);
$destination = Join-Path -Path $archiveTarget -ChildPath $withoutRoot
$dir = Split-Path $destination
if (!(Test-Path $dir))
{
mkdir $dir
}
Move-Item -Path $item.FullName -Destination $destination
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$sourceDir")
$Shortcut.TargetPath = $destination
$Shortcut.Save()
}
在我的脚本中,我尝试了创建此快捷方式,但它没有帮助。我也通读了以下内容,但不太了解..
How to create a shortcut using Powershell
Powershell Hard and Soft Links
编辑:
我已经成功获得了在原始文件夹中创建的快捷方式。但是,我似乎无法弄清楚如何传递一个变量以用作快捷方式名称。目前,字符串是硬编码的,这就是快捷方式的名称。请参阅下面的代码:我想将名称设置为项目全名(与被移动的文档同名)。
$sourceDir = "C:\Users\bgough\Documents\powershell\docs"
$archiveTarget = "C:\Users\bgough\Documents\archive"
$dateToday = Get-Date
$date = $dateToday.AddYears(-3)
$items = Get-ChildItem $sourceDir -recurse | Where-Object {!$_.PsIsContainer -and $_.LastWriteTime -le $date}
foreach ($item in $items)
{
$withoutRoot = $item.FullName.Substring([System.IO.Path]::GetPathRoot($item.FullName).Length);
$destination = Join-Path -Path $archiveTarget -ChildPath $withoutRoot
$dir = Split-Path $destination
if (!(Test-Path $dir))
{
mkdir $dir
}
Move-Item -Path $item.FullName -Destination $destination
$wshshell = New-Object -ComObject WScript.Shell
$desktop = [System.Environment]::GetFolderPath('Desktop')
$lnk = $wshshell.CreateShortcut($sourceDir + "\ShortcutName.lnk")
$lnk.TargetPath = "$destination"
$lnk.Save()
}
【问题讨论】:
-
您要创建快捷方式还是(符号)链接?它们是完全不同的东西。另外,您的尝试没有按预期工作怎么办?你收到错误了吗?
-
我正在寻找捷径。我也没有收到错误,但是原始位置没有快捷方式。
-
@AnsgarWiechers 非常感谢您的语法检查。 (叹气..)
标签: powershell