【PowerShell 一天一練】 2. 建立資料夾
阿新 • • 發佈:2019-01-25
【2. 建立資料夾】
New-Item 方法登場了,它的作用可不止建立資料夾,據說還可以建立登錄檔項等等。它的 -type 引數可以指定要建立的型別,-path 指定要在什麼位置建立, -name 則指定要建立東西的名字,可以猜到 -value 會指定建立的內容(對文件,可以是它的內容;對目錄,則不需要了)。
一個例子:
new-item -path c:/ -name logfiles -type directory
[在c盤下建立名為logfiles的資料夾]
不過咱志不止於此,還想用當前的日期來建立資料夾,並且如果存在該資料夾就不建立了……呵呵有點麻煩了。
得到日期很簡單:
get-date
順帶說一下它相關的引數 -displayHint date 是說就顯示日期部分就好了,否則get-date預設是得到日期和時間的(當然你還可以進一步用 -format 來格式化得到的日期格式)
不過判斷某個資料夾是否存在,就要用到流程控制關鍵字 if 了。
抄一段 if 的語法
if (<test1>)
{<code_block1>}
[elseif (<test2)
{<code_block2>}]
[else
<code_block3>}]
呵呵還好和一般的程式語言裡的if沒啥區別。
昨天的說到Get-Item對用法,今天剛好拿來:
Get-ChildItem -name * -include $dateText
用 $dateText 變數儲存前面獲得的日期,用Get-ChildItem來獲得該名字對應的資料夾名字,然後……嗯累了嘿嘿,具體解釋明天補上。
$dateText = get-date $dateText = $dateText.ToShortDateString() #轉為短日期格式(去掉時間部分) $file = Get-ChildItem -name * -include $dateText if ( $file.count -eq $null ) # 井號是註釋符, $null是預定義的變數,代表空