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=1,2,3 #定义简单类型数组
$test | foreach{
Write-Host $_ #遍历每个元素
}

$testObj=@{name="zzl";age=34},@{name="zhz";age=8} #定义一个对象数组
$testObj | foreach{
$name= $_.name #必须将它赋给一个变量,如果直接在字符串里使用,它将输出自己的类型
$age=$_.age
Write-Host "name=$name,age=$age"
}

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

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

整个DEMO运行的结果如图

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值