原文地址:http://www.pstips.net/navigating-the-file-system.html
PowerShell 文件系統(tǒng)系列文章:
PowerShell文件系統(tǒng)(一)前言PowerShell文件系統(tǒng)(二)訪問文件和目錄PowerShell文件系統(tǒng)(三)導(dǎo)航文件系統(tǒng)PowerShell文件系統(tǒng)(四)使用目錄和文件工作PowerShell文件系統(tǒng)(五)管理訪問權(quán)限除非你通過第九章介紹的方式更改了PowerShell控制臺(tái)的提示信息,否則你工作的當(dāng)前目錄會(huì)在控制臺(tái)的命令行開頭顯示。你也可以使用Get-Location命令獲取當(dāng)前工作的目錄。
Get-LocationPath----C:/Users/Mosser Lee/Sources如果你想導(dǎo)航到文件系統(tǒng)的另外一個(gè)位置,可以使用Set-Location或者它的別名Cd:
| 12345678910 | # 進(jìn)入父目錄 (相對(duì)路徑):Cd ..# 進(jìn)入當(dāng)前盤的根目錄 (相對(duì)路徑):Cd /# 進(jìn)入指定目錄 (絕對(duì)路徑):Cd c:/windows# 從環(huán)境變量中獲取系統(tǒng)目錄 (絕對(duì)路徑):Cd $env:windir# 從普通變量中獲取目錄 (絕對(duì)路徑):Cd $home |
路徑的指定可以是相對(duì)路徑,也可以是絕對(duì)路徑。在上面的最后一個(gè)例子中,兼而有之這兩種路徑。相對(duì)路徑依賴你當(dāng)前的路徑,比如./test.txt文件總是指定的是當(dāng)前目錄中的test.txt文件,而../test.txt指定的是父目錄的test.txt文件。相對(duì)路徑通常比較實(shí)用,比如你想使用的腳本庫(kù)位于當(dāng)前工作目錄,你就可以在不引入其它目錄的情況下,直接工作。而絕對(duì)路徑通常具有唯一性,并且獨(dú)立于你當(dāng)前的目錄。
用于指定相對(duì)路徑的四個(gè)重要的特殊字符 | |||
字符 | 意義 | 示例 | 示例描述 |
. | 當(dāng)前目錄 | Ii . | 用資源瀏覽器打開當(dāng)前目錄 |
.. | 父目錄 | Cd .. | 切換到父目錄 |
/ | 驅(qū)動(dòng)器根目錄 | Cd / | 切換到驅(qū)動(dòng)器的頂級(jí)根目錄 |
~ | 家目錄 | Cd ~ | 切換到PowerShell初始化的目錄 |
當(dāng)你使用相對(duì)路徑時(shí),PowerShell必須將這些相對(duì)轉(zhuǎn)換成絕對(duì)路徑。在你使用相對(duì)路徑執(zhí)行一個(gè)文件或者一條命令時(shí),該轉(zhuǎn)換會(huì)自動(dòng)發(fā)生。你也可以自己使用Resolve-Path命令來處理。
PS C:/Users/Mosser> Resolve-Path ./a.pngPath----C:/Users/Mosser/a.png然而,Resolve-Path命令只有在文件確實(shí)存在時(shí),才會(huì)有效。如果你的當(dāng)前文件夾中沒有一個(gè)名為a.png的是,Resolve-Path名諱報(bào)錯(cuò)。
如果你指定的路徑中包含了通配符,Resolve-Path還可以返回多個(gè)結(jié)果。下面的命令執(zhí)行后,會(huì)獲取PowerShell家目錄下面的所有的ps1xml文件的名稱。
PS> Resolve-Path $pshome/*.ps1xmlPath----C:/Windows/System32/WindowsPowerShell/v1.0/Certificate.format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/Diagnostics.Format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/DotNetTypes.format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/Event.Format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/FileSystem.format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/getevent.types.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/Help.format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/HelpV3.format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/PowerShellCore.format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/PowerShellTrace.format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/Registry.format.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/types.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/typesv3.ps1xmlC:/Windows/System32/WindowsPowerShell/v1.0/WSMan.Format.ps1xml像Dir一樣,Resolve-Path可以在下行函數(shù)中扮演選擇過濾器的的角色。下面的例子會(huì)演示在記事本中打開一個(gè)文件進(jìn)行處理。命令調(diào)用記事本程序通過Resolve-Path打開這個(gè)文件。
| 1 | notepad.exe (Resolve-Path $pshome/types.ps1xml).PRoviderpath |
如果沒有符合標(biāo)準(zhǔn)的文件,Resolve-Path會(huì)拋出一個(gè)異常,記錄在$?變量中(第十一章),在錯(cuò)誤發(fā)生時(shí)表達(dá)式!$?一直會(huì)統(tǒng)計(jì),在True的情況下,代表可能沒找到文件。
如果Resolve-Path找到了多個(gè)文件會(huì)把它保存在一個(gè)數(shù)組中,這樣的化會(huì)有很多不期望的文件被打開。函數(shù)使用了第六章講到的PowerShell 內(nèi)部的函數(shù)PromptForChoice(),來請(qǐng)求用戶做出選擇。
| 123456789101112131415161718192021222324252627282930313233343536373839404142 | functionedit-file([string]$path=$(Throw "請(qǐng)輸入相對(duì)路徑!")){# 處理相對(duì)路徑,并抑制錯(cuò)誤$files= Resolve-Path$path -ea SilentlyContinue# 驗(yàn)證是否有錯(cuò)誤產(chǎn)生:if(!$?){# 如果是,沒有找到符合標(biāo)準(zhǔn)的文件,給出提醒并停止:"沒有找到符合標(biāo)準(zhǔn)的文件.";break}# 如果返回結(jié)果為數(shù)組,表示有多個(gè)文件:if($files-is [array]){# 此種情況下,列出你想打開的文件:Write-Host-foregroundColor "Red" -backgroundColor "White" `"你想打開這些文件嗎?"foreach($filein $files){"- " + $file.Path} # 然后確認(rèn)這些文件是否為用戶想打開的:$yes= ([System.Management.Automation.Host.ChoiceDescription]"&yes")$no= ([System.Management.Automation.Host.ChoiceDescription]"&no")$choices= [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no)$result= $host.ui.PromptForChoice('Open files','Open these files?',$choices,1)# 如果用戶確認(rèn),使用"&"操作符啟動(dòng)所有的文件if($result-eq 0){foreach($filein $files){& $file}}}else{# 如果是單個(gè)文件,可以直接使用"&"啟動(dòng):& $files}} |
當(dāng)前的目錄可以使用Push-Location命令保存到目錄堆棧的頂部,每一個(gè)Push-Location都可以將新目錄添加到堆棧的頂部。使用Pop-Location可以返回。
因此,如果你要運(yùn)行一個(gè)任務(wù),不得不離開當(dāng)前目錄,可以在運(yùn)行任務(wù)前將用Push-Location存儲(chǔ)當(dāng)前路徑,然后運(yùn)行結(jié)束后再使用Pop-Location返回到當(dāng)前目錄。Cd $home總是會(huì)返回到你的家目錄,Push-Location 和 Pop-Location支持堆棧參數(shù)。這使得你可以創(chuàng)建很多堆棧,比如一個(gè)任務(wù),一個(gè)堆棧。Push-Location -stack job1會(huì)把當(dāng)前目錄保存到j(luò)ob1堆棧中,而不是標(biāo)準(zhǔn)堆棧中。當(dāng)然在你想重新回到這個(gè)位置時(shí),也需要在Pop-Location中指定這個(gè)參數(shù)-stack job1。
Windows使用了很多特殊的目錄,根據(jù)系統(tǒng)的安裝,可能稍有不同。一些非常重要的目錄的路徑同時(shí)也保存在Windows環(huán)境變量中,這樣PowerShell 可以非常方便和清晰的訪問它們。你也可以使用.NET framework中的Environment類去訪問其它特殊目錄。
存儲(chǔ)在環(huán)境變量中的Windows特殊目錄 | ||
特殊目錄 | 描述 | 示例 |
| application data | 存儲(chǔ)在本地機(jī)器上的應(yīng)用程序數(shù)據(jù) | $env:localappdata |
| User profile | 用戶目錄 | $env:userprofile |
| Data used incommon | 應(yīng)用程序公有數(shù)據(jù)目錄 | $env:commonprogramfiles |
| Public directory | 所有本地用戶的公有目錄 | $env:public |
| Program directory | 具體應(yīng)用程序安裝的目錄 | $env:programfiles |
| Roaming Profiles | 漫游用戶的應(yīng)用程序數(shù)據(jù) | $env:appdata |
| Temporary files(private) | 當(dāng)前用戶的臨時(shí)目錄 | $env:tmp |
| Temporary files | 公有臨時(shí)文件目錄 | $env:temp |
| Windows directory | Windows系統(tǒng)安裝的目錄 | $env:windir |
環(huán)境變量返回的只是其中一部分,還不是全部的特殊目錄。比如如果你想將某個(gè)文件放到一個(gè)用戶的桌面,你需要的路徑在環(huán)境變量中是無法獲取的。但是你可以使用.NET的方法environment類下面的GetFolderPath()方法。下面會(huì)演示如何在桌面上創(chuàng)建一個(gè)快捷方式。
| 1234567 | # 在桌面上創(chuàng)建一個(gè)快捷方式:$path= [Environment]::GetFolderPath("Desktop") + "/EditorStart.lnk"$comobject= New-Object-comObject WScript.Shell$link= $comobject.CreateShortcut($path)$link.targetpath = "notepad.exe"$link.IconLocation = "notepad.exe,0"$link.Save() |
GetFolderPath()目錄的類型可以在枚舉值SpecialFolder中找到。你可以使用下面一行腳本查看它的內(nèi)容。
PS> [System.Environment+SpecialFolder] | Get-Member -static -memberType Property | select -ExpandProperty NameAdminToolsApplicationDataCDBurningCommonAdminToolsCommonApplicationDataCommonDesktopDirectoryCommonDocumentsCommonMusicCommonOemLinksCommonPicturesCommonProgramFilesCommonProgramFilesX86CommonProgramsCommonStartMenuCommonStartupCommonTemplatesCommonVideosCookiesDesktopDesktopDirectoryFavoritesFontsHistoryInternetCacheLocalApplicationDataLocalizedResourcesMyComputerMyDocumentsMyMusicMyPicturesMyVideosNetworkShortcutsPersonalPrinterShortcutsProgramFilesProgramFilesX86ProgramsRecentResourcesSendToStartMenuStartupSystemSystemX86TemplatesUserProfileWindows如果你想預(yù)覽所有GetFolderPath()支持的目錄內(nèi)容,可以使用下面的例子:
[System.Environment+SpecialFolder] |Get-Member -static -memberType Property |ForEach-Object { "{0,-25}= {1}" -f $_.name, [Environment]::GetFolderPath($_.Name) }AdminTools = C:/Users/mosser/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Administrative ToolApplicationData = C:/Users/mosser/AppData/RoamingCDBurning = C:/Users/mosser/AppData/Local/Microsoft/Windows/Burn/BurnCommonAdminTools = C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Administrative ToolsCommonApplicationData = C:/ProgramDataCommonDesktopDirectory = C:/Users/Public/DesktopCommonDocuments = C:/Users/Public/DocumentsCommonMusic = C:/Users/Public/MusicCommonOemLinks =CommonPictures = C:/Users/Public/PicturesCommonProgramFiles = C:/Program Files/Common FilesCommonProgramFilesX86 = C:/Program Files (x86)/Common FilesCommonPrograms = C:/ProgramData/Microsoft/Windows/Start Menu/ProgramsCommonStartMenu = C:/ProgramData/Microsoft/Windows/Start MenuCommonStartup = C:/ProgramData/Microsoft/Windows/Start Menu/Programs/StartupCommonTemplates = C:/ProgramData/Microsoft/Windows/TemplatesCommonVideos = C:/Users/Public/VideosCookies = C:/Users/mosser/AppData/Local/Microsoft/Windows/INetCookiesDesktop = C:/Users/mosser/DesktopDesktopDirectory = C:/Users/mosser/DesktopFavorites = C:/Users/mosser/FavoritesFonts = C:/WINDOWS/FontsHistory = C:/Users/mosser/AppData/Local/Microsoft/Windows/HistoryInternetCache = C:/Users/mosser/AppData/Local/Microsoft/Windows/INetCacheLocalApplicationData = C:/Users/mosser/AppData/LocalLocalizedResources =MyComputer =MyDocuments = C:/Users/mosser/DocumentsMyMusic = C:/Users/mosser/MusicMyPictures = C:/Users/mosser/PicturesMyVideos = C:/Users/mosser/VideosNetworkShortcuts = C:/Users/mosser/AppData/Roaming/Microsoft/Windows/Network ShortcutsPersonal = C:/Users/mosser/DocumentsPrinterShortcuts = C:/Users/mosser/AppData/Roaming/Microsoft/Windows/Printer ShortcutsProgramFiles = C:/Program FilesProgramFilesX86 = C:/Program Files (x86)Programs = C:/Users/mosser/AppData/Roaming/Microsoft/Windows/Start Menu/ProgramsRecent = C:/Users/mosser/AppData/Roaming/Microsoft/Windows/RecentResources = C:/WINDOWS/resourcesSendTo = C:/Users/mosser/AppData/Roaming/Microsoft/Windows/SendToStartMenu = C:/Users/mosser/AppData/Roaming/Microsoft/Windows/Start MenuStartup = C:/Users/mosser/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/StartupSystem = C:/WINDOWS/system32SystemX86 = C:/WINDOWS/SysWOW64Templates = C:/Users/mosser/AppData/Roaming/Microsoft/Windows/TemplatesUserProfile = C:/Users/mosserWindows = C:/WINDOWS構(gòu)造路徑
路徑名稱由文本構(gòu)成,能讓你隨心所欲地構(gòu)造他們。你也應(yīng)當(dāng)看到了上面例子中構(gòu)造用戶桌面快捷方式的過程了:
path = [Environment]::GetFolderPath("Desktop") + "/file.txt"$pathC:/Users/mosser/Desktop/file.txt一定要確保你的路徑中的反斜杠個(gè)數(shù)正確。這也就是為什么前面的例子中在file.txt前面使用了一個(gè)反斜杠。還有一個(gè)更可靠的方式,就是使用命令 Join-Path方法,或者.NET中的Path靜態(tài)類。
path = Join-Path ([Environment]::GetFolderPath("Desktop")) "test.txt"$pathC:/Users/mosser/Desktop/test.txt$path = [System.IO.Path]::Combine([Environment]::`GetFolderPath("Desktop"), "test.txt")$pathC:/Users/mosser/Desktop/test.txtPath類還包含了許多用來合并或者獲取目錄特定信息的額外方法。你只需要在下面表格中列出的方法中前加[System.IO.Path]::,比如:
| 12 | [System.IO.Path]::ChangeExtension("test.txt", "ps1")test.ps1 |
構(gòu)造路徑的方法 | ||
| 方法 | 描述 | 示例 |
| ChangeExtension() | 更改文件的擴(kuò)展名 | ChangeExtension(“test.txt”, “ps1”) |
| Combine() | 拼接路徑字符串; 對(duì)應(yīng)Join-Path | Combine(“C:/test”, “test.txt”) |
| GetDirectoryName() | 返回目錄對(duì)象:對(duì)應(yīng)Split-Path -parent | GetDirectoryName(“c:/test/file.txt”) |
| GetExtension() | 返回文件擴(kuò)展名 | GetExtension(“c:/test/file.txt”) |
| GetFileName() | 返回文件名:對(duì)應(yīng)Split-Path -leaf | GetFileName(“c:/test/file.txt”) |
| GetFileNameWithoutExtension() | 返回不帶擴(kuò)展名的文件名 | GetFileNameWithoutExtension(“c:/test/file.txt”) |
| GetFullPath() | 返回絕對(duì)路徑 | GetFullPath(“./test.txt”) |
| GetInvalidFileNameChars() | 返回所有不允許出現(xiàn)在文件名中字符 | GetInvalidFileNameChars() |
| GetInvalidPathChars() | 返回所有不允許出現(xiàn)在路徑中的字符 | GetInvalidPathChars() |
| GetPathRoot() | 返回根目錄:對(duì)應(yīng)Split-Path -qualifier | GetPathRoot(“c:/test/file.txt”) |
| GetRandomFileName() | 返回一個(gè)隨機(jī)的文件名 | GetRandomFileName() |
| GetTempFileName() | 在臨時(shí)目錄中返回一個(gè)臨時(shí)文件名 | GetTempFileName() |
| GetTempPath() | 返回臨時(shí)文件目錄 | GetTempPath() |
| HasExtension() | 如果路徑中包含了擴(kuò)展名,則返回True | HasExtension(“c:/test/file.txt”) |
| IsPathRooted() | 如果是絕對(duì)路徑,返回為True; Split-Path -isAbsolute | IsPathRooted(“c:/test/file.txt”) |
原文地址:Working with the File System
本文鏈接: http://www.pstips.net/navigating-the-file-system.html請(qǐng)尊重原作者和編輯的辛勤勞動(dòng),歡迎轉(zhuǎn)載,并注明出處!新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注