I have the following in a powershell script:
$src_url = "http://my_server/my_file.zip"
if (!(Test-Path $src_zip))
{
"Downloading $src_url"
Start-BitsTransfer -Source "$src_url" -Destination .\$src_zip
}
The output of which is
Downloading http://my_server/my_file.zip
Start-BitsTransfer : The server name or address could not be resolved
At C:\foo.ps1:18 char:5
+ Start-BitsTransfer -Source "$src_url" -Destination .\$src_zip
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-BitsTransfer], Exception
+ FullyQualifiedErrorId : StartBitsTransferCOMException,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferComma
nd
I have tried with, without double and single quotes around the URL. However if I type the URL out directly the name is resolved correctly. What should I do to expand $src_url?
Considering it works with hard-coding URL, the source variable should expand correctly in your syntax.
And from error you pasted, it may due to destination path resolution. Try to use full path in it. Example,
$src_zip = "C:\temp\abc.zip"
Please see if the destination file needs to be removed or you can use force parameter.
Related
In Powershell, when I try to delete a file with a hyphen in the nam like this:
remove-item 'C:\S3\op_netadmin-47.bak'
I get this error:
remove-item : Cannot remove item C:\S3\op_netadmin-47.bak: Access to the path 'C:\S3\op_netadmin-47.bak' is denied.
At line:1 char:1
+ remove-item 'C:\S3\op_netadmin-47.bak'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\S3\op_netadmin-47.bak:FileInfo) [Remove-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand
But if I rename the file to op_netadmin_47.bak, it works fine.
I've tried with and without double quotes as well as single quotes
I tried your file name with - and _, both work ok. I also tried to use " around file name which also works.
As #mklement0 mentioned in comments read-only files require -Force parameter
Make sure user running script has read/write access to given folder
For a while, I am maintaining a PowerShell Join-Object cmdlet.
In here I am creating a few proxy commands with default parameters, as FullJoin-Object, Merge-Object and Insert-Object as described here: Proxy Functions: Spice Up Your PowerShell Core Cmdlets.
(In earlier version I was using aliases which could problems if the user creates its own aliases.)
Everything works as expected except that the error handling differs a little between the main command and the proxy command...
Taken the following MVCE, based on the following function:
Function Inverse([Int]$Number) {
Rubbish
Write-Output (1 / $Number)
}
(Where the function Rubbish doesn't exist)
Than I create a proxy function called Reverse0:
$MetaData = [System.Management.Automation.CommandMetadata](Get-Command Inverse)
$Value = [System.Management.Automation.ProxyCommand]::Create($MetaData)
$Null = New-Item -Path Function:\ -Name "Script:Inverse0" -Value $Value -Force
$PSDefaultParameterValues['Inverse0:Number'] = 0 # (Not really required for reproducing the issue)
If I run the original function Reverse 0, I get two errors:
Rubbish : The term 'Rubbish' 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:2 char:1
+ Rubbish
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (Rubbish:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Attempted to divide by zero.
At line:3 char:1
+ Write-Output (1 / $Number)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
If run the proxy command Reverse0 (or Reverse0 0), I get only the first error:
Rubbish : The term 'Rubbish' 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:2 char:1
+ Rubbish
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (Rubbish:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CommandNotFoundException
It seems that something like the $ErrorActionPreference has changed but I checked that and it appears to be the same within both functions.
Is there and explanation for the different behavior?
Is there a way to get a Proxy Command act the same as the original command with respect to error handling?
The code that [System.Management.Automation.ProxyCommand]::Create() generates is currently (PowerShell Core 7.0.0-preview.5) flawed:
It incorrectly propagates statement-terminating errors as script-terminating errors, by using throw rather than $PSCmdlet.ThrowTerminatingError($_) in its catch blocks, causing the function to abort instantly.
If you manually correct these calls, your proxy function should behave as expected.
See this GitHub issue; the linked issue isn't specifically about this behavior, but a change has been green-lighted, and it should include a fix for it.
In concrete terms, for now, you'll have to fix the generated code manually:
Locate all try / catch statements that look like this:
try {
# ...
} catch {
throw
}
and replace them with:
try {
# ...
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
I have the following code in an Azure Runbook:
$pathToDownloadedBlob = 'C:\depId-20150904032522\SevenZipSharp.dll'
if ((Test-Path $pathToDownloadedBlob) -eq $true)
{
try
{
Remove-Item -Path $pathToDownloadedBlob
}
catch
{
write-error "Could not delete $pathToDownloadedBlob. - $($error[0])"
exit
}
}
When I use Remove-Item I get this error:
4/7/2015 2:14:14 PM, Error: Remove-Item : The converted JSON string is in bad format.
At DavidTest:45 char:45
+
+ CategoryInfo : InvalidOperation: (System.Unauthor... Boolean force):ErrorRecord) [Remove-Item],
InvalidOperationException
+ FullyQualifiedErrorId : JsonStringInBadFormat,Microsoft.PowerShell.Commands.RemoveItemCommand
When I use [System.IO.File]::Delete($using:path) instead, I get this error:
4/7/2015 2:22:48 PM, Error: Exception calling "Delete" with "1" argument(s): "Access to the path 'C:\Deployment\SevenZipSharp.dll' is denied."
At DavidTest:46 char:46
+
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : UnauthorizedAccessException
I know I don't have permission to delete the file.
However, why is it complaining about a JSON string when I use Remove-Item?
EDIT:
Note this only happens in Azure Automation. However I wasn't truly able to replicate this in Powershell ISE locally because I have permission to files I wish to delete.
UPDATE:I just realised this is only happening for .dll files. If I try to delete a .7z file it works fine.
I would imagine that this is due to the serialization / deserialization of the object being passed between the PowerShell Workflow context, and the InlineScript Workflow Activity, which runs in a separate process by default.
Are you always passing in a [System.String], or are you sometimes passing in a [System.IO.FileInfo] object? If the latter, then you'll probably want to reference the FullName property, rather than passing in the object itself to Remove-Item.
I'm not 100% sure that this is what you're running into, but it's worth discussing.
By the way, as a best practice, always explicitly name your parameters, so other people understand what you're doing. Your call to Remove-Item doesn't include the -Path parameter, by name, because it's positionally at 0. Of course, this isn't a good thing to take for granted when you're asking for help. Better to be verbose.
Hope this helps at least a bit. By the way, is this problem unique to Azure Automation Runbooks, or does it also exist in locally executed PowerShell Workflows?
Edit: This code seems to work just fine for me locally.
workflow test {
$Path = 'C:\dsc\srv01.xml';
InlineScript { Remove-Item -Path $using:Path; };
}
test
I am trying to extract a zip file to then be downloaded by remote people. Once extracted I will have a script that installs the package but I need to use a compressed folder and the remote users don't have 7zip or anything like it.
I have this but I keep getting an error -
$shell = new-object -com shell.application
$zip = $shell.NameSpace(“C:\name.zip”)
foreach($item in $zip.items())
{
$shell.Namespace(“C:\temp\name”).copyhere($item)
}
The error I am getting is below -
You cannot call a method on a null-valued expression.
At line:5 char:43
+ $shell.Namespace(“C:\name”).copyhere <<<< ($item)
+ CategoryInfo : InvalidOperation: (copyhere:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
There are other issues with the code but this is a work in progress, I will fix the hard coding of values once I can get it to extract.
Does your extract path exist (“C:\temp\name”)? To be clear, both of the items in that path should be directories.
That should be a path that already exists. If it doesn't you get that error.
I'm trying to remove a file after checking some thing in that. I'm capturing the whole path into a variable and passing it to Remove-Item command and I'm getting below error:
Remove-Item : An object at the specified path E:\Import\IRIS_Import\working\RP
LS_BAI_20120719092600450-20120719093206.csv does not exist.
At E:\Import\IRIS_Import\FIX_IRIS_49_FILES_kr.ps1:53 char:13
+ Remove-Item <<<< $file
+ CategoryInfo : InvalidArgument: (:) [Remove-Item], PSArgumentEx
ception
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.RemoveIte
mCommand
Not sure why Powershell is complaining about file not being there even I can see the file there physically. Any ideas please?
I faced this exact same issue when I ran an Azure powershell webjob. I followed the answer in another thread in addition's to justinf's answer in this thread and modified my remove-item command as below.
remove-item filesystem::\\uncpath\folder
Your problem is that the file had an - in the file name and powershell does not like this it would seem.
This code worked for me. If it does not work for you post more of your code up and I will take a look.
$test = "c:\test\LS_BAI_20120719092600450-20120719093206.csv"
Remove-Item -LiteralPath $test