列出一個路徑下的所有文件名,或者文件夾名,或者所有名字
$path = "D:\"
Write-Host ("Get file names (not including folder names) only"); Get-ChildItem $path | ForEach-Object -Process{# 注意: { 必須緊跟着 Process if ($_ -is [System.IO.FileInfo]) #如果想要得到文件就用 System.IO.FileInfo { Write-Host ($_.name); } } Write-Host ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Write-Host ("Get all names whatever files or folders."); Get-ChildItem $path | ForEach-Object -Process{ Write-Host ($_.name); } Write-Host ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Write-Host ("Get all folders' names."); Get-ChildItem $path | ForEach-Object -Process{ if ($_ -is [System.IO.DirectoryInfo]) #如果想要得到文件夾,就用 System.IO.DirectoryInfo { Write-Host ("Folder: " + $_.name); } }
如何列出文件的創建時間有關的信息?
$path = "C:\Program Files (x86)\Jenkins\jobs"; Get-ChildItem $path | ForEach-Object -Process{ if($_ -is [System.IO.FileInfo] -and ($_.CreationTime -ge [System.DateTime]::Today)) #如果文件是在今天創建 { Write-Host("File " + $_.name + " is created at " + $_.CreationTime); } if ($_ -is [System.IO.DirectoryInfo] -and ($_.CreationTime -ge (Get-Date).Date.AddDays(-1)))#如果文件夾是在過去一天內創建 { Write-Host ("Folder " + $_.name + " is created at " + $_.CreationTime) } }
也看到用下面方法找到文件或者文件夾的:
#找出D盤根目錄下的所有文件
Get-ChildItem d:\ | ?{$_.psiscontainer -eq $false} #如果是 true 則為文件夾
另外,如果想遍歷一個文件夾的所有子文件夾和文件,可以用 --recurse
Get-ChildItem -Recurse
如何定義一個常量?
New-Variable var1 -Value "apple" -Option Constant
$var1
如何定義一個變量?
很簡單,
$var = "2"
$var
$var = "3"
$var
輸出:
2
3
其實變量有很多作用域,根據http://www.pstips.net/powershell-scope-of-variables.html,可以有下面的修飾符:$global, $private, $local, $script
定義數組?
$family = "0allen", "1jenny", "2alex", "3jessica"
$family[0]
$family[2]
Write-Host ("----")
$family[0, 1,3]
$family.Count
$family[$family.Count - 2]
Write-Host ("----")
#將數組逆序輸出
$family[($family.Count)..0]
Write-Host ("----")
$family[2..0]
Write-Host ("----")
#添加數組元素
$family+="4song";
$family;
Write-Host ("----")
#刪除數組元素
$family= $family[0..2]+$family[4]
$family
結果:
0allen
2alex
----
0allen
1jenny
3jessica
4
2alex
----
3jessica
2alex
1jenny
0allen
----
2alex
1jenny
0allen
----
0allen
1jenny
2alex
3jessica
4song
----
0allen
1jenny
2alex
4song