Download all pdfs on a webpage with PowerShell - powershell

I found online the following code to download all the pdfs on a webpage:
$psPage = Invoke-WebRequest "https://www.pi.infn.it/~rizzo/ingegneria/appunti_fisII_ing_mecc/
"
$urls = $psPage.ParsedHtml.getElementsByTagName("A") | ? {$_.href -like "*.pdf"} | Select-Object -ExpandProperty href
$urls | ForEach-Object {Invoke-WebRequest -Uri $_ -OutFile ($_ | Split-Path -Leaf)}
but PS gave me the error:
Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not
available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing
parameter and try again.
At C:\Users\Raffaele\Desktop\Nuova cartella\a.ps1:1 char:11
+ $psPage = Invoke-WebRequest "https://www.pi.infn.it/~rizzo/ingegneria ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [Invoke-WebRequest], NotSupportedException
+ FullyQualifiedErrorId : WebCmdletIEDomNotSupportedException,Microsoft.PowerShell.Commands.InvokeWebReq
uestCommand
You cannot call a method on a null-valued expression.
At C:\Users\Raffaele\Desktop\Nuova cartella\a.ps1:2 char:1
+ $urls = $psPage.ParsedHtml.getElementsByTagName("A") | ? {$_.href -li ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Split-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\Raffaele\Desktop\Nuova cartella\a.ps1:4 char:66
+ ... h-Object {Invoke-WebRequest -Uri $_ -OutFile ($_ | Split-Path -Leaf)}
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Split-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.S
plitPathCommand
Invoke-WebRequest : Cannot validate argument on parameter 'Uri'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At C:\Users\Raffaele\Desktop\Nuova cartella\a.ps1:4 char:48
+ $urls | ForEach-Object {Invoke-WebRequest -Uri $_ -OutFile ($_ | Spli ...
+ ~~
+ CategoryInfo : InvalidData: (:) [Invoke-WebRequest], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeWebReques
tCommand
How can I overcome this problem? Why it requires internet explorer engine?
EDIT: I tried to modify the code in this way:
$site = "https://www.pi.infn.it/~rizzo/ingegneria/appunti_fisII_ing_mecc/"
$psPage = Invoke-WebRequest -Uri $site -UseBasicParsing
$urls = $psPage.ParsedHtml.getElementsByTagName("A")
$urls | where {$_.pathname -like "*pdf"} | % {Invoke-WebRequest -Uri "$site$($_.pathname)" -OutFile $_.pathname }
and the error is:
You cannot call a method on a null-valued expression.
At C:\Users\Raffaele\Desktop\Nuova cartella\a.ps1:3 char:1
+ $urls = $psPage.ParsedHtml.getElementsByTagName("A")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
EDIT 2 I tried to modify the code in this way. New code:
$psPage = Invoke-WebRequest -Uri -UseBasicParsing "https://www.pi.infn.it/~rizzo/ingegneria/appunti_fisII_ing_mecc/"
$urls = $psPage.ParsedHtml.getElementsByTagName("A") | ? {$_.href -like "*.pdf"} | Select-Object -ExpandProperty href
$urls | ForEach-Object {Invoke-WebRequest -Uri $_ -OutFile ($_ | Split-Path -Leaf)}
The Windows PowerShell gave me a new error:
Invoke-WebRequest : Missing an argument for parameter 'Uri'. Specify a parameter of type 'System.Uri' and
try again.
At C:\Users\Raffaele\Desktop\Nuova cartella\b.ps1:1 char:29
+ $psPage = Invoke-WebRequest -Uri -UseBasicParsing "https://www.pi.inf ...
+ ~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
You cannot call a method on a null-valued expression.
At C:\Users\Raffaele\Desktop\Nuova cartella\b.ps1:2 char:1
+ $urls = $psPage.ParsedHtml.getElementsByTagName("A") | ? {$_.href -li ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Split-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\Raffaele\Desktop\Nuova cartella\b.ps1:3 char:66
+ ... h-Object {Invoke-WebRequest -Uri $_ -OutFile ($_ | Split-Path -Leaf)}
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Split-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.S
plitPathCommand
Invoke-WebRequest : Cannot validate argument on parameter 'Uri'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At C:\Users\Raffaele\Desktop\Nuova cartella\b.ps1:3 char:48
+ $urls | ForEach-Object {Invoke-WebRequest -Uri $_ -OutFile ($_ | Spli ...
+ ~~
+ CategoryInfo : InvalidData: (:) [Invoke-WebRequest], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeWebReques
tCommand

In your way : First you have to remove "about:" in your URL or replace it by nothing :
$site = "https://www.pi.infn.it/~rizzo/ingegneria/appunti_fisII_ing_mecc/"
$psPage = Invoke-WebRequest $site
$urls = $psPage.ParsedHtml.getElementsByTagName("A") | ? {$_.href -like "*.pdf"} | Select-Object -ExpandProperty href | ForEach-Object {$_.replace("about:", "")}
Second you have to recreate full URL :
$urls | ForEach-Object {Invoke-WebRequest -Uri "$site$_" -OutFile $_ }
But you can simplify using "textcontent" or "pathname" :
$site = "https://www.pi.infn.it/~rizzo/ingegneria/appunti_fisII_ing_mecc/"
$psPage = Invoke-WebRequest $site
$urls = $psPage.ParsedHtml.getElementsByTagName("A")
$urls | where {$_.pathname -like "*pdf"} | % {Invoke-WebRequest -Uri "$site$($_.pathname)" -OutFile $_.pathname }

Related

Powershell creating OU's

$DEPsOUs = #("A","B","C","D")
$createOUs = #('Users', 'Tester')
ForEach ($DEPOU In $DEPsOUs) {
$DEPOUDN = Get-ADOrganizationalUnit -Filter "Name -like '$DEPOU'" | select DistinguishedName | Format-Table -HideTableHeaders | Out-String
#write-host "$DEPOUDN" #checking if output is a string
ForEach ($createOU IN $createOUs) {
New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
}
}
this is the script, I just created some test OU's inside active directory. the script works but I get some weird issues which I don't understand.
New-ADOrganizationalUnit : The object name has bad syntax
At line:7 char:9
+ New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Users,
OU=A...,DC=local
:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUni
t
New-ADOrganizationalUnit : The object name has bad syntax
At line:7 char:9
+ New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Tester,
OU=...,DC=local
:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUni
t
New-ADOrganizationalUnit : The object name has bad syntax
At line:7 char:9
+ New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Users,
OU=B...,DC=local
:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUni
t
New-ADOrganizationalUnit : The object name has bad syntax
At line:7 char:9
+ New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Tester,
OU=...,DC=local
:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUni
t
New-ADOrganizationalUnit : The object name has bad syntax
At line:7 char:9
+ New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Users,
OU=C...,DC=local
:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUni
t
New-ADOrganizationalUnit : The object name has bad syntax
At line:7 char:9
+ New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Tester,
OU=...,DC=local
:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUni
t
New-ADOrganizationalUnit : The object name has bad syntax
At line:7 char:9
+ New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Users,
OU=D...,DC=local
:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUni
t
New-ADOrganizationalUnit : The object name has bad syntax
At line:7 char:9
+ New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Tester,
OU=...,DC=local
:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUni
t
can somebody clarify what is going on ? it creates the OU's with success but this issue appeared.i lauched it in Powershell ISE
I tried a few thing by converting it to string but doesn't really make sense to me when my arrays are string arrays.
You just need to expand the DistinguishedName attribute instead of using Format-Table (meant only for console display) and Out-String:
$DEPsOUs = #("A","B","C","D")
$createOUs = #('Users', 'Tester')
ForEach ($DEPOU In $DEPsOUs) {
$DEPOUDN = (Get-ADOrganizationalUnit -Filter "Name -eq '$DEPOU'").DistinguishedName
ForEach ($createOU IN $createOUs) {
New-ADOrganizationalUnit -Name $createOU -Path $DEPOUDN
}
}

Powershell scripting1

I am running this Script to get the directory listing
It was working few days ago but I keep having this error
New-PSSession : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At C:\DEV\Powershell3\directory-listing.ps1:11 char:38
+ $session=New-PSSession -ComputerName $servers
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.NewPSSessionCommand
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At C:\DEV\Powershell3\directory-listing.ps1:31 char:25
+ Invoke-Command -Session $session -ScriptBlock $scb
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
$servers=get-content C:\temp\servers.txt
$session=New-PSSession -ComputerName $servers
$scb = {
Write-host "working on $env:COMPUTERNAME" -ForegroundColor Red
$volumes=Get-WmiObject win32_volume -Filter "drivetype=3"
foreach($volume in $volumes) {
$driveletter=$volume.driveletter
if($driveLetter -ne $null) {
$drivename=$volume.name
(Get-ChildItem -path $drivename -Directory) |Select-Object Name,FullName
}
}
}
Invoke-Command -Session $session -ScriptBlock $scb

Passing filepath parameters to function

Below mentioned code is giving error, and I'm not able to troubleshoot issue. Can anyone please help, we are just passing SourceFile and DestinationFile location to this function...
ProcessDocumentsData "D:\Files\Scan1.doc","D:\Files\Scan1.csv"
Clear-Host
function ProcessDocumentsData {
Param(
[string]$SourceFile,
[string]$DestinationFile
)
$DestinationFileName = $DestinationFile
$SourceFileName = $SourceFile
$tableNum = 13
$delimiter = ','
$objWord = New-Object -Com Word.Application
$objWord.Visible = $false # $false
$objDocument = $objWord.Documents.Open($SourceFileName)
$LETable = $objDocument.Tables.Item($tableNum)
$LETableCols = $LETable.Columns.Count
$LETableRows = $LETable.Rows.Count
$RawCSV = for($r=1; $r -le $LETableRows; $r++) {
$content= #()
for($c=1; $c -le $LETableCols; $c++) {
#Write-Host ("R:{0},C:{1}" -f $r,$c)
$content += ("`"{0}`"" -f $LETable.Cell($r,$c).Range.Text -replace "(`r|`n|`t)|$([char]7)?")
}
$Content -join $delimiter
}
$Csv = $RawCSV | ConvertFrom-Csv
$objDocument.Close()
$objWord.Quit()
# Stop Winword Process
$rc = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objWord)
$Csv
$Csv | Export-Csv $DestinationFileName -NoTypeInformation
}
I'm getting the following error:
ProcessDocumentsData "D:\Files\Scan1.doc","D:\Files\Scan1.csv"
Command failed
At line:7 char:1
+ $objDocument = $objWord.Documents.Open($filename)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
You cannot call a method on a null-valued expression.
At line:8 char:1
+ $LETable = $objDocument.Tables.Item($tableNum)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:21 char:1
+ $objDocument.Close()
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
In PowerShell, when calling a function multiple parameters are delimited by a whitespace.
Try to call the function like that:
ProcessDocumentsData "D:\Files\Scan1.doc" "D:\Files\Scan1.csv"

Receiving odd error message in PS script

I have a PowerShell script that goes out grabs the currently logged in user on a remote computer and gets the total size of their local profile C:\users\USERNAME\documents, pictures, music, etc. I have confirmed that the remote computer is online and the user is logged in. While the script is working, in the sense that it gets the folder size, it returns this message:
Get-WmiObject : Invalid parameter
At C:\Users\administrator\Desktop\get_folder_size.ps1:4 char:9
+ $user = Get-WmiObject Win32_ComputerSystem -ComputerName $system | Se ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
You cannot call a method on a null-valued expression.
At C:\Users\administrator\Desktop\get_folder_size.ps1:5 char:1
+ $pos = $user.IndexOf("\")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\administrator\Desktop\get_folder_size.ps1:6 char:1
+ $user = $user.Substring($pos+1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
I'm confused because if I'm reading the message correctly it shouldn't be able to grab the username thus not get the correct folder and the size.
Here is the code that I'm running
foreach ($system in Get-Content "C:\net_view.txt")
{
$colItems = 0
$user = Get-WmiObject Win32_ComputerSystem -ComputerName $system |
Select-Object -ExpandProperty UserName
$pos = $user.IndexOf("\")
$user = $user.Substring($pos+1)
$path = $system +"\c$\users\" + $user
$colItems = (Get-ChildItem $path -Recurse -ErrorAction SilentlyContinue |
Measure-Object -property length -sum)
"{0:N2}" -f ($colItems.sum / 1MB) + " MB"
Add-Content C:\users\administrator\desktop\profile_size.txt ($colItems.sum / 1MB)
Add-Content C:\users\administrator\desktop\profile_size.txt $system
}

powershell get-content path null error

$commonElementsLocation = ((Get-Location).Path + "\FolderMatchingCommonWords.txt")
if ($commonElementsLocation) {
$result += Start-Job -InitializationScript {
$commonElements = Get-Content -Path $commonElementsLocation
} -ScriptBlock $testScriptBlock -ArgumentList "testing" | Wait-Job | Receive-Job
}
Not sure what I am doing wrong here - probably a stupid mistake, but I put a condition around the Start-Job statement, and powershell still gives the following error:
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:1 char:39
+ $commonElements = (Get-Content -Path $commonElementsLocation)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentC
ommand
Running startup script threw an error: Cannot bind argument to parameter 'Path' because it is null..
+ CategoryInfo : OpenError: (localhost:String) [], RemoteException
+ FullyQualifiedErrorId : PSSessionStateBroken
In v3 add $using:
....(Get-Content -Path $using:commonElementsLocation...
You have already used a variable for a script block once with $testScriptBlock. You could just do that again for -InitializationScript?
$anotherSB = [scriptblock]::create("$commonElements = (Get-Content -Path $commonElementsLocation)")
$result += Start-Job -InitializationScript $anotherSB -ScriptBlock $testScriptBlock -ArgumentList "testing" | Wait-Job | Receive-Job