PowerShell~文件操作和对象遍历
生活随笔
收集整理的這篇文章主要介紹了
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 Yellowremove-item -path $outPath -Force -Recurse -ErrorAction SilentlyContinue #先刪除先來的文件夾及內容Write-Host "Publishing $projectPathAndFile to $outPath" -ForegroundColor YellowNew-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運行的結果如圖
?本文轉自博客園張占嶺(倉儲大叔)的博客,原文鏈接:PowerShell~文件操作和對象遍歷,如需轉載請自行聯系原博主。
總結
以上是生活随笔為你收集整理的PowerShell~文件操作和对象遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win10电脑锁屏设置的方法是什么
- 下一篇: jsp中引入js文件缓存问题解决