![](/img/trans.png)
[英]New-Object : The term New-Object is not recognized as the name of a cmdlet
[英]New-Object not recognized
我想運行即使關閉終端窗口也將繼續執行的腳本。
我在PowerShell 2.0上使用以下命令從Internet下載文件:
$fyle = New-Object System.Net.WebClient;
$fyle.DownloadFile($url, $dest);
下面的腳本下載並運行.ps1腳本,由於我必須等待文件下載,因此我可以關閉窗口,但不能立即關閉。
$fyle = New-Object System.Net.WebClient;
$fyle.DownloadFile($url, $dest_filename);
Start-Process cmd -ArgumentList " /c start /min powershell -Exec Bypass $dest_filename" -NoNewWindow
為了解決這個問題,我所做的就是將$fyle
放在Start-Process
塊中:
$url = "https://google.com";
$dir = "$env:userprofile/adir";
$dest_filename = "$dir/script.ps1";
Start-Process cmd -ArgumentList " /c start powershell -Exec Bypass mkdir $dir; $fyle=New-Object System.Net.WebClient; $fyl.DownloadFile($url,$dest_filename); $dest_filename"
但是,我收到此錯誤:
The term '=New-Object' 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:40 + mkdir C:\Users\IEUser/adir; =New-Object <<<< System.Net.WebClient; .DownloadFile(https://google.com,C:\Users\IEUser/adir/script.ps1); C:\Users\IEUser/adir/script.ps1 + CategoryInfo : ObjectNotFound: (=New-Object:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
除了代碼中的錯別字外,如果您仔細查看引發錯誤的語句,就會很明顯地看到發生了什么:
+ mkdir C:\Users\IEUser/adir; =New-Object <<<< System.Net.WebClient; .DownloadFile(https://google.com,C:\Users\IEUser/adir/script.ps1); C:\Users\IEUser/adir/script.ps1 ^^ ^^
您要使用的變量在我上面指出的位置缺失。 沒有變量,語句將成為不完整的命令,從而引發您觀察到的錯誤。
原因是您要在雙引號字符串中傳遞CMD的參數。 PowerShell的解析器會在將該字符串傳遞給Start-Process
之前擴展該字符串中的所有變量。 未定義的變量將擴展為空字符串,從而使您無法執行完整的命令行。 變量擴展還會導致代碼出現另一個問題,因為用作DownloadFile()
的參數的變量也會 在將字符串傳遞給Start-Process
之前擴展。 但是, DownloadFile()
期望字符串不是裸詞作為參數。
您可以通過轉義您在參數字符串中定義的$
in變量並在DownloadFile()
的參數周圍添加引號來解決此問題:
Start-Process cmd -ArgumentList " /c start powershell -Exec Bypass mkdir $dir; `$fyle=New-Object System.Net.WebClient; `$fyle.DownloadFile('$url','$dest_filename'); $dest_filename"
# ^ ^ ^ ^ ^ ^
更好的是,將參數列表定義為數組,然后將其傳遞給Start-Process
:
$params = '/c', 'start', 'powershell', '-Exec Bypass',
"mkdir $dir;",
'$fyle=New-Object System.Net.WebClient;',
"`$fyle.DownloadFile('$url','$dest_filename');",
"$dest_filename"
Start-Process cmd -ArgumentList $params
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.