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

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

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

PowerShell DSC: The data source could not process the filter

Afternoon!
I have run into an issue with PowerShell DSC (the Start-DscConfiguration cmdlet specifically) 2 days trying to figure it out, now I am here :)
I am getting the following error for a specific MOF file, prior MOFs run fine.
The data source could not process the filter. The filter might be missing or it might be invalid. Change the filter
and try the request again.
+ CategoryInfo : InvalidArgument: (root/Microsoft/...gurationManager:String) [], CimException
+ FullyQualifiedErrorId : HRESULT 0x8033801a
EDIT: Has anyone experienced this error before? I can share the MOF file in question, with some restricted info removed.
Thank you
The issue here wasn't with PowerShell DSC, rather just PowerShell in itself.
I had a cmdlet within a switch block. As an example:
Switch($item){
{$_ -eq $true}{do something}
{$_ -eq $fales}{do something}
get-service -name $item
}
It was the get-service cmdlet that could not be filtered.

The start-process cmdlet of powershell will fail with -PassThru argument when trying to launch Edge browser

In my test script by powershell, I'd start an Edge browser and get it's main process's ID. Simply like this:
$edge = Start-Process microsoft-edge: www.ted.com -PassThru
but instead of able to get the process id from $edge.Id, I've got error message like this:
Start-Process : This command cannot be run completely because the system cannot find all the information required.
At line:1 char:7
+ $edge=Start-Process microsoft-edge: www.ted.com -PassThru
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
Is there any simple and straightforward way to really doing this without enumerate and check the process list?
Thanks!
I try to test your script and I am getting a similar error as yours.
Based on my search result, passthru is not one of the common parameters, and it does not exist everywhere.
Reference:
Use the PowerShell Passthru Parameter and Get Back Objects
I think it is not available for the MS Edge browser and that's why the script gives an error.
I try to search for an alternative command for PassThru but I did not get any helpful information about it.
In this situation, it is better to enumerate and check the process list

Why do proxy commands handle errors differently

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($_)
}

Having issue removing a file in 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