所以我一直在用 powershell 撰寫一個腳本,我想做一些改動,讓人們可以用最少的努力來使用它。其中一部分包括調整腳本,以便將路徑中我的用戶名實體替換為$env:USERNAME.
例如,C:\Users\{username}\Downloads\executable.exe
會成為C:\Users\$env:USERNAME\Downloads\executable.exe
結果是一樣的。
我反復收到錯誤The term 'C:\Users\$env:USERNAME\Downloads\executable.exe' 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.
當我將它作為分配變數的一部分呼叫時,我得到The term C:\Users\{username}\Downloads\executable.exe is not ...,因此在這種情況下正確處理了路徑。
我之前在 bash 中的路徑中使用了變數,但問題為 0,所以我不確定我哪里出錯了。
我已經嘗試將它分配給一個變數并呼叫它,并$env:USERNAME在路徑中分配和包含該變數,但都沒有奏效。
我也試過用$env:HOMEPATH。
我嘗試將變數分配為字串(帶雙引號),并使用Invoke-command $commandandInvoke-Expression $command但沒有骰子。
如何使用路徑名中的變數執行腳本或可執行檔案?這在powershell中可能嗎?
Mathias R. Jensen 的回答解決了我的問題,我的代碼現在可以作業了。
#Constructed path as advised
$TestPath = Join-Path $env:USERPROFILE \Downloads\executable.exe
Get-date | Out-File -FilePath $env:USERPROFILE\test\testfile.txt -Append
#Invoked executable
& $TestPath | Out-File -FilePath $env:USERPROFILE\test\testfile.txt -Append
uj5u.com熱心網友回復:
要構建相對于用戶組態檔檔案夾的路徑,請使用$env:USERPROFILE并將操作拆分為 2 個單獨的步驟:
- 構建可執行檔案的路徑
- 使用
&呼叫操作員呼叫:
# Construct path
$exePath = Join-Path $env:USERPROFILE 'Downloads\executable.exe'
# Invoke executable
& $exePath
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490708.html
標籤:电源外壳 壳 命令行界面 powershell-5.0
