2016-04-01 57 views
2

我正在處理腳本以更改計算機的登錄背景。我已經做好了所需的一切,但我試圖讓腳本更加高效,因爲在選擇新腳本之後,我創建了一個名爲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

回答

1

是的,你可以在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'將返回集合中的一個隨機項目,它比計算隨機索引更簡潔一點 –