Having issue removing a file in powershell - powershell

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

Related

PowerShell Import-GPO: Operation not valid

Afternoon everyone. I'm running into an issue I'm not sure how to handle. I'm working on a script for work to deploy a Domain Controller using PSremoting. It all works well in fine until I get to where I'm importing some GPOs from backups.
*All the commands are run under invoke-command
I run the command Import-GPO -BackUpName $GPO -TargetName $GPO -Path $GPOPath -MigrationTable $MigTable -CreateIfNeeded
When I run this, I get an error on the host:
Operation is not valid due to the current state of the object.
+ CategoryInfo : NotSpecified: (:) [Import-GPO], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.GroupPolicy.Commands.ImportGpoCommand
+ PSComputerName : v204-DC1
I can't seem to find anything that says what this means. When I check for the GPOs on the DC, they all show up and seem to be linked properly. I am curious what this error is, or if I should just append -ErrorAction SilentlyContinue to the end of my code.
Ended up being an issue with my migration table. I rolled back to an earlier one and ended up being good to go

In Powershell, how do I delete a file with a hyphen (dash) in the filename?

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

Use variable for URL in powershell BITS transfer

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.

Powershell script uses the user's home directory as current working dir when using .NET ZipFile.CreateFromDirectory. How to fix?

Here's my script (createdistro.ps1)
Add-Type -assembly "system.io.compression.filesystem"
$source = "bin\Debug\"
$destination = "gwtester_signed.zip"
If(Test-path $destination) {Remove-item $destination}
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
Notice the error message I get from running the script:
PS C:\dev\DEV7\Test\gwtester> .\createdistro.ps1
Exception calling "CreateFromDirectory" with "2" argument(s): "The file 'C:\Users\bbren\gwtester_signed.zip' already
exists."
At C:\dev\DEV7\Test\gwtester\createdistro.ps1:7 char:1
+ [io.compression.zipfile]::CreateFromDirectory($source, $destination)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IOException
As you can see, the script attempts to write to C:\Users\bbren\gwtester_signed.zip, but the current working directory is C:\dev\etc\.
The documentation for ZipFile.CreateFromDirectory states that "A relative path is interpreted as relative to the current working directory."
What is wrong?
I don't recommend $PSScriptRoot.
Try this:
$destination = Join-Path (Get-Location) 'gwtester_signed.zip'
But depending on your psversion, how about Expand-Archive?
Change $destination = "gwtester_signed.zip" to $destination = "$PSScriptRoot\gwtester_signed.zip"
I've actually added this to my prompt function to keep the .NET and Powershell view of what the current working directory is in sync. There's probably a load of reasons this is a BadIdeaâ„¢ - but it works for me :
[System.Environment]::CurrentDirectory = $PWD
Of course, you could just call that before you want to run a .NET method that cares about it too.
Edit: Ah yes, this question points out why this might end up being a bad idea :
Why don't .NET objects in PowerShell use the current directory?
Edit2: and in light of the above, I've now changed my prompt function to do this :
if($PWD.Provider.Name -eq 'Filesystem'){
[System.Environment]::CurrentDirectory = $PWD
}
So that the attempt to update the .NET view of current directory only happens when the current Powershell provider is the Filesystem one.

Remove-Item Vs [System.IO.File]::Delete()

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