[英]Using $env:USERNAME or other variables when executing a script
所以我一直在用 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\$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 $command
和Invoke-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
要構建相對於用戶配置文件文件夾的路徑,請使用$env:USERPROFILE
,並將操作拆分為 2 個單獨的步驟:
&
調用運算符調用:# Construct path
$exePath = Join-Path $env:USERPROFILE 'Downloads\executable.exe'
# Invoke executable
& $exePath
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.