Powershell get-childitem UnauthorizedAccessException

I am running the Get-ChildItem -recurse command against files on a remote file server and am getting an error that I can't explain (see below).  The account running the command has full control of all of the directories listed in the tree and can open/edit
any file via Windows explorer.  The account in question (domain\_myservice_account) is a domain account and it can successfully run the command on my laptop or a different server.  This command started failing about 1.5 months ago but had worked
successfully from that server for 2 years.
The command fails whether I try using the UNC name or a mapped drive to the directory.  It seems to successfully scan dir7 through dir12 with no issues the error comes once it reaches directory dir13 and it's children.
Is there some configuration that I need to change on the servers where this command is failing in order to get this working again?
Please help as I have been trying to figure this out for a while now with no progress.
Thanks,
Mike
Get-ChildItem : Access to the path '\\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\dir9\dir10\dir11\dir12\dir13' is denied.
At line:1 char:14
+ Get-ChildItem <<<<  \\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\ -recurse -filter my_file_*.gz
    + CategoryInfo          : PermissionDenied: (\\Server...\dir12\dir13:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

Thank you for your response.  For clarity I have run the same command from my local PC (as myself or the service account that the process has run under for 2 years) and it works fine.  However when I run the command from my Windows 2008 R2 Server
I get the issue I mentioned above.  I know this it is not a permissions issue because of this testing.
I tried running the command you mentioned above and it appears that the process fails when it fails at dir12 and never makes it to any of the child directories beyond that point.  The process works fine up through dir11.
Works fine at this level
\\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\dir9\dir10\dir11
Fails for all at this level
\\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\dir9\dir10\dir11\dir12
Let me know if you have any other ideas.

Similar Messages

  • Powershell Get-childItem: The specified path, file name, or both are too long.

    Hey Scriping Guys!
    I've been using a PowerShell script for a couple of years now to generate a monthly report showing the size of user folders on a number of departmental file servers.  It's working just fine on all file servers except one where the users have gotten carried away with creating sub-folders and using realy long descriptive file names.  The problem piece of script is this:
    $colItems = (Get-ChildItem \\192.168.10.5\marketing -recurse | Measure-Object -property length -sum)
    "marketing-serv\marketing: "+"{0:N2}" -f ($colItems.sum / 1GB) + " GB"
    The reply I get is:
    Get-ChildItem : The specified path, file name, or both are too long. The fully
    qualified file name must be less than 260 characters, and the directory name mu
    st be less than 248 characters.
    At G:\data\Server_space_Report\serverspace2.ps1:37 char:27
    + $colItems = (Get-ChildItem  <<<< \\192.168.10.5\marketing -recurse | Measure-Obje
    ct -property length -sum)
    Yes, the message is correct, however, when I connect to the server, right click the folder and chose properties it returns a size of 128 GB.  My questions are
    1. Why does clicking on folder properties not produce an error (what is it doing differently from my script)?
    2. How can I fix my script?
    Thanks,

    I am trying to clear up the older open posts on this forum. If this is still an unresolved issue for you please let me know. If you do not post back within one week I will assume it is resolved and will close this thread.
    Thank you
    Ed Wilson
    Microsoft Scripting Guy

  • Get-Childitem with Get-FileHash Info

    Hello,
    I have been able run the following script to get File names in a Recurse folders, although I'm looking to use Get-Filehast too, although I'm not sure or unable to tag this on the end of this script File-filehast info.  could you advise.
    my current Get-Childitem script
    get-childitem'\\folder1\folder2\folder3'-recurse|
    Add-Member
    -MemberTypeScriptProperty-NameVersion-Value{
    $this
    .VersionInfo.ProductVersion
    -PassThru|
    select-object
    DirectoryName,Name,Version,LastWriteTime,Length|where{
    $_.DirectoryName
    -ne$NULL}

    Hi I'm outputting to a text file, which I'm then importing into a database, although I have the following objects
    of which I looking to get also hash (Algorithm SHA256) file values as well.  Thanks
    ( DirectoryName,Name,Version,LastWriteTime,Length
    my code is this & screen print from PowerShell
    get-childitem'\\ServerShare\Folder1\Folder2\FolderData'-recurse|
    Add-Member
    -MemberTypeScriptProperty-NameVersion-Value{
    $this
    .VersionInfo.ProductVersion
    -PassThru|
    select-object
    DirectoryName,Name,Version,LastWriteTime,Length|where{
    $_.DirectoryName
    -ne$NULL}
    |Export-Csv-PathC:\folder0\data1.txt
     

  • Inconsistency between get-childitem -include and -exclude parameters

    Hi,
    Powershell 2.0
    Does anyone else consider this a minor design bug in the Get-ChildItem command?  
    # create dummy files
    "a","b","c" | % {$null | out-file "c:\temp\$_.txt"}
    # this "fails", returns nothing
    get-childitem c:\temp -include a*,b*
    # this "works", returns desired files
    get-childitem c:\temp\* -include a*,b*
    # this "works", excludes undesired files
    get-childitem c:\temp -exclude a*,b*
    # this "fails", excludes undesired files BUT RECURSES sub-directories
    get-childitem c:\temp\* -exclude a*,b*
    I'm writing a wrapper script around the GCI cmdlet, but the inconsistency between the two parameters is problematic.  My end user will surely just type a path for the path parameter, then wonder why -include returned nothing.  I can't unconditionally
    add an asterisk to the path parameter, since that messes up the exclude output.
    I'm just wondering why Microsoft didn't make the parameter interaction consistent???  
    # includes desired files in the specified path
    get-childitem -path c:\temp -include a*,b*
    # excludes undesired files in the specified path
    get-childitem -path c:\temp -exclude a*,b*
    # combine both options
    get-childitem -path c:\temp -include a*,b* -exclude *.log,*.tmp
    # same as above, the asterisk doesn't matter
    get-childitem -path c:\temp\* -include a*,b*
    get-childitem -path c:\temp\* -exclude a*,b*
    get-childitem -path c:\temp\* -include a*,b* -exclude *.log,*.tmp
    # same as above, but explicitly recurse if that's what you want
    get-childitem -path c:\temp\* -include a*,b* -recurse
    get-childitem -path c:\temp\* -exclude a*,b* -recurse
    get-childitem -path c:\temp\* -include a*,b* -exclude *.log,*tmp -recurse
    If I execute the "naked" get-childitem command, the asterisk doesn't matter...
    # same results
    get-childitem c:\temp
    get-chileitem c:\temp\*
    If this isn't considered a bug, can you explain why the inconsistency between the two parameters when combined with the -path parameter?
    Thanks,
    Scott

    The Get-ChildItem cmdlet syntax is horrific for advanced use. It's not a bug in the classic sense, so you shouldn't call it that. However, feel free to call it awful, ugly, disastrous, or any other deprecatory adjective you like - it really is
    nasty.
    Get-ChildItem's unusual behavior is rooted in one of the more 'intense' dialogues between developers and users in the beta period. Here's how I recall it working out; some details are a bit fuzzy for me at this point.
    Get-ChildItem's original design was as a tool for enumerating items in a namespace -
    similar to but not equivalent to dir and
    ls. The syntax and usage was going to conform to standard PowerShell (Monad at the time) guidelines.
    In a nutshell, what this means is that the Path parameter would have truly just meant Path - it would not have been usable as a combination path specification and result filter, which it is now. In other words
    (1) dir c:\temp
    means you wanted to return children of the container c:\temp
    (2) dir c:\temp\*
    means you wanted to return children of all containers inside
    c:\temp. With (2), you would never get c:\tmp\a.txt returned, since a.txt is not a container.
    There are reasons that this was a good idea. The parameter names and filtering behavior was consistent with the evolving PowerShell design standards, and best of all the tool would be straightforward to stub in for use by namespace
    providers consistently.
    However, this produced a lot of heated discussion. A rational, orthogonal tool would not allow the convenience we get with the dir command for doing things like this:
    (3) dir c:\tmp\a*.txt
    Possibly more important was the "crash" factor.  It's so instinctive for admins to do things like (3) that our fingers do the typing when we list directories, and the instant failure or worse, weird, dissonant output we would get with a more pure Path
    parameter is exactly like slamming into a brick wall.
    At this point, I get a little fuzzy about the details, but I believe the Get-ChildItem syntax was settled on as a compromise that wouldn't derail people expecting files when they do (3), but would still allow more complex use.  I think that this
    is done essentially by treating all files as though they are containers for themselves. This saves a lot of pain in basic use, but introduces other pain for advanced use.
    This may shed some light on why the tool is a bit twisted, but it doesn't do a lot to help with your particular wrapping problem. You'll almost certainly need to do some more complicated things in attempting to wrap up Get-ChildItem. Can you describe some
    details of what your intent is with the wrapper? What kind of searches by what kind of users, maybe? With those details, it's likely people can point out some specific approaches that can give more consistent results.

  • Get-ChildItem Issue With Variable

    I hope some very clever person out there can resolve this without even thinking, however my brain seems to be blocked.
    $FileVersion
    = (Get-ChildItem
    C:\Windows\System32\drivers\somedriver.SYS).VersionInfo
    |
    Select-Object
    FileVersion
    If ($FileVersion
    -eq
    "2, 0, 0, 1") {Copy-Item
    -Force
    "C:\local\somedriver.SYS","C:\Windows\System32\drivers\somedriver.SYS"} 
    I have verified this and $FileVersion does in fact equal 2, 0, 0, 1 however starts as a formatted table.
    FileVersion
    2, 0, 0, 1
    I think it must be passing the variable as the whole table, I also tried adding in my if statement the value @{FileVersion=2, 0, 0, 1 however that also failed.
    Any ideas what I'm missing here?
    Many Thanks

    If the strings are not in the same format then the files are not the same.  Simple logic.  IF they are in the same format and compare exactly then the strings are identical.  Who cares what is in them?
    Comparing to equal will always work.  If they do not compare as equal you know the files are different.
    That is all. That is all I said.  No need to make more of it.
    ¯\_(ツ)_/¯
    You never answered how you're getting this string. Again, as I've said in more than one post now, if you're using .VersionInfo.FileVersion, that string is not accurate for a significant number of files (especially Microsoft files).
    You are correct when you say that if the strings don't match they're not the same. But you're forgetting that the strings may be the same and yet the file isn't the same. To me, that's a big deal. If you're cataloging file versions, your information could
    be incorrect.
    Here's a scenario:
    1. I check the 'mshtml.dll' VersionInfo.FileVersion today. It reports back that it is '11.00.9600.16410 (winblue_gdr.130923-1706)'.
    It is actually at version '11.0.9600.16476' (which can be confirmed by using Explorer or by combining the File*Part
    properties as in previous posts).
    2. An Internet Explorer patch comes along that updates the file to '11.0.9600.16482' (something higher than 16476)
    3. I check the version of the file again using the VersionInfo.FileVersion property. It reports back '11.00.9600.16410
    (winblue_gdr.130923-1706)', which is the same thing it showed before the patch. The file is obviously different, but the FileVersion property is reporting that it hasn't changed.
    So, if you're using that property, you will miss file changes on a significant number of files. 'mshtml.dll' is just one example. Go back and read my example to get a list of DLLs
    from system32 that are affected by this (remember, you will get some false positives).
    If you're combining the File*Part properties (which is what both Bill and I do), then the version will always be in a known format, and then all of the stuff you said about not being
    able to compare them is simply not correct.
    So, how are you proposing that someone gets a file's version from PowerShell?

  • Get-ChildItem with -LiteralPath is throwing "The specified wildcard character pattern is not valid" when filenames contain brackets

    I'm trying to get a list of folders in a hierarchy that don't contain any mp3 files. (The goal here is to eventually clean up all the "empty" folders that only have album art, thumbs.db, desktop.ini, etc. files left). So I wrote a quick PowerShell
    command to try to do this. But it doesn't seem to be working.
    I already checked out this thread <Get-ChildItem
    SomeFile[].txt occurs error because of the [brackets]: "specified wildcard pattern not valid"> and I think I'm using LiteralPath correctly. Any other hints for troubleshooting this problem? Here's the command I'm using.
    Get-ChildItem -Recurse -Directory | ?{
    @( @(Get-ChildItem -LiteralPath $_.FullName -Recurse) | ?{
    $_.Extension -eq ".mp3"}).Count -eq 0 }
    This is on the latest version of PowerShell found in Windows Technical Preview.

    Fair enough, but it still doesn't answer the original question- why isn't this working with -LiteralPath when the path contains brackets? 
    Get-ChildItem -Recurse -Directory | ?{
    @( @(Get-ChildItem -LiteralPath $_.FullName -Recurse) | ?{
    $_.Extension -eq ".mp3"}).Count -eq 0 }
    Thanks,
    Ben

  • Get-Childitem with millions of files

    Hello all,
    My task is to create a report with all subfolders in a given path, sorted after the newest LastWriteTime on any file in the folder.
    The ultimate reason is to determine which folders have been unused for long enough to move to offline storage.
    So far I've come up with this:
    Get-ChildItem $folderpath | Where {$_.PsIsContainer} | foreach-object { Get-ChildItem $_ -Recurse -ErrorAction SilentlyContinue | Where {!$_.PsIsContainer} | Select Name,DirectoryName, LastWriteTime, Mode | Sort LastWriteTime -descending | select -first
    1}|export-csv $drive:\report.csv
    I know this works, I've tested it on a couple of folders.
    The problem is that the folder I really want to run the report for contains approximately 6.5 million files in many thousands of subfolders. Memory usage goes through the roof, server gets unresponsive, I have to kill the script before users get angry.
    I suppose that PowerShell tries to create an array in memory before actually piping and sorting, and that's the reason for the memory problem.
    Is there a smarter way to do it?

    It is all on 1 line, everything is going through the pipeline, it has to do each part of the pipeline before it`s gets to the next part of the pipeline.
    Do each each folder separately, here is a function to step through a folder structure recursively. Customize it for your needs. The maximum amount of resources used will be limited to one folder.
    function Recurse-Folders([string]$path) {
    Set-Location -Path $Path
    # $L = Get-Location
    # Do something at this location
    [String[]]$Folders = Get-ChildItem "." -Directory
    ForEach ($F in $Folders)
    Recurse-Folders($F)
    Set-Location -Path ".."

  • Get-ChildItem : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

    Hi, Im trying to get the whole path in my server, so i tried that with this following code
    Get-ChildItem $sourceFolder  -Recurse | ?{$_.PsIsContainer} |Get-Acl
    But then, it showed me somtehing like this :
    Get-ChildItem : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
     I tried to find the solver everywhere and mostly they propose to change the path name, which is impossible, since I am working with my company server, and those folder have already there before i start to work here, then the other ask me to use robocopy,
    but all of the trick just dont work
    is there any way to solve this problem? thanks

    There is no simple solution to this. And it is not a limitation of powershell itself, but of the underlying NTFS file system.
    If the problem is that a folder with a name longer than 248 exists anywhere within your directory structure, you are hooped.
    If the problem is that some fully qualified path names exceed 260 characters, then, in those cases, the solution already given is to create a psdrive partway up the path from the drive letter or server/share root of the path. Unfortunately, the output produced
    will be relative to that psdrive and not to what is specified as the $sourcefolder.
    unless you already know where those problematic paths are, you might consider trying to trap those errors and have your script figure out where it needs to create psdrives. You might then be able to calculate the equivalent path for each file or folder and
    output that. the programming effort would be simpler to just created a psdrive for each folder encountered, however I expect that would be very inefficient.
    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

  • Using get -childitem to scan different drives but append one text file.

    Folks,
    I need some help, I wrote the below to scan for certain files types on client machines but I cant get the script to scan anything other than the C$. Apologies I am kind of new to scripting and PS. The script is kicked off using a batch file that makes the
    CR directory on the clients. I think the problem stems from the $disk variable or the way I have used foreach or the loop - any help would be appreciated
    Set-Location c:\
    $s = new-object -comObject SAPI.SPVoice
    $s.speak("Scan in progress")
    write-host "Scanning for files"
    $Extension = @("*.zip","*.rar","*.ppt","*.pdf")
    $Path = "$env:userprofile\Desktop"
    $disks = "c$","D$"
    foreach ($disks in $disks)
    {get-childitem -force -include $Extension -recurs -EA SilentlyContinue >$path\files.txt}
    $s.speak("Scan completed")
    Write-Host "Scan complete, files.txt created on your desktop - press any key to exit..."
    $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")
    Remove-Item c:\cr -recurse -EA SilentlyContinue
    exit

    Then there is "$x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")" , What are you trying to do?
    It looks like that is a pause after the code has completed to give the user time to read the message prior to exiting.
    @V Sharma - As gaff-jakobs has mentioned, there are some parts of your code that need looked at. Please take a look at what he has advised and make the necessary changes. If you want to append data (doing a > does not append), I would look at using Out-File
    -Append -FilePath <filename> to accomplish this. 
    Usually, outputting to a text file limits what you can do with the output once it goes to a text file. I would look at using something such as Export-Csv -Append -Path instead (assuming you are running PowerShell V3). But if saving to a text file is part
    of your requirement, then just be sure to use the first method I mentioned.
    Boe Prox
    Blog |
    Twitter
    PoshWSUS |
    PoshPAIG | PoshChat |
    PoshEventUI
    PowerShell Deep Dives Book

  • Powershell Get-Acl not allowed Exception

    Hello
    On some objects, i get "Requested registry access is not allowed" with get-acl. But when i try to access to this object with regedit, i can enumerate Access rights.
    The perfect example is the command  get-acl hklm:\security
    i don't understand why i have sufficient access rights with regedit and not with Get-Acl ?

    Actually David is closer on that key>
    If we do this you will see also why:
    PS C:\scripts> `cd hklm:
    PS HKLM:\> dir
    Name                           Property
    BCD00000000
    HARDWARE
    SAM
    dir : Requested registry access is not allowed.
    At line:1 char:1
    + dir
    + ~~~
        + CategoryInfo          : PermissionDenied: (HKEY_LOCAL_MACHINE\SECURITY:String) [Get-ChildItem], SecurityExceptio
       n
        + FullyQualifiedErrorId : System.Security.SecurityException,Microsoft.PowerShell.Commands.GetChildItemCommand
    SOFTWARE                       (default) :
    SYSTEM
    PS HKLM:\>
    ¯\_(ツ)_/¯

  • CM-ImportDriver and Get-ChildItem

    I am trying to use the CM-ImportDriver Cmdlet and running into a problem.  After I import the module, I change my site to ABC1:.  From there, I cannot use Get-ChildItem for a UNC path and the CM-ImportDriver throws an error saying it needs a valid
    driver to import.  That happens because it cannot access the UNC path from earlier.  If I change back to C:, then I can run Get-ChildItem with no problem.  What do I need to do in order to bridge the gap between using C: and ABC1:? 
    The CM-ImportDriver requires a UNC path to pull the stored drivers from, which is fine. However, I cannot get it to read the UNC paths provided.   Thanks in advance. 
    Best, Jacob I'm a PC.

    Hi,
    This is taken from here Get-ChildItem - In its basic form the Get-ChildItem cmdlet provides functionality similar to the dir command. For example, if you simply type Get-ChildItem
    at the Windows PowerShell prompt you’ll get back information about the objects in the current location.
    For example this lists HKLM registry child items
    Set-Location HKLM:
    Get-ChildItem
    For example this lists C:\ drive child items
    Set-Location C:\
    Get-ChildItem
    For example in CM 2012 R2 it lists all the admin console nodes
    Set-Location PS1:\
    Get-ChildItem
    You need to query the driver sources before you change the connection context to your site code. For example like this
    #Step 1
    Set-Location C:\
    $Drivers = Get-childitem -path "\\cm01\Sources\OSD\Drivers\Sources\Lenovo\W7x64\T500" -Recurse -Filter "*.inf"
    #Step 2
    Set-Location PS1:\
    foreach($item in $Drivers)
    Import-CMDriver -UncFileLocation $item.FullName
    Best,
    Kaido

  • Get-ChildItem directory only (not full path) on error output

    Hello,
    I currently use the snippet below to check for folder permissions, it outputs a CSV file which details Category, Reason and TargetName. When I open my error.csv file I see the 3 columns being populated, but how can I get a 4th column with the directory name
    as well? TargetName outputs the complete path to the folder, I want to also include the directory name in the CSV.
    $Path = "C:\test"
    $errors=@()
    get-childitem -recurse $Path -ea silentlycontinue -ErrorVariable +errors | Out-Null
    $errors | select -expand categoryinfo | select category,reason,targetname | export-csv -NoTypeInformation -Delimiter “,” .\error.csv
    Any help would be appreciated. At this point I dont think getting the directory name only is feasible with my method. I've tried many exampled but cant seem to get it. As easy as it may sound.
    Thank you.

    Hi jrv,
    I plugged in your suggestion as follows:
    $Path = "C:\test"
    $errors=@()
    get-childitem $Path -recurse -ea silentlycontinue -ErrorVariable +errors | Out-Null
    $errors | Select TargetObject
    It works but I'm still receiving the full path to the directory. How can I get only the directory name?
    You cannot use $errors.  It is owned by the system and will give you issues.
    If you want a folder name from a full path just use Split-Path
    I took the + out for a reason. It was not a mistake and I changed the name of the variable for a reason.  The custom error variable will fill with all errors and will be created new each time this is run. Try it without changing it incorrectly until
    you understand what is happening.  Don't just blindly do things because it feels good or because you saw a friend do it.
    $Path = 'C:\test'
    get-childitem  $Path -recurse -ea silentlycontinue -ErrorVariable myerrors| Out-Null
    $myerrors| %{Split-Path $_.TargetObject -leaf }
    PowerShell is very easy If you take the time to learn it. If you just guess you will never learn.  Believe me you could never guess how it works short of a course in software engineering.
    ¯\_(ツ)_/¯

  • Get-ChildItem BaseName returing @{} in value

    A folder contains a number of encrypted files named like...SB_SeminoleCounty_Dispatch_1.bak.gpg.  I need the base file name without the.gpg extension.
    If I execute the this command in powershell I get the expected value
    PS L:\SQLServerBackupFile> gci .\SB_SeminoleCounty_Dispatch_1.bak.gpg  | select basename
    BaseName
    SB_SeminoleCounty_Dispatch_1.bak
    I am trying to retrieve the same information in my script
    ..some code..
    $fileDirectory  = 'L:\SQLServerBackupFile'
    foreach($file in Get-ChildItem $fileDirectory | where {! $_.PSIsContainer} | Sort-Object name -unique )
    $DecryptedFileName = Get-ChildItem $fileDirectory\$file | select {$_.BaseName}
    Write-Host "Base file name: " $DecryptedFileName
    The output is:
    Base file name:  @{$_.basename=SB_SeminoleCounty_Dispatch_1.bak}
    How can I get just the value of the file name ..SB_SeminoleCounty_Dispatch_1.bak without @{$_.basename=..}?
    Of course, I am sure there is a better alternative so any suggestions are appreciated.
    Thanks

    This works.  I was not sure if you intended for me to modify my original statement  foreach($file in Get-ChildItem $fileDirectory..
    I was trying to retrieve information with my original code and might be able to replace my foreach with your logic.  I did not want to try too many things until I fixed my original question.  But your construct is very helpful.
    I added your suggestion into the current foreach and it works. 
    I will comment on the other two posts.  Their suggestion worked with a slight modification
    $DecryptedFileName = $file.BaseName
    I like this command because it is one line.  I actually tried calling $file.FullName oreviously, but it did not work.  I must have had something else wrong.  I am just learning powershell.
    Thanks for your feedback.

  • Get-ChildItem on version 2.0 vs 3.0

    Not sure if this has been discussed or is known, but I found an interesting issue when running Get-ChildItem on version 2.0 vs 3.0
    So I have the simple command of
    $files = Get-ChildItem -Path $Source -Recurse -ErrorAction SilentlyContinue -ErrorVariable myError
    If $Source only contains 1 file, then $files is of type System.IO.FileInfo, whereas, if there are more than one, it would be of type Syste.Array. I actually thought $files would always be a collection, no mater if there was one or multiple files, but obviously
    I was wrong.
    So with thinking it will always be a collection, I used $files.Count for my Write-Progress
    Write-Progress -Activity "Backing up Files" -Status "File: $src-->$dest" -PercentComplete ($counter / $files.Count*100)
    Everything on my machine worked and I am running version 3.0, so I put the script on a machine that was running 2.0 and the Write-Progress failed with cannot divide by zero..hmmmmm
    So doing a little testing, I ran the Get-ChildItem command on version 2.0 and then did $files.Count which returned nothing due to $files being System.IO.FileInfo, and it doesn't have a property of Count, but if you run it on version 3.0 and then do $files.Count,
    even though $files doesn't have a Count property when it is of type Syste.IO.FileInfo or System.IO.DirectoryInfo, it will return 1
    If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.
    Don't Retire Technet

    In PowerShell 3.0 or later, you can check a .Count property on any value (even $null.Count); it was added along with the Member Enumeration feature.  This works for .Length as well.  If no property / field named Count or Length exists on the object,
    PowerShell will enumerate it for you and return the number of objects
    When you're needing to support PowerShell 2.0, you need to be more careful.
    On a side note, use the syntax in Boe's last post, with the @() operator around the command that you ran.  There's a subtle difference between these two:
    $files = @(dir DoesNotExist.txt -ErrorAction SilentlyContinue)
    $temp = dir DoesNotExist.txt -ErrorAction SilentlyContinue
    $files2 = @($temp)
    $files.Count # 0
    $files2.Count # In PowerShell 2.0, this will be 1. In 3.0 or later, it's 0.
    This is because there are technically two different kinds of Null values that the PowerShell engine recognizes:  actual null references, and a value called AutomationNull, which is used to represent a command which didn't output anything.  In PowerShell
    2.0, when you assign the result of a command to a variable, it didn't keep track of whether the result was AutomationNull or not, resulting in this weird behavior.  3.0 and later correct this.
    Here are a couple of other demonstrations of this in action:
    $array1 = @($null)
    $array2 = @([System.Management.Automation.Internal.AutomationNull]::Value)
    $array1.Count # 1
    $array2.Count # 0
    function ReturnsNull { return $null }
    function ReturnsNothing { }
    $array1 = @(ReturnsNull)
    $array2 = @(ReturnsNothing)
    $array1.Count # 1
    $array2.Count # 0

  • Powershell - Get size of files listed in an array

    Hi there! I'm a newbie in powershell. As you can see, maybe my problem is kinda easy but i'm getting nuts over here.
    I got this object, that is an array
    PS C:\scripts\CleanScan> $gotFiles.GetType()
    IsPublic IsSerial Name                                     BaseType                            
    True     True     Object[]                                 System.Array  
    It came from an query gci
    $gotFiles = Get-ChildItem -Path $path -Recurse | Where-Object {$_.CreationTime -lt $limit}
    It gets the files in a directory older than $limit 
    Then my problem: Need to get the size in KB of each item in the array.
    Any help would be appreciated.

    GetType has it's value, but not for what you're trying to learn.  You want to use Get-Member to show the methods and properties you can use with your $GotFiles object, which actually consists of System.IO objects:
    $gotfiles | Get-Member
       TypeName: System.IO.DirectoryInfo
    Name                      MemberType     Definition
    Mode                      CodeProperty   System.String Mode{get=Mode;}
    Create                    Method         System.Void Create(System.Security.AccessControl.DirectorySecurity director...
    CreateObjRef              Method         System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
    <lots of other stuff here>
    Parent                    Property       System.IO.DirectoryInfo Parent {get;}
    Root                      Property       System.IO.DirectoryInfo Root {get;}
    BaseName                  ScriptProperty System.Object BaseName {get=$this.Name;}
       TypeName: System.IO.FileInfo
    Name                      MemberType     Definition
    Mode                      CodeProperty   System.String Mode{get=Mode;}
    AppendText                Method         System.IO.StreamWriter AppendText()
    <still more stuff here>
    Length                    Property       System.Int64 Length {get;}
    Name                      Property       System.String Name {get;}
    The first section applies to directories because there's a directory in my path, so don't worry about that for now.  The second section has a Length property that might help:
    PS C:\temp\scratch> $gotfiles.length
    7
    Nope, that's just the number of files
    PS C:\temp\scratch> $gotfiles
        Directory: C:\temp\scratch
    Mode                LastWriteTime     Length Name
    d----         3/25/2014   3:13 PM            NTFSSecurity
    -a---         3/24/2014  12:27 PM         94 data.csv
    -a---         3/26/2014  12:48 PM         51 grp - Copy.csv
    -a---         3/27/2014   8:39 AM        104 grp.csv
    -a---         3/27/2014   8:28 AM         60 grp2.csv
    -a---         3/27/2014   8:34 AM        104 grp3.csv
    -a---         3/25/2014  12:23 PM      37003 obs.xml
    You can see the Length property right there in the output, in bytes
    PS C:\temp\scratch> $gotfiles | select name, length
    Name                                                        length
    NTFSSecurity
    data.csv                                                    94
    grp - Copy.csv                                              51
    grp.csv                                                     104
    grp2.csv                                                    60
    grp3.csv                                                    104
    obs.xml                                                     37003
    Then to make a report about this
    $gotfiles | select fullname, length | export-csv c:\filesizereport.csv -NoType
    Your code might look like this just to get the output:
    $gotFiles = Get-ChildItem -Path $path -Recurse | Where-Object {$_.CreationTime -lt $limit} | select fullname, @{name="Size in KB";expression={$_.length / 1024}}
    That last bit converts to KB. 
    I hope this post has helped!

Maybe you are looking for

  • 2.3.11 and 2.4.13 fail tests on OpenSuse 10.3 x86_64

    I am trying to get php and perl API of BDBXML 2.3.11 and 2.4.13 running on OpenSuse 10.3 x86_64 when using --enable-perl the perl tests fail so i tried to run the test suite and compare it against 32bit builds. 2.3.11 after changing dbxml/dist/config

  • Hard drive failure (why can't I start up with boot disk)?

    Running OS 10.4.6. I was getting flashing question mark at startup. Tried starting with Disk Warrior holding down "C" key. Got Apple logo, but then screen frooze with horizontal lines across screen. Rebooted, held mouse to eject disk. Tried TechTool

  • Trouble uploading iweb site

    I have created my site in iWeb '08 and published it to a folder. I am uploading it to a domain I have with MacHighway via FTP (Cyberduck). When all files are finished uploading, I visit the site on safari and only text appears. No images, music, or p

  • Hyperion Shared Services getting HTTP404 error

    Hi All, I am trying to get Hyperion 11 Shared Services working, however i am getting this http://404 error. I am using Web Sphere as my web agent, i have check and validated during the configuration and all is good, except for the 404 error. Does any

  • Can't open any website

    I can't open any website using Firefox. I tried for 4 hours this morning, just blank, or "loading" (but nothing actually loaded). Finally got google partially open but not completely. Shut down my computer about 50 times, had my internet provider che