切换两个文件的名称

问题描述:

我正在处理脚本以更改计算机的登录背景。我已经做好了所需的一切,但我试图让脚本更加高效,因为在选择新脚本之后,我创建了一个名为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名称。回到大学后,我可以创建一个临时变量,将BGNew存储到它,使BGNew等于BGOld,然后使BGOld等于临时值。但是当我用BGOld的值创建一个临时变量时,它不起作用。实际上,这些变量似乎没有随着重命名功能而改变,并且将一个等于其他结果设置为

由于item at不存在,所以无法重命名。

精细,所以我尝试的文件只是名字与Select basename设置为一个变量,但我得到一个错误约

不能索引类型system.io.fileinfo的对象。

此外,我试图$BGOld.FullName = $BGNew.FullName,试图用Rename-Item和其他一些我现在不记得了。

我试图复制项目名称,但这也不起作用。我希望这不是简单的,我忽略了。

TL; DR
是否有可能一个文件名后面在复制到一个临时变量,所以,当我重命名这些文件,我可以复制的临时变量的名称为“老”一个避免重命名的一切?或者甚至更好,我可以切换文件名吗?

+0

看起来你回答了自己的问题:第一个文件重命名为一个临时名称,重命名第二个文件到第一个文件名,然后重命名临时文件到第二个文件的名称。 –

+0

在将新文件重命名为旧名称之前,将磁盘上的文件重命名为随机文件* is *文件系统相当于您在内存中所描述的C变量swap中所描述的内容 –

+0

@Bill_Stewart我试过这样做,但它不会让我这样做 - 当我试图让我得到错误的文件名不存在,甚至更好,路径为空。 – user6111573

是的,你可以在PowerShell中做类似的事情。在“算法”这基本上是一样的,你形容为C:

  1. 重命名旧的东西临时
  2. 重命名新老
  3. 名老重命名的名称新

因此,我们需要跟踪的唯一信息是新旧名称+临时文件名。

# 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 
+0

谢谢!我没有正确初始化临时名称,也不知道如何使用[System.IO.Path]。不是管道重命名 - 项目就像我应该有。原谅我的无知,还没有掌握PowerShell的所有细节。 – user6111573

+0

@ user6111573不要太担心,我们都活着学习:)请注意,将一个集合传递给'Get-Random'将返回集合中的一个随机项目,它比计算随机索引更简洁一点 –