文章出處

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運行的結果如圖

 


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()