這是我的兩個腳本。第一個顯示包含多個檔案的目錄串列。第二個只是一個測驗,因為我以前從未使用$PSScriptRoot過。
Get-ChildItem -Path $PSScriptRoot -Directory -Name -Recurse |
Write-Output
Where-Object { (Get-ChildItem $_ -File).Count -ge 2 }|
ForEach-Object { ".\$_"} |
Invoke-Item
# If running in the console, wait for input before closing.
if ($Host.Name -eq "ConsoleHost")
{
Write-Host "Press any key to continue..."
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
Write-Output $PSScriptRoot
# If running in the console, wait for input before closing.
if ($Host.Name -eq "ConsoleHost")
{
Write-Host "Press any key to continue..."
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
一開始,我沒有-Path $PSScriptRoot,我使用背景關系選單中的“Run with Powershell”運行我的腳本。這樣腳本似乎使用腳本目錄作為作業目錄。當我將默認應用程式更改為 PowerShell 時,它開始使用 PowerShell 的安裝目錄作為作業目錄。所以我補充說-Path $PSScriptRoot,現在第一個腳本不起作用;它會打開一個控制臺并立即關閉它。第二個腳本作業得很好。
此外,如果我使用背景關系選單“使用 Powershell 運行”,第一個腳本仍然可以正常運行。
我在第一個腳本中做錯了什么?
uj5u.com熱心網友回復:
我猜你的腳本路徑中有空格。問題與 Windows 將檔案引數傳遞給應用程式的方式以及決議腳本路徑的方式有關。
當您使用“Run with Powershell”運行腳本時,以下命令將發送到 shell:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & 'C:\Temp\with spaces\scriptRoot.ps1'"
您會注意到該命令用引號括起來。這意味著 shell 會將參考的部分作為引數傳遞給 powershell 可執行檔案,并有效地去除外部"引號。因此,powershell 將其視為命令:
if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & 'C:\Temp\with spaces\scriptRoot.ps1'
現在您會注意到腳本的路徑仍然用單引號括起來,即使路徑有空格,一切仍然有效。
當您以“打開方式...”powershell 運行腳本時,windows(資源管理器外殼)只會將路徑傳遞給用引號括起來的腳本。它看起來像這樣:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "C:\Temp\with spaces\scriptRoot.ps1"
如果我打開命令提示符并嘗試運行上述命令,我會得到以下資訊:
#>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "C:\Temp\with spaces\scriptRoot.ps1"
C:\Temp\with : The term 'C:\Temp\with' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
C:\Temp\with spaces\scriptRoot.ps1
~~~~~~~~~~~~
CategoryInfo : ObjectNotFound: (C:\Temp\with:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
那是因為 powershell 本身永遠不會看到外部引號。如果我添加一個額外的層,''它的作業原理:
#>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "'C:\Temp\with spaces\scriptRoot.ps1'"
C:\Temp\with spaces\scriptRoot.ps1
不幸的是,除了擺脫路徑中的空格之外,我不知道如何解決這個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/333060.html
標籤:电源外壳
上一篇:PowerShell不洗掉換行符
