我正在编写一个脚本来更改计算机的登录背景。我已经完成了我需要做的所有事情,但我正在努力使脚本更有效率,因为在选择新的脚本之后,我创建了一个名为OrderNames
的函数来重命名所有内容随机,然后将它们重命名为background1,2,3,依此类推。以下是我正在使用的内容片段:
Function OrderNames #Renames everything to a format better than random numbers
{
$FileNames = GCI $BGPath -exclude $BGOld
$FileNames | ForEach-Object -process { Rename-Item $_ -NewName "$Get-Random).jpg" }
$OrderNames = GCI $BGPath -exclude $BGOld
$OrderNames | ForEach-Object -begin { $count = 1 } -process
{ Rename-Item $_ -NewName "background$count.jpg"; $count++ }
}
$Path = "C:\Windows\System32\oobe\info\backgrounds"
$BGOld = GCI $BGPath "backgrounddefault.jpg" #Store current background name
$BGFiles = GCI $BGPath -exclude $BGOld #Get all other images
$BGNew = $BGFiles[(get-random -max ($BGFiles.count)] #Select new image
Rename-Item $BGOld.FullName "$(Get-Random)-$($_.Name).jpg"
Rename-Item $BGNew.FullName "backgrounddefault.jpg"
OrderNames
这样做很好,花花公子,但我希望能够简单地切换$BGOld
和$BGNew
的名称。回到大学用C我可以创建一个临时变量,将BGNew存储到它,使BGNew等于BGOld,然后使BGOld等于temp。但是当我创建一个值为BGOld的临时变量时,它不起作用。事实上,变量似乎没有随着重命名功能而改变,并且设置一个等于另一个导致
无法重命名,因为项目at不存在。
很好,所以我尝试将文件名设置为Select basename
的变量,但是我收到错误
无法索引到system.io.fileinfo类型的对象。
另外,我尝试了$BGOld.FullName = $BGNew.FullName
,尝试使用Rename-Item
以及其他一些我现在还记不住的其他人。
我尝试复制项目名称,但这也不起作用。我希望这不是一件我忽略的事情。
TL; DR
是否可以将文件名复制到临时变量中,这样当我重命名文件时,我可以将临时变量的名称复制回“旧”变量以避免重命名所有内容?或者甚至更好,我可以切换文件名吗?
答案 0 :(得分:1)
是的,你可以在PowerShell中做类似的事情。这个“算法”与你为C描述的基本相同:
因此,我们需要跟踪的唯一信息是旧名称和新名称+临时文件名。
# Grab the current background and pick the new one
$BGPath = "C:\Windows\System32\oobe\info\backgrounds"
$CurrentBG = Get-Item (Join-Path $BGPath -ChildPath 'backgrounddefault.jpg')
$NewBG = Get-ChildItem $BGPath -Filter *.jpg -Exclude $CurrentBG.Name |Get-Random
# Store the current name of the new background in a variable
$NewBGName = $NewBG.Name
# Now comes the swap operation
# 1. Rename old file to something completely random, but keep a reference to it with -PassThru
$OldBG = $CurrentBG |Rename-Item -NewName $([System.IO.Path]::GetRandomFileName()) -PassThru
# 2. Rename new file to proper name
$NewBG |Rename-Item -NewName 'backgrounddefault.jpg'
# 3. And finally rename the old background back to the name previously used by the new background
$OldBG |Rename-Item -NewName $NewBGName
答案 1 :(得分:0)
检查一下。使用变量引用文件,然后交换变量。
${c:file1.txt},${c:file2.txt} = ${c:file2.txt},${c:file1.txt}