Using the Test-Path PowerShell command we can check if the system drive path or file exists or not in local drive. Similarly how can we check if the SharePoint document library folder path or file in document library exists or not using Test-Path or any similar command?
Test-Path -Path "http://win-3:001/sites/Dev/Shared%20Documents/Test1"
Test-Path -Path "http://win-3:001/sites/Dev/Shared%20Documents/Test1/sample.txt"
You should be able to check that with an HTTP request:
$uri = 'http://win-3:001/sites/Dev/Shared%20Documents/Test1'
(Invoke-WebRequest -Method Head -Uri $uri -UseDefaultCredentials).StatusCode
If your PowerShell version is too old to provide the Invoke-WebRequest cmdlet you should upgrade. If for some reason you can't do that use the System.Net.WebRequest class instead:
$uri = 'http://win-3:001/sites/Dev/Shared%20Documents/Test1'
$req = [Net.WebRequest]::Create($uri)
$req.Method = 'HEAD'
$req.UseDefaultCredentials = $true
$req.PreAuthenticate = $true
$req.Credentials = [Net.CredentialCache]::DefaultCredentials
$req.GetResponse().StatusCode.value__
Either way, a status code of 200 means the request was OK, i.e. the document exists.
Related
# Source file location
$source1 ="https://ftp.mozilla.org/pub/firefox/releases/11.0/win32/enUS/Firefox%20Setup%2011.0.exe"
$source2 ="https://www.fosshub.com/Code-Blocks.html?dwl=codeblocks-20.03-setup.exe"
$source3 ="https://github.com/x64dbg/x64dbg/releases/download/snapshot/snapshot_2021-07-01_23-17.zip"
$source4 ="https://www.python.org/ftp/python/3.9.6/python-3.9.6-amd64.exe"
$source5 ="https://www.nasm.us/pub/nasm/releasebuilds/2.15.05/win64/nasm-2.15.05-installer-x64.exe"
# Destination to save the file
$destination1 = "C:\Users\cdac\Desktop\Shravan\Softwares\firefox.exe"
$destination2 = "C:\Users\cdac\Desktop\Shravan\Softwares\codeblocks.exe"
$destination3 = "C:\Users\cdac\Desktop\Shravan\softwares\xdbg.zip"
$destination4 = "C:\Users\cdac\Desktop\Shravan\softwares\python.exe"
$destination5 = "C:\Users\cdac\Desktop\Shravan\softwares\nasm.exe"
Invoke-WebRequest -Uri $source1 -OutFile $destination1
Invoke-WebRequest -Uri $source2 -OutFile $destination2
Invoke-WebRequest -Uri $source3 -OutFile $destination3
Invoke-WebRequest -Uri $source4 -OutFile $destination4
Invoke-WebRequest -Uri $source5 -OutFile $destination5
#Installing one software
Start-Process -Wait -FilePath 'C:\Users\cdac\Desktop\Shravan\Softwares\codeblocks.exe' -ArgumentList '/silent' -PassThru
I have written Powershell script which downloads the software tools from the internet through URL and stored in a separate directory but iam not able to install all the softwares which are stored in a separate directory silently using foreach loop. kindly help me in writing script for installing all the softwares stored in a directory using foreach loop.
Thanking you
There isn't enough information to say exactly what's going wrong here - what error are you getting specifically? What behavior are you observing when you run your script? My first guess is that your foreach loop is running through installer names, not the full path like you posted in your example.
That said, if I understand what you're trying to do, here's a quick and dirty way to do what I think you're after;
# Array of installer details
[Hashtable[]]$Installers = #();
# Firefox
$Installers += #{
SoftwareName = "Firefox"
Url = "https://ftp.mozilla.org/pub/firefox/releases/11.0/win32/enUS/Firefox%20Setup%2011.0.exe"
Destination = "C:\Users\cdac\Desktop\Shravan\Softwares\firefox.exe"
Arguments = '/s'
}
#Code Blocks
$Installers += #{
SoftwareName = "CodeBlocks"
Url = "https://www.fosshub.com/Code-Blocks.html?dwl=codeblocks-20.03-setup.exe"
Destination = "C:\Users\cdac\Desktop\Shravan\Softwares\codeblocks.exe"
Arguments = '/silent'
}
function Install-Software([Hashtable]$installer) {
Write-Host "Installing $($installer.SoftwareName)"
Write-Host "Invoke-WebRequest -Uri $($installer.Url) -OutFile $($installer.Destination)"
Write-Host "Start-Process -FilePath $($installer.Destination) -ArgumentList $($installer.Arguments) -Wait"
# Remove Write Host above - uncomment the following lines:
#Invoke-WebRequest -Uri $installer.Url -OutFile $installer.Destination
#Start-Process -FilePath $installer.Destination -ArgumentList $installer.Arguments -Wait
}
foreach($installer in $Installers) {
Install-Software -installer $installer
}
I'd recommend having a look at the PSAppDeployToolkit if you're trying to package applications silently using PowerShell - this helped me a lot back when I was doing a lot of SCCM packaging.
I recently wrote a PowerShell script that downloads the latest release from a public repo and that works as intended. However, I want to change my script so it can access my private repo. Here is the code I have tried so far:
# Download latest release from GitHub
$credentials="myPersonalAccessToken"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "token $credentials")
$repo = "myUserName/MyPrivateReleaseRepo"
$file = "MyBinaries.zip"
$releases = "https://api.github.com/repos/$repo/releases"
Write-Host Determining latest release
$tag = (Invoke-WebRequest $releases -Headers $headers | ConvertFrom-Json)[0].tag_name
$download = "https://github.com/$repo/releases/download/$tag/$file"
$name = $file.Split(".")[0]
$zip = "$name-$tag.zip"
$dir = "$name-$tag"
Write-Host Dowloading latest release
Invoke-WebRequest $download -Headers $headers -Out $zip
Write-Host Extracting release files
Expand-Archive $zip -Force
# Cleaning up target dir
Remove-Item "C:\MyOutPutFolder\$name" -Recurse -Force -ErrorAction SilentlyContinue
# Moving from temp dir to target dir
Move-Item $dir\$name -Destination "C:\MyOutPutFolder\$name" -Force
# Removing temp files
Remove-Item $zip -Force
Remove-Item $dir -Recurse -Force
I get the following error only when using my private repo:
Invoke-WebRequest : The remote server returned an error: (404) Not Found
At C:\Script\DownloadLatestGitHubRelease.ps1:25 char:1
+ Invoke-WebRequest $download -Headers $headers -Out $zip
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
I've also tried providing bad credentials vs the correct credentials and got a "Bad Credentials" error when providing the incorrect ones as expected, so I believe I'm using the token correctly.
What am I doing wrong? Thanks in advance for any suggestions.
Landed here trying to do the same thing. After digging into some bash scripts that do similar, I came up with this to do the download:
$token = "<your token from https://github.com/settings/tokens>"
$downloadFolder = "C:\temp";
$ownerSlashRepo = "owner/reop";
$tag = "latest";
$json = Invoke-Webrequest -Uri "https://api.github.com/repos/$ownerSlashRepo/releases/$tag" -Headers #{'Authorization'='token '+$token; 'Accept'='application/json'}
$release = $json.Content | ConvertFrom-Json
$release.assets | %{
$asset = $_;
$x = Invoke-Webrequest -Uri $($asset.url) -OutFile "$downloadFolder\$($asset.name)" -Headers #{'Authorization'='token '+$token; 'Accept'='application/octet-stream'}
}
This downloads every file from the release, but you could filter it to just download one as needed, something like:
$release.assets | ?{$_.name -eq 'foo.zip'} | %{
To answer your question, in the original code you're attempting to use the token with https://github.com. I tried similar at first and got similar results to what you describe. I think it is only good for https://api.github.com and the REST API. I also found I had to specify Accept:application/octet-stream when downloading the asset.
I am trying to download a file from a website with powershell and save it in a C:\temp dir with it's original name
if i try Invoke-WebRequest -Uri ("uri to file download") -Method Get with the "-OutFile" Parameter i can save the file but not with the original name.
if i save the WebRequest return value in a parameter i find the original filename under $r.Headers.'Content-Disposition'
but i don't know how to output "the file" out of this variable.
can any one help me ?
Kind regards
Florian
I just created a quick snippet that should help you. Sadly, I couldn't test it without a valid URL :(
# Vars
$url = ""
$outputDir = $PSScriptRoot
# Invoke request
$result = Invoke-WebRequest -Method GET -Uri $url
# Extract name
$contentDisposition = $result.Headers.'Content-Disposition'
$fileName = $contentDisposition.Split("=")[1].Replace("`"","")
$path = Join-Path $outputDir $fileName
# Write into file
$file = [System.IO.FileStream]::new($path, [System.IO.FileMode]::Create)
$file.write($result.Content, 0, $result.RawContentLength)
$file.close()
I have a set of URLs using which I need to download files which can be of any type. I tried to use below PowerShell script, but the problem with this script is that I need to mention the type of the file. e.g. in below example I had to specify the type as PDF. Is there a way I can download file of any type from a URL to a specified folder?
$Path = "D:\Downloads\test.pdf"
# below url turns into 'https://xyz.abc.com/efg/TempData/data/%7B5a8662ff-1cbf-4141-bc93-c2f65657%7D/G4068.pdf'
$Url = "http://xyz.abc.com/efg/url.asp?SessID=1904B8A0E7B358A45F5422BC751CB763666BAB2F6EE10098823DFC10BCA2051260D63DCC93C0D9E63"
$WebClient = New-Object System.Net.WebClient
Write-Host "Downloading" $Path -ForegroundColor Green
$WebClient.DownloadFile($url, $path)
You can use the response headers to learn the file type, then adjust the file as necessary.
$data = Invoke-WebRequest -Uri $Url -Method get
Switch ($data.Headers.'Content-Type'){
"*pdf*" {$Data.content | Out-File MyOutfile.pdf}
"*jpeg*" {$Data.content | Out-File MyOutfile.jpg}
}
I'm running the following code
$client = new-object System.Net.WebClient
$client.DownloadFile( $UriValue, "C:\Temp\BHRout.json" )
$json = Get-Content "C:\Temp\BHRout.json"
This does not work because it needs my prompts credentials passed into the download string function. I've used the above code to replace this:
$NagiosResults = Invoke-WebRequest -Uri $Uri -UseDefaultCredentials | ConvertFrom-Json
The only problem with this is that the server I'm running the script on doesn't have Powershell v3; so this will not work either. Is there an alternative to Invoke-WebRequest for Powershell v2? If not, is there a way to 'use default credentials' with a System.Net.WebClient object?
Just set the UseDefaultCredentials property of the WebClient to $true and that will use the credentials of the current user for authentication.
$uri = "http://myserver/service"
$wc = New-Object System.Net.WebClient
$wc.UseDefaultCredentials = $true
$json = $wc.DownloadString($uri)