Powershell $webclient.UploadFile

Hello Community!
I am new to powershell and i have been playing around with getting files to upload using FTP.
I have got it working and i am happy with the results but i would like to get the script to exit if the upload fails and to only move the file if its successful. 
#Files to Send
$Dir="C:\test\Output"
#ftp server
$ftp = "ftp://xxx.xxx.xxx.xxx/"
$user = "User"
$pass = "Password"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
foreach($item in (dir $Dir "*.csv")){
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
Move-Item c:\test\Output\*.csv c:\test\Output\copied
can anyone assist please?
Many Thanks in advance :-)
Kallum

Hi Kallum,
To use try and catch in script, please refer to the script below, please note I haven't tested this script, which can only move files if the .csv has been uploaded via FTP successfully.
In addition, in case of deleting the files by mistake, I have added the "-whatif" to display the files name without deleting the file:
#Files to Send
$Dir="C:\test\Output"
#ftp server
$ftp = "ftp://xxx.xxx.xxx.xxx/"
$user = "User"
$pass = "Password"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
foreach($item in (dir $Dir"*.csv")){
"Uploading $item..."
try{
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)}#end try
catch{
$err=$_
Write-Host $error.exception.message
continue} # using the "continue" to turn to the next loop and ignore the move-item cmdlet
Move-Item $item.fullname c:\test\Output\copied -whatif}
If there is anything else regarding this issue, please feel free to post back.
Best Regards,
Anna Wang

