无法识别新对象

时间:2018-12-30 13:17:16

标签: powershell

我想运行一个即使关闭终端窗口也将继续执行的脚本。

我在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

1 个答案:

答案 0 :(得分:0)

抛开代码中的错别字,如果您仔细看看引发错误的语句,就会很明显地看到发生了什么:

+ 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之前,在该字符串 中扩展 all 个变量。未定义的变量将扩展为空字符串,从而使您无法执行完整的命令行。变量扩展还会导致您的代码出现另一个问题,因为用作字符串DownloadFile()的变量也是 扩展了 ,然后将字符串传递给{ {1}}。但是,Start-Process期望 strings 不是裸词作为其参数。

您可以通过以下方法解决此问题:将DownloadFile()转义到变量内部中定义的变量中,并为$的参数加上引号:

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
相关问题