PowerShell~文件操作和对象遍历

时间:2023-03-09 21:56:43
PowerShell~文件操作和对象遍历

ps提供了丰富的文件操作,如建立,删除,改名,移动,复制,文件夹建立,显示文件列表,同时对数组对象的遍历也很方便,如果在使用PS脚本时,希望现时传入参数,可以把参数声明为param,当然需要把它写在文件开头的位置。

下面是大叔在看完eshop项目后,写的几个测试代码,对它们进行了注释,方便大家学习。

Param([string] $rootPath) #输入参数
$scriptPath = Split-Path $script:MyInvocation.MyCommand.Path #当前应用程序目录 Write-Host "Current script directory is $scriptPath" -ForegroundColor Yellow #定义字体颜色 if ([string]::IsNullOrEmpty($rootPath)) { #如果变量为空,就为它赋值
$rootPath = "$scriptPath\"
} Write-Host "Root path used is $rootPath" -ForegroundColor Yellow $projectPaths =
@{Path="$rootPath\src\web";Prj="test.txt"},
@{Path="$rootPath\src\api";Prj="test.txt"} $projectPaths | foreach {
$projectPath = $_.Path
$projectFile = $_.Prj
$outPath = $_.Path + "\publish"
$projectPathAndFile = "$projectPath\$projectFile"
Write-Host "Deleting old publish files in $outPath" -ForegroundColor Yellow
remove-item -path $outPath -Force -Recurse -ErrorAction SilentlyContinue #先删除先来的文件夹及内容
Write-Host "Publishing $projectPathAndFile to $outPath" -ForegroundColor Yellow New-Item $outPath -type directory -Force #建立文件夹  Copy-Item $projectPathAndFile -Destination $outPath # 复制到指定位置 # dotnet restore $projectPathAndFile
# dotnet build $projectPathAndFile
# dotnet publish $projectPathAndFile -o $outPath
} $test=,, #定义简单类型数组
$test | foreach{
Write-Host $_ #遍历每个元素
} $testObj=@{name="zzl";age=},@{name="zhz";age=} #定义一个对象数组
$testObj | foreach{
$name= $_.name #必须将它赋给一个变量,如果直接在字符串里使用,它将输出自己的类型
$age=$_.age
Write-Host "name=$name,age=$age"
}

上面代码会在E盘指定目录进行文件的复制,这类似于网站的发布机制,从一个地方复制到网站目录。

其中param要求我们在使用ps1文件时,提供一下参数,当然可以不传,我们代码里也有对它的赋值。

PowerShell~文件操作和对象遍历

整个DEMO运行的结果如图

PowerShell~文件操作和对象遍历