当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] Powershell 移动文件并使用日期重命名

作者:精品下载站 日期:2024-12-14 22:06:25 浏览:13 分类:玩电脑

Powershell 移动文件并使用日期重命名


PowerShell 提供 Move-Item 和 Rename-Item cmdlet 来移动文件并使用日期重命名。使用 Get-Date cmdlet 获取当前日期并将其附加到文件中。

PowerShell 提供了许多 cmdlet 来管理系统中的文件和文件夹。

在本文中,我们将讨论如何使用 PowerShell 中的 Rename-Item、Move-Item 和 Get-Date cmdlet 重命名和移动文件并附加当前日期。

使用当前日期重命名文件

使用 PowerShell 中的 Rename-Item cmdlet 通过将当前日期附加到文件名称来重命名文件。

$currentDate = Get-Date -Format yyyy-MM-dd

$sourceFile = "D:\PS\ad.txt"
$destinationFile = "D:\PS\ad_$currentDate.txt"

Rename-Item -Path $sourceFile -NewName $destinationFile  

在上面的 PowerShell 脚本中,Get-Date cmdlet 获取当前日期时间并将其存储在 $currentDate 变量中。 $sourcePath 变量包含文件名,$destinationFile 包含文件名和附加的当前日期。

Rename-Item 使用 -Path 参数指定旧文件名,并使用 -NewName 参数指定具有当前日期的新文件。假设当前日期为 2023 年 4 月 9 日,它将文件 ad.txt 重命名为 ad_2023-04-09.txt

移动文件并使用当前日期重命名文件

使用 PowerShell 中的 Move-Item cmdlet 将文件移动到其他文件夹并使用当前日期重命名。

# Get the current date
$currentDate = Get-Date -Format yyyy-mm-dd     

# Source file name                                                                 
$sourceFile = "D:\PS\ad.txt"

# Append the Current date to file name                                                                                    $destinationFile = "ad_$currentDate.txt"

# Destination folder path                                                                        $destinationFolder = "D:\PS\AD"

# Move file and rename the file                                                                                 
Move-Item -Path $sourceFile -Destination "$destinationFolder$destinationFile"

# Get the items from the destination folder                                 
Get-ChildItem -Path D:\PS\AD\ | Select-Object -First 1  

在上面的 PowerShell 脚本中,Move-Item cmdlet 使用 -Path 参数指定源文件名,并使用 -Destination 参数指定目标文件夹路径。它会移动文件并使用当前日期重命名文件。

Get-ChildItem cmdlet 从目标文件夹路径检索项目。

使用当前日期移动并重命名文件后,上述 PowerShell 脚本的输出为:

[玩转系统] Powershell 移动文件并使用日期重命名

酷提示:如何在 PowerShell 中创建带有日期时间的日志文件!

结论

我希望上述有关如何使用 PowerShell 中的 Move-Item cmdlet 移动文件并使用当前日期重命名文件的文章对您有所帮助。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