Using Invoke-Command to get around UnathorizedAccessException

This topic contains 6 replies, has 5 voices, and was last updated by  Kevyn 9 months, 3 weeks ago.

  • Author
  • #76223

    John Steele

    I'm trying to understand the use of Invoke-Command in a very specific scenario.

    Get-ChildItem -Path C:\Windows\csc -Recurse -File

    Running the above command produces the following error:

    Get-ChildItem : Access to the path 'C:\Windows\csc' is denied.
    At line:1 char:1
    + Get-ChildItem -Path C:\Windows\csc -Recurse -File
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : PermissionDenied: (C:\Windows\csc:String) [Get-C 
       hildItem], UnauthorizedAccessException
        + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell. 
    Invoke-Command -ComputerName localhost -ScriptBlock {Get-ChildItem -Path C:\Windows\csc -Recurse -File}

    Wrapping that same command in the ScriptBlock of Invoke-Command as shown above
    will actually output all the files in that folder.

    What is Invoke-Command doing that allows it to output all the files instead
    of generating an error?

  • #76225

    Ben Camareno

    Running from ISE or normal Powershell console?

  • #76229


    Is PowerShell in administrator mode? check the rights of the user by which you are executing the command.

  • #76234

    John Steele

    I get the same result from the console or the ISE running as administrator. Both commands are run back to back.

    Test it out. I imagine you get the same result.

  • #76289

    Richard Siddaway

    If you try to look at the permissions on the folder you'll see you don't have any. Its not a PowerShell issue its a Windows permissions issue. PowerShell won't and can't so anything that you don't have permissions to do or access

  • #76295

    John Steele

    I understand I don't have permissions to that folder which explains the default behavior of Get-Childitem and the access denied error. When wrapped in the scriptblock of Invoke-Command though I can view the files in that folder just fine. So what is Invoke-Command doing that allows me to view the files of a folder that I don't have permissions to?

  • #76298


    At the below post, the moderator says "The difference is that, with Invoke, you are bypassing UAC." Not sure if that's the answer, but there ya go.

You must be logged in to reply to this topic.