Filter Get-ChildItem on TargetPath?

With Get-ChildItem is it possible to filter on a shortcut's TargetPath? I did a Get-Member on a shortcut and I don't see anything there that looks promising, so I am filtering to just get shortcuts, then looping and evaluating 
if (($Shell.CreateShortcut($Shortcut.FullName)).TargetPath -eq $Document)
where $Document is the TargetPath I am looking for. And it works. But I wonder if there is a pipeline way to do it, rather than the loop?

Hi Gordon,
I'm afraid not, because the "$Shell.CreateShortcut" doesn't accept array, and we also can't find the targetpath information with the cmdlet "Get-Childitem", so the foreach seems a good way:
Get-ChildItem d:\*lnk -Recurse|Select-Object -ExpandProperty fullname|foreach{
$Shortcut = New-Object -COM WScript.Shell
$Shortcut.CreateShortcut($_).TargetPath}
Best Regards,
Anna Wang
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]

Similar Messages

  • Filter Objects returned by Get-ChildItem

    Hello there,
    I had a look at the properties available for objects returned by Get-ChildItem command using:
    PS C:\> Get-ChildItem | Get-Member
    This command shows that objects returned by Get-ChildItem command possess properties
    'Name, FullName, LastAccessTime etc...'
    If I declare a variable to retrieve objects starting with 'Program':
    PS C:\> $ChildItems_Program = Get-ChildItem -name 'Program*'
    and check what is stored in $ChildItems_Program, it shows me two objects/items as shown below:
    PS C:\> $ChildItems_Program
    Program Files
    Program Files (x86)
    However if I try to access properties 'Name, FullName, LastAccessTime' from the first object saved in $ChildItems_Program
    PS C:\> $ChildItems_Program[0] | Select -Property Name, FullName, LastAccessTime
    Name FullName LastAccessTime
    I can't see any results for above command- Shouldn't it return the properties of first object saved in $ChildItems_Program?
    Can anyone please guide.
    Thank you!
        

    Hi,
    Tommy is right, using -Name doesn't actually return the full object. When you use that parameter, you're getting back an array of names only. Here's how you can tell:
    PS C:\> $ci_program = Get-ChildItem -Name 'Program*'
    PS C:\> $ci_program.GetType()
    IsPublic IsSerial Name BaseType
    True True Object[] System.Array
    PS C:\> $ci_program[0].GetType()
    IsPublic IsSerial Name BaseType
    True True String System.Object
    PS C:\> $ci_program[0] | Get-Member -MemberType Property
    TypeName: System.String
    Name MemberType Definition
    Length Property int Length {get;}
    PS C:\> $ci_program
    Program Files
    Program Files (x86)
    Here's what you should see if you get objects back from gci, using -Filter (I use -Path here):
    PS C:\> $ci_program_object = Get-ChildItem -Path 'Program*'
    PS C:\> $ci_program_object.GetType()
    IsPublic IsSerial Name BaseType
    True True Object[] System.Array
    PS C:\> $ci_program_object[0].GetType()
    IsPublic IsSerial Name BaseType
    True True DirectoryInfo System.IO.FileSystemInfo
    PS C:\> $ci_program_object[0] | Get-Member -MemberType Property
    TypeName: System.IO.DirectoryInfo
    Name MemberType Definition
    Attributes Property System.IO.FileAttributes Attributes {get;set;}
    CreationTime Property datetime CreationTime {get;set;}
    CreationTimeUtc Property datetime CreationTimeUtc {get;set;}
    Exists Property bool Exists {get;}
    Extension Property string Extension {get;}
    FullName Property string FullName {get;}
    LastAccessTime Property datetime LastAccessTime {get;set;}
    LastAccessTimeUtc Property datetime LastAccessTimeUtc {get;set;}
    LastWriteTime Property datetime LastWriteTime {get;set;}
    LastWriteTimeUtc Property datetime LastWriteTimeUtc {get;set;}
    Name Property string Name {get;}
    Parent Property System.IO.DirectoryInfo Parent {get;}
    Root Property System.IO.DirectoryInfo Root {get;}
    PS C:\> $ci_program_object
    Directory: C:\
    Mode LastWriteTime Length Name
    d-r-- 1/26/2014 12:40 AM Program Files
    d-r-- 3/28/2014 12:07 PM Program Files (x86)
    Don't retire TechNet! -
    (Don't give up yet - 12,700+ strong and growing)

  • 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.

  • 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

  • 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.

  • 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 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
     

  • 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 issue when sending mail

    I'm having a problem where the below command works but not the way it should. For example, if i have two files it will display both files in the email instead of just one. 
    $fname=Get-ChildItem \\Main\Drop| Where-Object {!$_.PSIsContainer}
    and here is the body of the email
    $Body = "Check Drop Folder for new file: `n $fname `n`nOR `nclick here: \\Main\Drop\$fname"
    If i have 2 files in that drop directory say: file1.txt, file2.txt the email will say:
    Check Drop Folder for new file:
    file1.txt file2.txt
    OR
    click here: \\main\Drop\file1.txt file2.txt
    I know its a simple fix but im missing it..

    The idea here is to get only ONE email PER FILE, i do not want to combine the files in one email. So for two files, i will have two emails. 
    Okay, here's a start:
    Get-ChildItem \\Main\Drop | ForEach {
    $body = "Check the drop folder for $($_.Name)"
    Send-MailMessage -To [email protected] -From [email protected] -Subject $body -Body $body -SmtpServer smtp.domain.com
    Don't retire TechNet! -
    (Don't give up yet - 12,575+ strong and growing)

  • 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 : 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

  • 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.

Maybe you are looking for

  • HOw can i show a table(name given in parameters) in a report program

    I made a report in which there is a paremeter asking for a table name .... PARAMETERS TBLLE_NAME(10) OBLIGATORY. Now when I enter the table namke then how can i show its values.... HINT:- We have to use fiels symbols....AND THE USER CAN ENTER ANY DDI

  • Screen resolution in Vista Ultimate in Boot camp cant' select HD

    I am using a new imac 24" and can only seem to increase the screen resolution to 1600 x1200. Shouldn't I be able to select HD 1080 x 1900

  • Payment terms change in MIRO

    Hi All, If the proposed payment terms are changed in the MIRO, (other than the payment terms in PO or vendor master), then the MIRO/ Invoice document should be blocked and should not allow vendor payment. Please let me know the procedure for this. Th

  • UK based Alliance Member looking for local and remote opportunities

    Austin Consultants is looking for contract and part time opportunities in the whole of UK and Europe and remote work for companies all over the world. With the current exchange rate situation, we have become really cost-effective for our clients in A

  • COGS transfer to  COPA failed

    Dear friend:    I  have assigned VPRS to a value field,but COGS is not transferred to COPA after i billed,revenue succeds in transferred to COPA(the goods using average moving price and no cost releasing and marking)!    Who could tell me why!    Tha