我制作了 [1] 接受 2 個引數(又名引數),[2] 更改檔案的修改日期和時間,以及 [3] 向主機寫入內容的 powershell 腳本。以下命令列在 powershell 控制臺中運行良好,但是當我在 Windows cmd 提示符 (DOS) 視窗中運行相同的命令列時會觸發錯誤訊息:
E:\Apps\UtilitiesByMarc\Change_DateTime_for_test1.bat_and_Hello_world_with_2_named_args_aaa.ps1 -dateTimeVarArg "01/11/2005 06:01:36" -file_dateTimeMod_fullname "E:\Apps\Delete01\test1.bat"
以下是我給出長名稱“Change_DateTime_for_test1.bat_and_Hello_world_with_2_named_args_aaa.ps1”的 powershell 腳本的編碼:
param ( [string]$dateTimeVarArg, [string]$file_dateTimeMod_fullname)
Get-ChildItem $file_dateTimeMod_fullname | % {$_.LastWriteTime = $dateTimeVarArg}
#Get-ChildItem "E:\Apps\Delete01\test1.bat" | % {$_.LastWriteTime = $dateTimeVarArg}
$strString = "Hello World"
write-host $strString
function ftest{
$test = "Test"
write-host $test
}
ftest
當我在 Windows DOS 命令提示符設定中運行上面顯示的命令列時,我收到以下錯誤訊息:
Exception setting "LastWriteTime": "Cannot convert null to type "System.DateTime"."
At E:\Apps\UtilitiesByMarc\Change_DateTime_for_test1.bat_and_Hello_world_with_1_named_arg_aaa.ps1:6 char:50
... "E:\Apps\Delete01\test1.bat" | % {$_.LastWriteTime = $dateTimeVarArg}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
FullyQualifiedErrorId : ExceptionWhenSetting
我想知道 [1] 如何更改上面顯示的命令列(在 powershell 控制臺中可以正常作業),以便它可以在 Windows DOS 命令提示符設定中作業,以及 [2] 我可以在其中了解更多關于我的命令的原因行觸發錯誤,以及如何避免它們。
根據命令“Get-Host | Select-Object Version”的輸出,我正在運行版本。5.1.19041.1682。
任何提示將不勝感激。
uj5u.com熱心網友回復:
默認情況下,您不能直接從Windows 舊 shell 或完全從 PowerShell外部執行PowerShell 腳本(.ps1檔案)cmd.exe。
- 嘗試這樣做會打開腳本檔案進行編輯
.ps1,就像從檔案資源管理器/桌面雙擊檔案一樣。
從 PowerShell 本身外部執行.ps1腳本需要使用 PowerShell CLI(powershell.exe對于 Windows PowerShell,pwsh對于 PowerShell (Core) 7 ),在您的情況下,這會轉換為呼叫,例如(可能會呼叫其他 CLI 引數):
powershell.exe -File E:\Apps\UtilitiesByMarc\Change_DateTime_for_test1.bat_and_Hello_world_with_2_named_args_aaa.ps1 -dateTimeVarArg "01/11/2005 06:01:36" -file_dateTimeMod_fullname "E:\Apps\Delete01\test1.bat"
至于你嘗試了什么:
您能夠執行.ps1from的事實cmd.exe表明您更改了此類檔案的檔案型別定義以改為通過執行powershell.exe。
您嘗試傳遞給腳本的引數被忽略的事實- 正如您收到的錯誤訊息所暗示的那樣 - 表明您使用檔案資源管理器的Open with快捷選單命令選擇打開所有.ps1檔案powershell.exe; 所述方法不支持引數傳遞。
有一種方法可以更改檔案型別定義以支持引數傳遞,并且在這個答案中有詳細說明(“程式方法”部分)。
但是,一般來說,我建議不要應用此自定義,尤其是在必須由其他用戶/在其他計算機上運行的批處理檔案中,不能期望這些檔案具有相同的自定義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476849.html
