PowerShell 文件操作
最后修改:2025 年 2 月 15 日
在本文中,我们将介绍如何在 PowerShell 中进行文件操作。
PowerShell 是一个跨平台的任务自动化解决方案,它包含一个命令行 Shell、一个脚本语言和一个配置管理框架。
PowerShell 提供了丰富的 cmdlet 来进行文件操作。
Get-ChildItem
Get-ChildItem
cmdlet 用于获取一个或多个指定位置中的项。
get_child_item.ps1
Get-ChildItem -Path "C:\"
在此程序中,我们获取 C 驱动器根目录的子项。
PS C:\> .\get_child_item.ps1 Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 15/02/2025 16:23 Config.Msi d----- 15/02/2025 16:23 Documents and Settings d----- 15/02/2025 16:23 PerfLogs d----- 15/02/2025 16:23 Program Files d----- 15/02/2025 16:23 Program Files (x86) d----- 15/02/2025 16:23 Recovery d----- 15/02/2025 16:23 System Volume Information d----- 15/02/2025 16:23 Users d----- 15/02/2025 16:23 Windows
我们运行脚本并查看输出。
Remove-Item
Remove-Item
cmdlet 用于删除文件、目录和注册表项等项。
remove_item.ps1
Remove-Item -Path "test.txt"
在此程序中,我们删除一个名为 test.txt
的文件。
PS C:\> .\remove_item.ps1
我们运行脚本,没有看到任何输出。
Copy-Item
Copy-Item
cmdlet 将一个项从一个位置复制到另一个位置。
copy_item.ps1
Copy-Item -Path "test.txt" -Destination "test_copy.txt"
在此程序中,我们将一个名为 test.txt
的文件复制到一个名为 test_copy.txt
的新文件中。
PS C:\> .\copy_item.ps1
我们运行脚本,没有看到任何输出。
Move-Item
Move-Item
cmdlet 将一个项从一个位置移动到另一个位置。
move_item.ps1
Move-Item -Path "test.txt" -Destination "test_moved.txt"
在此程序中,我们将一个名为 test.txt
的文件移动到一个名为 test_moved.txt
的新文件中。
PS C:\> .\move_item.ps1
我们运行脚本,没有看到任何输出。
Test-Path
Test-Path
cmdlet 用于测试路径是否存在。
test_path.ps1
Test-Path -Path "test_moved.txt"
在此程序中,我们测试一个名为 test_moved.txt
的文件是否存在。
PS C:\> .\test_path.ps1 True
我们运行脚本并查看输出。
来源
在本文中,我们向您展示了如何在 PowerShell 中进行文件操作。
作者
列出 所有 PowerShell 教程。