PowerShell~文件操作和对象遍历

栏目: 编程工具 · 发布时间: 7年前

内容简介: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文件时,提供一下参数,当然可以不传,我们代码里也有对它的赋值。

PowerShell~文件操作和对象遍历

整个DEMO运行的结果如图

PowerShell~文件操作和对象遍历


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

High Performance JavaScript

High Performance JavaScript

Nicholas C. Zakas / O'Reilly Media / 2010-4-2 / USD 34.99

If you're like most developers, you rely heavily on JavaScript to build interactive and quick-responding web applications. The problem is that all of those lines of JavaScript code can slow down your ......一起来看看 《High Performance JavaScript》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具