Similar Messages

  • Upload a PDF file

    Hi all,
    I have post url and PDF file path
    how do i upload pdf file. As i did in .net like
    webclient.UploadFile(posturl,pdfpath);
    please let me know if nay body has an idea
    thanks
    Naveen

    Use Commons-FileUpload API.

  • Importing an external database of images into BC

    Hello,
    Is it possible to upload from an external intranet system to BC? I have a client with a database of images on their own intranet which they would like to upload/merge into the BC site we are building for them without having to go through the laborious process of loading them one at a time into what ever web app/gallery we will be using . They have asked the following -
    "Are you able to write import scripts to populate content if we schedule an export to ftp/web service etc?.
    All the data is stored in SQLServer and interfaces/reporting have been done in c# asp.net/Delphi.
    The only thing we do not have is Image attachment for the equipment (this is a manual process on the existing CMS) but all other details are in SQLServer.
    Depending on how your system can be manipulated we can automated some sort of data to send to it."
    This is a bit beyond my level of understanding/ability in BC but am happy to make it work if I know what I am doing. Is what is being asked possible? I know I can import a customer database into the CRM system, can I do something similar with images being key?
    Grant

    hello Alex,
    thank you for this thread & greetimgs from germany... (sorry for my english)
    my question - I have written an API (C#, .net)  for update the products-data via SOAP in eCommerce - so far so good... but I try for 2 Days to upload *.jpg Files to a BC-(_assets/images/)-Folder - with the C# WebClient.UploadFile method - I have no Chance to reach the BC Server - 404 - is in the Destination-Folder a jpg-File with the same name - there is no Problem to overwrite it, but I didnt create a new one ??!! - I try out many variants of ftp access to my Site via the API - by the way - with FileZilla everything is ok...
    is there any way to upload image files to my BC-Server via API ??
    thank you very much
    André

  • Download a UNIX based CGI page into a CSV file using Powershell

    Hello,
    I have been struggling to get a powershell script to work.
    I have a web-based page which ends in .cgi and I want to copy the text from that page to a CSV file.
    Normally the below script works for .html or .aspx types of pages but this time I have been getting the 'The remote server returned an error: (401) Unauthorized' page. I think the error is because the page is Unix based and for some reason I am not
    able to automate the authentication process.
    Below is the Powershell script I have been using. I have already created the securestring for my password and saved in a temp folder.
    $wc=new-object system.net.webclient
    $password = get-content 'C:\temp\Scripts\SecureString.txt' | convertto-securestring
    $wc.Credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "Domain\username", $password
    $wc.downloadfile("https://website.domain.com/cgi-bin/text_status_csv.cgi", "C:\temp\Scripts\output.csv")
    Currently I am able to successfully copy the data from the page over if I use
    $wc.Credentials = Get-Credential
    And then type in the username and password manually. I could really use some help to get this automated.
    Thanks in advance for your help

    A little searching and you will find hundreds of examples.
    https://www.google.com/#newwindow=1&q=powershell+persist+credentials
    ¯\_(ツ)_/¯

  • Download RSS feed as xml file from Sharepoint Online using PowerShell

    Hello
    Our company sharepoint (Office 365) contains also several RSS feeds.
    How it is possible to download xml file out of this feed (website) using PowerShell?
    I can authenticate with sharepoint using CSOM but do not what to do next.
    As service user is not administrator I cannot use "SPOService".
    This script works OK for standard website, but not for Sharepoint.
    $doc = New-Object System.Xml.XmlDocument
    $doc.Load("http://www.{CompanySite}.com/feed/")
    $doc.save("C:\temp\feed.xml")
    I am getting this error when using for company Sharepoint:
    "The remote server returned an error: (403) Forbidden."
    Thanks for your time considering this question.
    Jozin

    Hi Scott,
    thanks for advice.
    Combination of WebClient and Sharepoint Credentials is working OK:
    $client = New-Object System.Net.WebClient 
    $client.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User, $SecurePassword)
    $client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
    $client.DownloadFile($SiteURL, $file)

  • How to add tags to SharePoint via Powershell?

    Hi,
    I have a large directory of folders and files that I have to upload onto SharePoint Online. The only thing is, my boss wants to keep the folder structure but not the folders
    Basically he wants to use the folder names for tags and upload files underneath the tags.
    Is there a way to upload the tags using powershell?
    Or if not is there a way to upload files to existing tags ? 
    thanks
    Dearbhla Bradley

    You can create social tag using powershell 
    http://www.c-sharpcorner.com/uploadfile/anavijai/create-social-tag-in-sharepoint-2010-using-powershell/
    http://www.toddklindt.com/blog/Lists/Posts/Post.aspx?ID=468
    Not sure if this will work in SharePoint Online
    If this helped you resolve your issue, please mark it Answered

  • Third question - Using parameters in powershell recovery - Alert description

    Hi guys,
    With help i created powershell recovery in a management pack. Once again thanks very much, this is new to me. Now i know these parameters (variables):
    http://blogs.technet.com/b/kevinholman/archive/2009/09/23/alert-notification-subscription-variables-and-linking-that-to-the-console-database-and-sdk.aspx
    But how can i implement this in this XML? I think i must declare them in the XML, because when i put the variable there, it doesn't work. I would like to get the alert description in the message variable (see xml below)
    </Recovery>
    <Recovery ID="MomUIGenaratedRecovery28e1547022254ccbb82784c60d51b1d2" Accessibility="Public" Enabled="true" Target="Type603f92b7b83945598af55495615db953" Monitor="UIGeneratedMonitor0cd347f57f3949deb958cebb02d25555" ResetMonitor="false" ExecuteOnState="Error" Remotable="true" Timeout="300">
    <Category>Custom</Category>
    <WriteAction ID="MomUIGenaratedModule75df98fbfc5b48e39fd605cccd97d29b" TypeID="Windows!Microsoft.Windows.PowerShellWriteAction">
    <ScriptName>sendSMS.ps1</ScriptName>
    <ScriptBody>
    # function SendSMS
    # PowerShell function to send SMS messages via the CM SMS Gateway.
    function SendSMS{
    param([string]$url, [int]$customer, [string]$login, [string]$password, [string]$recipient, [string]$sender,[string]$reference)
    $xml = New-Object XML
    $messages = $xml.CreateElement("MESSAGES")
    $customerxml = $xml.CreateElement("CUSTOMER")
    $customerxml.SetAttribute("ID", $customer)
    $messages.AppendChild($customerxml)|Out-Null
    $user = $xml.CreateElement("USER")
    $user.SetAttribute("LOGIN", $login)
    $user.SetAttribute("PASSWORD", $password)
    $messages.AppendChild($user) |Out-Null
    if (!($reference.Equals(''))) {
    $refxml = $xml.CreateElement("REFERENCE")
    $refxml.Innertext = $reference
    $messages.AppendChild($refxml) |Out-Null
    $tariff = $xml.CreateElement("TARIFF")
    $tariff.InnerText = 0
    $messages.AppendChild($tariff) |Out-Null
    $msg = $xml.CreateElement("MSG")
    $from = $xml.CreateElement("FROM")
    $from.InnerText = $sender
    $msg.AppendChild($from) |Out-Null
    $to = $xml.CreateElement("TO")
    $to.InnerText = $recipient
    $msg.AppendChild($to) |Out-Null
    $body = $xml.CreateElement("BODY")
    $body.SetAttribute("TYPE", "TEXT")
    $body.InnerText = $message
    $msg.AppendChild($body) |Out-Null
    $messages.AppendChild($msg) |Out-Null
    $xml.AppendChild($messages) |Out-Null
    Write-Output $xml.OuterXml
    $webClient = New-Object net.WebClient
    return ($webClient.UploadString($url, $xml.OuterXml))
    # test
    SendSMS -url 'https://website.sms.nl/webservice.ashx' -recipient 0031612345678 -customer 1 -login 1 -password 'password' -sender 'Standby' -message 'Here i want the alert description' -reference '1234'
    </ScriptBody>
    <TimeoutSeconds>60</TimeoutSeconds>
    </WriteAction>
    Kind regards,
    André

    Parameters are defined between ScriptBody and TimeoutSeconds like this:
    <Parameters>
    <Parameter>
    <Name>param1</Name>
    <Value>$Config/param1$</Value>
    </Parameter>
    <Parameter>
    <Name>param2</Name>
    <Value>$Config/param2$</Value>
    </Parameter>
    </Parameters
    This information is available on MSDN.
    Jonathan Almquist | SCOMskills, LLC (http://scomskills.com)

  • How to get the content of a website to a txt file via powershell

    Hello,
    I have a reporting server that creates a report to a URL, by running multiple .xsl files. I want to be able to gather the data in the URL and convert it to csv or txt file via powrshell.
    Again I want the data inside the URL, I've been playing around Net.Webclient but I'm not getting what I need.

    If you're using PowerShell 3.0 or later you can try using Invoke-WebRequest.
    This previous thread shows how you can download the content from the page.
    Without knowing what type of content (i.e. text vs images vs other objects) is on the page it's hard to say if this will work for you.
    Jason Warren
    @jaspnwarren
    jasonwarren.ca
    habaneroconsulting.com/Insights

  • Automating ftp download with powershell

    I need to setup a scheduled task that is going to download files from an ftp location (or just run it manually)
    I have the following for a ps1
    $File = "c:\store\somefilename.zip"
    $ftp = "ftp://username:[email protected]/pub/outbound/somefilename.zip"
    "ftp url: $ftp"
    $webclient = New-Object System.Net.WebClient
    $uri = New-Object System.Uri($ftp)
    "Downloading $File..."
    $webclient.DownloadFile($uri, $File)
    I'm guessing I can set $File to *.* but I don't want to download the same files everytime. I am hoping the users will be moving the files once downloaded but who can quarentee that. What for loop can I add to achieve this?
    I found the following but not sure how I would alter my original to add this in.
    foreach($listOut in $listIn)
    $a = ((Get-Date) - [datetime]::ParseExact($listOut.ModifiedDate, "MMM dd HH:mm", $null)).days
    if ($a -le 0)
    Get-FTPItem -path $dirBank\$($listOut.Name) -LocalPath d:\backup\test\$($listOut.Name)
    Thanks in advance for the help.

    Hi,I have written a PowerShell module which handles things like uploading/download of files to websites and ftp servers.
    The code is available at: https://github.com/kjacobsen/WebFunctions
    Import-Module E:\WebFunctions\Web-Actions.psm1
    Get-WebFile ftp://ftp.uni-rostock.de/pub/systems/windows/WinNT/Sys/SysInternals/Filemon.zip
    The code above will download the file to the current folder. The CMDlets support a variety of features including Proxy connections and authentication.
    Kieran Jacobsen @kjacobsen http://aperturescience.su

  • Second queston using powershell in SCOM as recovery

    Hi guys,
    In a previous question i needed some ideas about using powershell in a recovery.
    Now i've implemented this in the XML, but it gives me this error as i import my managementpack back in SCOM 2012 R2 UR 2
    Error, it gives the error on Microsoft.Windows.PowerShellWriteAction too:
    If any management packs in the Import list are dependent on this management pack, the installation of the dependent management packs will fail.
    Cannot resolve identifier Windows!Microsoft.Windows.PowerShellWriteAction in the context of management pack ANWB.Informatica.Powercenter0. Unknown alias: Windows.
    <Recovery ID="MomUIGenaratedRecovery7187d8e283b44c9c9a115f06af5d3dcc" Accessibility="Public" Enabled="true" Target="Type603f92b7b83945598af55495615db953" Monitor="UIGeneratedMonitor0cd347f57f3949deb958cebb02d25555" ResetMonitor="false" ExecuteOnState="Error" Remotable="true" Timeout="300">
    <Category>Custom</Category>
    <WriteAction ID="MomUIGenaratedModule8ea82cdaccd8404b810409334cc50e47" TypeID="Windows!Microsoft.Windows.PowerShellWriteAction">
    <ScriptName>SendSMS-XMLPOST.ps1</ScriptName>
    <Arguments />
    <ScriptBody>function SendSMS{
    param([string]$url, [int]$customer, [string]$login, [string]$password, [string]$recipient, [string]$sender, [string]$message, [string]$reference)
    $xml = New-Object XML
    $messages = $xml.CreateElement("MESSAGES")

    Vladimir,
    Thanks for your response.
    Ofcourse i can. Here you got my XML. These are my changes to the XML:
    In the typedefenitions -> moduletypes:
    <ModuleTypes>
    <!-- ABO ADDED code 18-07-2014 -->
    <WriteActionModuleType ID="Microsoft.Windows.PowerShellWriteAction" Accessibility="Public" Batching="false">
    <Configuration>
    <IncludeSchemaTypes>
    <SchemaType>Microsoft.Windows.PowerShellSchema</SchemaType>
    </IncludeSchemaTypes>
    <xsd:element name="ScriptName" type="NonNullString" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="ScriptBody" type="NonNullString" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="SnapIns" type="SnapInsType" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="Parameters" type="NamedParametersType" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="TimeoutSeconds" type="xsd:integer" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="StrictErrorHandling" type="xsd:boolean" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="SerializationDepth" type="xsd:integer" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    </Configuration>
    <OverrideableParameters>
    <OverrideableParameter ID="TimeoutSeconds" Selector="$Config/TimeoutSeconds$" ParameterType="int" />
    </OverrideableParameters>
    <ModuleImplementation Isolation="Any">
    <Composite>
    <MemberModules>
    <WriteAction ID="PowerShellWriteAction" TypeID="Microsoft.Windows.PowerShellWriteActionBase">
    <ScriptName>$Config/ScriptName$</ScriptName>
    <ScriptBody>$Config/ScriptBody$</ScriptBody>
    <SnapIns>$Config/SnapIns$</SnapIns>
    <Parameters>$Config/Parameters$</Parameters>
    <TimeoutSeconds>$Config/TimeoutSeconds$</TimeoutSeconds>
    <OutputType>SerializedObjectData_OpsMgrSerialization</OutputType>
    <StrictErrorHandling>$Config/StrictErrorHandling$</StrictErrorHandling>
    <SerializationDepth>$Config/SerializationDepth$</SerializationDepth>
    </WriteAction>
    </MemberModules>
    <Composition>
    <Node ID="PowerShellWriteAction" />
    </Composition>
    </Composite>
    </ModuleImplementation>
    <OutputType>Microsoft.Windows.SerializedObjectData</OutputType>
    <InputType>System!System.BaseData</InputType>
    </WriteActionModuleType>
    <WriteActionModuleType ID="Microsoft.Windows.PowerShellWriteActionBase" Accessibility="Internal" Batching="false">
    <Configuration>
    <IncludeSchemaTypes>
    <SchemaType>Microsoft.Windows.PowerShellSchema</SchemaType>
    </IncludeSchemaTypes>
    <xsd:element name="ScriptName" type="NonNullString" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="ScriptBody" type="NonNullString" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="SnapIns" type="SnapInsType" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="Parameters" type="NamedParametersType" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="TimeoutSeconds" type="xsd:integer" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="OutputType" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:simpleType>
    <xsd:restriction base="xsd:string">
    <xsd:enumeration value="SerializedObjectData_OpsMgrSerialization" />
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:element>
    <xsd:element name="StrictErrorHandling" type="xsd:boolean" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="SerializationDepth" type="xsd:integer" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    </Configuration>
    <ModuleImplementation Isolation="Any">
    <Managed>
    <Assembly>Microsoft.EnterpriseManagement.Modules.PowerShell, Culture="", PublicKeyToken="31bf3856ad364e35", Version="6.0.4900.0"</Assembly>
    <Type>Microsoft.EnterpriseManagement.Modules.PowerShell.PowerShellProbeActionModule</Type>
    </Managed>
    </ModuleImplementation>
    <OutputType>Microsoft.Windows.SerializedObjectData</OutputType>
    <InputType>System!System.BaseData</InputType>
    </WriteActionModuleType>
    </ModuleTypes>
    <!-- ABO ADDED code 18-07-2014 -->
    And in the monitor recovery:
    <!-- ABO ADDED code 18-07-2014 -->
    <Recovery ID="MomUIGenaratedRecovery7187d8e283b44c9c9a115f06af5d3dcc" Accessibility="Public" Enabled="true" Target="MPAuthoring.PowerShellScript.ServiceTarget" Monitor="MPAuthoring.PowerShellScript.ServiceMonitor" ResetMonitor="false" ExecuteOnState="Warning" Remotable="true" Timeout="300">
    <Category>Custom</Category>
    <WriteAction ID="ServiceRestartScriptWriteAction" TypeID="Windows!Microsoft.Windows.PowerShellWriteAction">
    <ScriptName>SendSMS-XMLPOST.ps1</ScriptName>
    <Arguments />
    <ScriptBody>function SendSMS{
    param([string]$url, [int]$customer, [string]$login, [string]$password, [string]$recipient, [string]$sender, [string]$message, [string]$reference)
    $xml = New-Object XML
    $messages = $xml.CreateElement("MESSAGES")
    $customerxml = $xml.CreateElement("CUSTOMER")
    $customerxml.SetAttribute("ID", $customer)
    $messages.AppendChild($customerxml)|Out-Null
    $user = $xml.CreateElement("USER")
    $user.SetAttribute("LOGIN", $login)
    $user.SetAttribute("PASSWORD", $password)
    $messages.AppendChild($user) |Out-Null
    if (!($reference.Equals(''))) {
    $refxml = $xml.CreateElement("REFERENCE")
    $refxml.Innertext = $reference
    $messages.AppendChild($refxml) |Out-Null
    $tariff = $xml.CreateElement("TARIFF")
    $tariff.InnerText = 0
    $messages.AppendChild($tariff) |Out-Null
    $msg = $xml.CreateElement("MSG")
    $from = $xml.CreateElement("FROM")
    $from.InnerText = $sender
    $msg.AppendChild($from) |Out-Null
    $to = $xml.CreateElement("TO")
    $to.InnerText = $recipient
    $msg.AppendChild($to) |Out-Null
    $body = $xml.CreateElement("BODY")
    $body.SetAttribute("TYPE", "TEXT")
    $body.InnerText = $message
    $msg.AppendChild($body) |Out-Null
    $messages.AppendChild($msg) |Out-Null
    $xml.AppendChild($messages) |Out-Null
    Write-Output $xml.OuterXml
    $webClient = New-Object net.WebClient
    return ($webClient.UploadString($url, $xml.OuterXml))
    # test
    SendSMS -url 'https://sms.nl/' -recipient 0031123456789 -customer 1 -login 1 -password 'password' -sender 'Standby' -message 'Test' -reference '1234'</ScriptBody>
    <!-- ABO ADDED code 18-07-2014 -->

  • How to set Current quota template dropdownto 50 GB using powershell script

    In central administrator under Application Management -> Configure quotas and locks  we have Current quota template drop down. I  want to set drop down value to 50 GB using powershell . Is it possible and it if it possible then How ? Please
    let me know 
    Thanks in Advance 
    Regards
    Subhash
     

    Hi Sub_84,
    A quota template consists of storage limit values that specify the maximum amount of data that can be stored in a site collection. When the storage limit is reached, a quota template can also trigger an e-mail alert to the site
    collection administrator. You can create a quota template that can be applied to any site collection in the farm. The storage limit applies to the sum of the content sizes for the top-level site and all subsites within the site collection.
    You can create quota template using powershell, ojbect module and sharepoint UI.
    Create new Quota template using powershell:
    $newQuotaTemplate = New-Object Microsoft.SharePoint.Administration.SPQuotaTemplate
    $newQuotaTemplate.Name = "New Quota Template"
    $newQuotaTemplate.StorageMaximumLevel = (150 * 1024) * 1024
    $newQuotaTemplate.StorageWarningLevel = (100 * 1024) * 1024
    $newQuotaTemplate.UserCodeMaximumLevel = 300
    $newQuotaTemplate.UserCodeWarningLevel = 300
    $contentService =[Microsoft.SharePoint.Administration.SPWebService]::ContentService
    $contentService.QuotaTemplates.Add($newQuotaTemplate)
    $contentService.Update()
    Check the link which can guide you how
    http://www.c-sharpcorner.com/uploadfile/anavijai/quota-templates-in-sharepoint-2010/
    Please mark the Answer and vote me if you think that above solution can help you to resolve the issue

  • Powershell DownloadFile(,) command giving 403 - Forbidden error

    I am using Powershell DownloadFile(,) command for reading a .csv file from a document library in SharePoint 2013 site. When i ran the code on my DEV environment, it ran properly. The DEV environment is using http://. But , when I run this code on TEST
    environment i get 403 Forbidden error. The site(TEST environment) is running over https://.
    I am using below code ,
    $FilePath = "https://ServerName/sites/SiteName/MyDocumentLibrary/MyCSVFile.csv"
    $localPath = "C:\temp\test.csv" 
    $wc = New-Object System.Net.Webclient
    $wc.DownloadFile($FilePath, $localPath)
    $list = Import-Csv $localPath
    The error says,
    Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (403) Forbidden." At D:\Amit\UpdateUserInformationList.ps1:39 char:1
    I have gone through various articles which talks about passing credentials with the Webclient($wc) object. But, with no luck. Still getting same error.
    I am still unaware, when/why does Powershell throws this error ? What is the root cause of this error?
    Any help will be greatly appreciated.

    After a long day, it turned out that for successfully using the Powershell DownloadFile() method, in my environment (SP2013 with ADFS) following two lines did the trick(at least for me).
    $wc.UseDefaultCredentials = $true
    $wc.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
    So, the final code looks like,
    $FilePath = "https://ServerName/sites/SiteName/MyDocumentLibrary/MyCSVFile.csv"
    $localPath = "C:\temp\test.csv" #Make sure the folder do exist
    $wc = New-Object System.Net.Webclient
    $wc.UseDefaultCredentials = $true
    $wc.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
    $wc.DownloadFile($FilePath, $localPath)
    $list = Import-Csv $localPath

  • Install dotnet 4.5 powershell

    the script is take from below link and modified for my lab testing I have commented out few lines.
    Basically I save the below file as ps1 and I run .
    Invoke-command -computername abc -filepath c:\script\name.ps1  .the script will run file locally but not remotely any help would be appreciated
    http://www.zerrouki.com/silently-install-the-net-framework-v4-0/
    <#
    .SYNOPSIS
        SilentInstallNET - Download and Install silently the .NET framework v4.0.
    .NOTES
        File Name  : SilentInstallNET.ps1
        Author     : Fabrice ZERROUKI -
    [email protected]
    .EXAMPLE
        PS D:\>SilentInstallNET.ps1
    #>
    $TempFolder = "C:\DOWNLOADED_APPLICATIONS"
    if(!(test-path $TempFolder))
    {New-Item -path $TempFolder -type directory}
    Write-Host ""
    Write-Host "Downloading .NET framework v4.0 installation package" -ForegroundColor Yellow;
    $src = "\\ramads004\dotnet\dotNetFx40_Full_x86_x64.exe"
    $dest = "$TempFolder" + "\" + "dotNetFx40_Full_x86_x64.exe /quiet /norestart"
    #$wc = New-Object System.Net.WebClient
    #$wc.DownloadFile($src, $dest)
    $args = " /q /norestart"
    Write-Host "Installing .NET framework v4.0" -ForegroundColor Yellow;
    #Start-Process -FilePath $dest -ArgumentList $args -Wait
    Invoke-Expression $dest
    Write-Output "Dot net 4.5 installed"
    start-sleep -seconds 360
    # Remove-Item $TempFolder -recurse
    also followed this article but doesn't work for me remotely
    http://social.technet.microsoft.com/Forums/windowsserver/ar-SA/3045eb24-7739-4695-ae94-5aa7052119fd/install-dotnet-framework-4-using-powershell?forum=winserverpowershell

    Hiya,
    The below is how I usually do my remote powershelling, including parameters.
    $Session = New-PSSession -Computername $SQLServer -Authentication Kerberos
    $SQLOptions = {
    param([Parameter(Mandatory=$true)]$Database,[Parameter(Mandatory=$true)]$DatabaseLog,[Parameter(Mandatory=$true)]$Instance)
    Add-PSSnapin sqlserverprovidersnapin100
    Add-PSSnapin sqlservercmdletsnapin100
    Invoke-SQLcmd -Query "USE master;ALTER DATABASE $Database SET RECOVERY FULL, AUTO_SHRINK OFF, AUTO_CLOSE OFF, AUTO_CREATE_STATISTICS ON, AUTO_UPDATE_STATISTICS ON;" -ServerInstance "$Instance"
    Invoke-SQLcmd -Query "USE master;ALTER DATABASE $Database MODIFY FILE (NAME= $Database,FILEGROWTH= 150MB, MAXSIZE= UNLIMITED);" -ServerInstance "$Instance"
    Invoke-SQLcmd -Query "USE master;ALTER DATABASE $Database MODIFY FILE (NAME= $DatabaseLog,FILEGROWTH= 150MB, MAXSIZE= UNLIMITED);" -ServerInstance "$Instance"
    Invoke-Command -ArgumentList $Database, $DatabaseLog, $Instance -Session $Session -ScriptBlock $SQLOptions
    Remove-PSSession $Session

  • PowerShell 3 update-help (proxy issues?)

    I am running the PowerShell 3.0, as an admin, but update-help is not working. I suspect it does not know that we have an outbound proxy that requires: port, host, username, password. However WinHTTP API apps should grab this from the default credentials.
    I expected PS to do this.
    PS C:\Windows\system32> update-help
    update-help : Failed to update Help for the module(s) 'ISE, Microsoft.PowerShell.Management, Microsoft.PowerShell.Utility, CimCmdlets, Microsoft.PowerShell.Diagnostics,
    Microsoft.PowerShell.Host, Microsoft.PowerShell.Security, Microsoft.WSMan.Management, PSScheduledJob, PSWorkflow, PSWorkflowUtility, Microsoft.PowerShell.Core' with UI
    culture(s) {en-US} : Unable to connect to Help content. Make sure the server is available and then try the command again.
    At line:1 char:1
    + update-help
    + ~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [Update-Help], Exception
        + FullyQualifiedErrorId : UnableToConnect,Microsoft.PowerShell.Commands.UpdateHelpCommand
    Dr. YSG

    Fhoffman's solution, is not working for me.
    And I cannot follow the german (translated to english) (although I do speak some German) in Peter Kriegel's post.
    PS C:\Windows\system32> $webclient = New-Object System.Net.WebClient
    $creds = Get-Credential
    $webclient.Proxy.Credentials = $creds
    cmdlet Get-Credential at command pipeline position 1
    Supply values for the following parameters:
    PS C:\Windows\system32> update-help
    update-help : Failed to update Help for the module(s) 'ISE, Microsoft.PowerShell.Management, Microsoft.PowerShell.Security, Microsoft.PowerShell.Utility, CimCmdlets, Microsoft.PowerShell.Diagnostics, Microsoft.PowerShell.Host, Microsoft.WSMan.Management, 
    PSScheduledJob, PSWorkflow, PSWorkflowUtility, Microsoft.PowerShell.Core' with UI culture(s) {en-US} : Unable to connect to Help content. Make sure the server is available and then try the command again.
    At line:1 char:1
    + update-help
    + ~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [Update-Help], Exception
        + FullyQualifiedErrorId : UnableToConnect,Microsoft.PowerShell.Commands.UpdateHelpCommand
    PS C:\Windows\system32> $creds
    UserName                                                                        
                        Password
    ysg4206`                                                                        
    System.Security.SecureString
    Dr. YSG

  • Question about using PowerShell to detect web page availability and then perform alternate action.

    I have a specific Windows 7 machine that needs to always display a specific Intranet page.  (it shows an internal status page in kiosk mode).
    If this machine every loses connectivity to the web server, unfortunately, the browser shows the typical "web page could not be retrieved" error message and it never recovers.  I need to manually reload the page when the connection is restored.
    I'm thinking if it would be possible to write a PowerShell script that checks the connectivity/availability of the Intranet page and if it detects an error, it would launch a browser that points to a local file html file which would say something more professional
    and graceful like "site temporarily down for maintenance."  Also, if the PowerShell script could run on a regular interval, when the Intranet page becomes available again, it would close the browser that is showing the maintenance page and start
    showing the page with the original Intranet site.
    For the Intranet site checking, I was looking at the invoke-webrequest: as the mechanism.
    Any guidance would be appreciated as I am new to PowerShell.

    With these lines you get the static content of the web page:
    $page = new-object net.webclient
    $page.UseDefaultCredentials = $True
    $Page.DownloadString(“http://www.intranet.local.com/”)
    You could first check whether the web server is pingable, then use the lines above to see whether there is a HTML response.
    If the web server doesnt respond you could kill the browser process and then open a HTML page stored locally on the Win 7 client:
    Invoke-Item .\ErrorPage.html
    If the web server responds, kill the browser and restart it showing the Intranet page.
    All this run from a scheduled task.

Maybe you are looking for