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运行的结果如图

  • 相关阅读:
    [调参]batch_size的选择
    [调参]CV炼丹技巧/经验
    [Pytorch]Pytorch加载预训练模型(转)
    [PyTorch]论文pytorch复现中遇到的BUG
    [Opencv]图像的梯度与边缘检测(转)
    freemodbus移植、实例及其测试方法
    eclipse的C/C++开发搭建
    ROS安装
    U-boot移植
    QT开发实战一:图片显示
  • 原文地址:https://www.cnblogs.com/lori/p/6971072.html
Copyright © 2011-2022 走看看