我已經測驗了很多命令,我似乎遇到了障礙并尋求幫助。
- 當我在 ComputerA 上運行此代碼時,我可以使用此代碼。ComputerA 的 HomeFolder 目錄位于 D: 驅動器上。文本檔案現在有 2 個機器名稱用于測驗目的。然后為ComputerB 和ComputerC 創建一個名為“NewCreation”的檔案夾。這是完美的。
Get-Content "D:\HomeFolder\MachineNames.txt" | %{New-Item -ItemType Directory -Path "\\$_\d$\NewCreation" -Force -Verbose}
但問題是,當環境中有一臺計算機已經存在此檔案夾(NewCreation)以及大量其他子檔案夾和檔案時,我正在尋找一個 if 陳述句,如果此檔案夾存在,我想將其重命名為“ NewCreation_OLD”并創建檔案夾“NewCreation”。
- 這是我的嘗試,我知道它并不完美,或者它不起作用我花了幾個小時和搜索,我浪費了很多時間。所以是的......我將非常感謝大家的所有指示和幫助!
$Folder = Get-Content "D:\HomeFolder\MachineNames.txt"
foreach ($Folders in $Folder){
if (Test-Path -Path "\\$_\d$\NewCreation")
{
Rename-Item -Path "\\$_\d$\NewCreation" -NewName NewCreation_OLD -Force -Verbose
New-Item -Path "\\$_\d$\" -Name NewCreation -ItemType Directory -Force -Verbose
}
else{
Write-Host "Do something else"
}
}
uj5u.com熱心網友回復:
您非常接近,唯一真正的問題是使用自動變數$_(也稱為$PSItem)而不是$item來自您的$collection:
foreach ($<item> in $<collection>){<statement list>}
我添加了一些評論以供指導。
# $computers instead of $Folder, for clarity
$computers = Get-Content "D:\HomeFolder\MachineNames.txt"
foreach ($computer in $computers)
{
# If this folder exists in this host
if (Test-Path -Path "\\$computer\d$\NewCreation")
{
# Rename it
Rename-Item -Path "\\$computer\d$\NewCreation" -NewName "NewCreation_OLD" -Force -Verbose
}
# Here we can assume that the folder was not there or was renamed, so we can create it
New-Item -Path "\\$computer\d$\" -Name NewCreation -ItemType Directory -Force -Verbose
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418466.html
標籤:
