powershell 文件/文件夹操作

新建文件夹

New-Item -ItemType Directory -Force -Path $TargetPath

复制文件夹到另外文件夹

Copy-Item <源文件夹>  <新文件夹>  -recurse -force

复制文件(与修改文件名)

// 达到复制文件到新文件夹,及修改文件名效果
copy-item $testPic $nowselectHDD

// 目标文件不能包含路径,既不能移动到新文件夹
rename-Item $filePath -NewName $NewFilePath  

最新修改文件

$allFolder= Get-ChildItem "C:\Target"
$newFolder=($allFolder|Sort-Object LastWriteTime -Descending|select -first 1).name

//1. Get-ChildItem获取所有文件
//2. Sort-Object LastWriteTime -Descending 排序
//3. select -first 1 选择前 1 个
//4. .name 只获取文件名。如果没有会出现制表

跳过最新的前面n个文件

$files = $allPIc | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip 2
if ($files.count -gt 0) 
{
	foreach($file in $files)
	{
		Remove-Item $file.FullName -Recurse -Force
	}
}  

//1.  Select-Object -Skip 2 排除前两个文件
//2.  foreach 删除所有选择文件。
//3.  最后剩下1跳过的文件。

删除文件

Remove-Item c:/scripts/* -recurse

$TargetFolder = "c:\Test" 
$Files = get-childitem $TargetFolder -force
Foreach ($File in $Files)
{
$FilePath=$File.FullName
Remove-Item -Path $FilePath -Recurse -Force
}

可以使用“get-help remove-item -full”命令来查看Remove-Item的完整帮助文档,内容如下:

PS C:\> get-help remove-item -full

复制文件

Copy-Item c:/scripts/Test.txt  c:/Test
Copy-Item c:/scripts/*  c:/Test
Copy-Item c:/scripts/*.txt  c:/Test
Copy-Item c:/scripts c:/Test –recurse  //复制文件夹

获取文件名

[System.IO.Path]::GetFileNameWithoutExtension("test.mm.txt")
//结果为test.mm

获取txt内容

$txt=(Get-Content d:\1.txt -TotalCount 2)[-1].Trim()

$txt[0] //第一行

//-TotalCount 表示获取txt内行数,2表示取前2行
//[-1] 表示最后一个
//Trim() 去空格

输出到txt文件

 "Hello World!" | Out-File d:\1.txt
$fileCount | Out-File -Append d:\1.txt //追加

获取txt所有内容,以及行数

$statusList = Get-Content ./StatusList.txt
$statusList[0] 

//第一行

$statusList.length

//所有行

比较文件内容

PS C:\> $old=Get-Content c:\test\File1.txt
PS C:\> $new=Get-Content c:\test\File2.txt
PS C:\> Compare-Object $old $new

其他文件名操作参考

PowerShell文件系统(三)导航文件系统 – PowerShell 中文博客

打包压缩

Compress-Archive -LiteralPath <PathToFiles> -DestinationPath <PathToDestination>
Compress-Archive -LiteralPath <PathToFolder> -DestinationPath <PathToDestination>

# PathToFiles 文件集合,用逗号隔开
# PathToDestination zip包名

# PathToFolder 需要压缩文件夹

参考 (11条消息) powershell 压缩_如何使用PowerShell压缩(和解压缩)文件_culiyuan8310的博客-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值