[英]PowerShell Script Error in command but works in ISE
I am running a script in the ISE that essentially downloads a file from a public site:我在 ISE 中运行一个脚本,该脚本实质上是从公共站点下载文件:
#This PowerShell code scrapes the site and downloads the latest published file.
Param(
$Url = 'https://randomwebsite.com',
$DownloadPath = "C:\Downloads",
$LocalPath = 'C:\Temp',
$RootSite = 'https://publicsite.com',
$FileExtension = '.gz'
)
#Define the session cookie used by the site and automate acceptance. $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$cookie = New-Object System.Net.Cookie
$cookie.Name = "name"
$cookie.Value = "True"
$cookie.Domain = "www.public.com"
$session.Cookies.Add($cookie);
$FileNameDate = Get-Date -Format yyyyMMdd
$DownloadFileName = $DownloadPath + $FileNameDate + $FileExtension
$DownloadFileName
TRY{
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$WebSite = Invoke-WebRequest $Url -WebSession $session -UseBasicParsing #this gets the links we need from the main site.
$Table = $WebSite.Links | Where-Object {$_.href -like "*FetchDocument*"} | fl href #filter the results that we need.
#Write-Output $Table
$FilterTable=($Table | Select-Object -Unique | sort href -Descending) | Out-String
$TrimString = $FilterTable.Trim()
$FinalString = $RootSite + $TrimString.Trim("href :")
#Write-Verbose $FinalString | Out-String
#Start-Process powershell.exe -verb RunAs -ArgumentList "-File C:\some\path\base_server_settings.ps1" -Wait
Invoke-WebRequest $FinalString -OutFile $DownloadFileName -TimeoutSec 600
$ExpectedFileName = Get-ChildItem | Sort-Object LastAccessTime -Descending | Select-Object -First 1 $DownloadPath.Name | SELECT Name
$ExpectedFileName
Write-Host 'The latest DLA file has been downloaded and saved here:' $DownloadFileName -ForegroundColor Green
}
CATCH{
[System.Net.WebException],[System.IO.IOException]
Write "An error occured while downloading the latest file."
Write $_.Exception.Message
}
Expectation is that it downloads a file into the downloads folder and does in fact download the file when using the ISE.预期是它将文件下载到下载文件夹中,并且在使用 ISE 时实际上会下载该文件。
When I try to run this as a command however (PowerShell.exe -file "/path/script.ps1) I get an error stating:但是,当我尝试将其作为命令运行时(PowerShell.exe -file "/path/script.ps1),我收到一条错误消息:
An error occurred while downloading the latest file.下载最新文件时出错。 Operation is not valid due to the current state of the object.
由于 object 的当前 state,操作无效。
out-lineoutput: The object of type "Microsoft.PowerShell.Commands.Internal.Format.GroupEndData" is not valid or not in the correct sequence.
out-lineoutput:“Microsoft.PowerShell.Commands.Internal.Format.GroupEndData”类型的 object 无效或顺序不正确。 This is likely caused by a user-specified "format-*" command which is conflicting with the default formatting.
这可能是由用户指定的“format-*”命令与默认格式冲突引起的。 At \path\to\file\AutomatedFileDownload.ps1:29 char:9
在 \path\to\file\AutomatedFileDownload.ps1:29 char:9
$FilterTable=($Table | Select-Object -Unique | sort href -Des...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- CategoryInfo: InvalidData: (:) [out-lineoutput], InvalidOperationException
CategoryInfo: InvalidData: (:) [out-lineoutput], InvalidOperationException
- FullyQualifiedErrorId: ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand
FullyQualifiedErrorId:ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand
I found several articles describing using the MTA or STA switch and I have tried to add in -MTA or -STA to the command, but it still gives me the same error in the command.我发现了几篇描述使用 MTA 或 STA 开关的文章,并且我尝试将 -MTA 或 -STA 添加到命令中,但它仍然在命令中给我同样的错误。
As commented, you are trying to get one link from the website, but pipe your commande to things like Format-List
and Out-String
, rendering the result to either nothing at all or as a single multiline string.. In both cases, this won't get you what you are after.正如评论的那样,您正在尝试从网站获取一个链接,但是 pipe 您对
Format-List
和Out-String
之类的命令,将结果呈现为根本没有或作为单个多行字符串。在这两种情况下,这不会得到你所追求的。
Not knowing the actual values of the linksof course, I suggest you try this:当然不知道链接的实际值,我建议你试试这个:
Param(
$Url = 'https://randomwebsite.com',
$DownloadPath = "C:\Downloads",
$LocalPath = 'C:\Temp',
$RootSite = 'https://publicsite.com',
$FileExtension = '.gz'
)
# test if the download path exists and if not, create it
if (!(Test-Path -Path $DownloadPath -PathType Container)){
$null = New-Item -Path $DownloadPath -ItemType Directory
}
#Define the session cookie used by the site and automate acceptance.
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$cookie = New-Object System.Net.Cookie
$cookie.Name = "name"
$cookie.Value = "True"
$cookie.Domain = "www.public.com"
$session.Cookies.Add($cookie);
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
try {
$WebSite = Invoke-WebRequest -Uri $Url -WebSession $session -UseBasicParsing -ErrorAction Stop #this gets the links we need from the main site.
# get the file link
$lastLink = ($WebSite.Links | Where-Object {$_.href -like "*FetchDocument*"} | Sort-Object href -Descending | Select-Object -First 1).href
# create the file URL
$fileUrl = "$RootSite/$lastLink"
# create the full path and filename for the downloaded file
$DownloadFileName = Join-Path -Path $DownloadPath -ChildPath ('{0:yyyyMMdd}{1}' -f (Get-Date), $FileExtension)
Write-Verbose "Downloading $fileUrl as '$DownloadFileName'"
Invoke-WebRequest -Uri $fileUrl -OutFile $DownloadFileName -TimeoutSec 600 -ErrorAction Stop
# test if the file is downloaded
if (Test-Path -Path $DownloadFileName -PathType Leaf) {
Write-Host "The latest DLA file has been downloaded and saved here: $DownloadFileName" -ForegroundColor Green
}
else {
Write-Warning "File '$DownloadFileName' has NOT been downloaded"
}
}
catch [System.Net.WebException],[System.IO.IOException]{
Write-Host "An error occured while downloading the latest file.`r`n$($_.Exception.Message)" -ForegroundColor Red
}
catch {
Write-Host "An unknown error occured while downloading the latest file.`r`n$($_.Exception.Message)" -ForegroundColor Red
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.