zoukankan      html  css  js  c++  java
  • 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="$rootPathsrcweb";Prj="test.txt"},
        @{Path="$rootPathsrcapi";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运行的结果如图

  • 相关阅读:
    2018-2019-20172329 《Java软件结构与数据结构》第八周学习总结
    2018-2019-20172329 《Java软件结构与数据结构》第七周学习总结
    20172324 2018-2019-1《程序设计与数据结构》课程总结
    选择困难症的福音——团队Scrum冲刺阶段-Day5(补发 那天csshow)
    IG—金字塔
    选择困难症的福音——团队Scrum冲刺阶段-Day 7
    选择困难症的福音——团队Scrum冲刺阶段-Day 4
    哈夫曼编码测试
    选择困难症的福音——团队Scrum冲刺阶段-Day 3
    选择困难症的福音——团队Scrum冲刺阶段-Day 2
  • 原文地址:https://www.cnblogs.com/lori/p/6971072.html
Copyright © 2011-2022 走看看