列出一个路径下的所有文件名,或者文件夹名,或者所有名字
$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