PowerShell~文件操作和对象遍历
生活随笔
收集整理的這篇文章主要介紹了
PowerShell~文件操作和对象遍历
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
ps提供了豐富的文件操作,如建立,刪除,改名,移動(dòng),復(fù)制,文件夾建立,顯示文件列表,同時(shí)對(duì)數(shù)組對(duì)象的遍歷也很方便,如果在使用PS腳本時(shí),希望現(xiàn)時(shí)傳入?yún)?shù),可以把參數(shù)聲明為param,當(dāng)然需要把它寫(xiě)在文件開(kāi)頭的位置。
下面是大叔在看完eshop項(xiàng)目后,寫(xiě)的幾個(gè)測(cè)試代碼,對(duì)它們進(jìn)行了注釋,方便大家學(xué)習(xí)。
Param([string] $rootPath) #輸入?yún)?shù) $scriptPath = Split-Path $script:MyInvocation.MyCommand.Path #當(dāng)前應(yīng)用程序目錄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 #先刪除先來(lái)的文件夾及內(nèi)容Write-Host "Publishing $projectPathAndFile to $outPath" -ForegroundColor YellowNew-Item $outPath -type directory -Force #建立文件夾 Copy-Item $projectPathAndFile -Destination $outPath # 復(fù)制到指定位置# dotnet restore $projectPathAndFile# dotnet build $projectPathAndFile# dotnet publish $projectPathAndFile -o $outPath }$test=1,2,3 #定義簡(jiǎn)單類型數(shù)組 $test | foreach{ Write-Host $_ #遍歷每個(gè)元素 }$testObj=@{name="zzl";age=34},@{name="zhz";age=8} #定義一個(gè)對(duì)象數(shù)組 $testObj | foreach{ $name= $_.name #必須將它賦給一個(gè)變量,如果直接在字符串里使用,它將輸出自己的類型 $age=$_.age Write-Host "name=$name,age=$age" }上面代碼會(huì)在E盤指定目錄進(jìn)行文件的復(fù)制,這類似于網(wǎng)站的發(fā)布機(jī)制,從一個(gè)地方復(fù)制到網(wǎng)站目錄。
其中param要求我們?cè)谑褂胮s1文件時(shí),提供一下參數(shù),當(dāng)然可以不傳,我們代碼里也有對(duì)它的賦值。
整個(gè)DEMO運(yùn)行的結(jié)果如圖
?本文轉(zhuǎn)自博客園張占嶺(倉(cāng)儲(chǔ)大叔)的博客,原文鏈接:PowerShell~文件操作和對(duì)象遍歷,如需轉(zhuǎn)載請(qǐng)自行聯(lián)系原博主。
總結(jié)
以上是生活随笔為你收集整理的PowerShell~文件操作和对象遍历的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: win10电脑锁屏设置的方法是什么
- 下一篇: 完全优化MySQL数据库性能的八大巧方法