Get-ChildItem is not showing all files in a folder - powershell

When I call Get-ChildItem in PowerShell it is only returning a few of the files that exist in the directory. This is the driver folder, so I tried using the -Force parameter in case they were hidden, but with no luck.
It's interesting though because it works perfect on my Windows 7 32 bit, but not 64 bit. Any ideas?

I believe PowerShell is showing you everything however the folder you're looking at in the x86 PowerShell prompt isn't what you think. The directory you're actually looking at is under C:\Windows\SysWow64\Drivers and not actually C:\Windows\System32\Drivers. This is due to a Windows feature (Vista and higher) for 32-bit processes running on 64-bit OS called virtualization (specifically the File System Redirector). When you run a 64-bit PowerShell prompt virtualization is not used so you see the real C:\Windows\System32\Drives dir.
From a 32-bit PowerShell prompt, you can see the "real" C:\windows\system32\drivers dir by using this path:
Get-ChildItem C:\Windows\SysNative\Drivers

I ran across this while searching for a similar issue. I want to list user folder usage, but run into issues with folder ownership/permissions. Even though I am a local admin, I need to explicitly give myself access. Not ideal. Below gives accurate usage, despite permissions. (Of course, if you want to know more detailed usage, you need to use a for loop or something.)
Get-ChildItem "C:\Users" -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object Length -Sum
As for what files are included, hidden and system files are not shown by default: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-6
Hidden parameter: Hidden files only
System parameter: System files only
Force parameter: Include hidden and system files, with regular files
To confirm, I granted myself permission to one of the user directories. I compared size reported from PowerShell (before granting permission) and that reported in File Explorer (after granting permission). Size and count was the same.

Related

What is the use of -recurse in powershell?

Sorry it's probably a dumb question: what is the difference between
Remove-Item -recurse -Force -Verbose and Remove-Item -Force -Verbose
it seems if we use -recurse for a folder and subfolders powershell delete file one by one inside the folder. and if we remove the -recurse powershell simply delete the main folder without checking inside the folder. technically isn't script will run faster without -recurse?
tl;dr
Pass both -Recurse and -Force to Remove-Item in order to (more) predictably delete (remove) a given folder, which - barring any permission and timing problems - deletes the folder and any contents it may have.
Caveat: This instantly deletes any contents inside the target folder, and, given that deleted items are not placed in the operating system's recycle bin, can only be recovered, potentially, with specialty software.
it seems if we use -recurse for a folder and subfolders powershell delete file one by one inside the folder.
More accurately, it deletes the target folder's subtree, i.e. it recursively deletes all files and subfolders located in the target folder, including their files and subfolders, recursively, before deleting the target folder itself. In effect, it deletes the target folder and all of its contents, if any, but note the caveats:
re "protected" items, which additionally require -Force, discussed below.
re intermittent failures due to the file-system APIs being asynchronous in older Windows versions, discussed in the bottom section.
In fact, deleting all the contents of a folder before deleting the folder itself is the only way to delete a nonempty folder, technically: the file-system APIs do not offer deletion of a nonempty folder as a single operation.
Because inadvertently deleting an entire subfolder tree can have disastrous consequences, as a safety mechanism PowerShell requires you to signal the intent to delete a nonempty folder explicitly - by passing -Recurse.
If you neglect to pass -Recurse and the target folder is nonempty, you get an interactive confirmation prompt - irrespective of whether -Force is specified or not. Choose [A] Yes to All (type a) to delete the folder and all its contents - but see the situational additional need for -Force below.
That said, you do also need -Force in order to (more) predictably remove a nonempty target folder, because -Force makes PowerShell also delete "protected" files and folders, which are hidden files and folders and files that have the ReadOnly and/or System attributes set (on Windows).
If you neglect to pass -Force when you use -Recurse or interactively choose [A] Yes to All in response to the confirmation prompt, the presence of at least one protected item will prevent removal of the target folder as a whole, though unprotected items inside the subtree will get deleted right away.
Each protected item will cause a non-terminating error to be emitted, concluded by a non-terminating error that the target folder cannot be removed, because it isn't empty (yet). Perhaps confusingly, in Windows PowerShell the per-protected-item error messages only talks about "[in]sufficient access rights", even though the real problem in this case isn't one of permissions; the error message has been amended in _PowerShell (Core) 7+ to explicitly mention hidden, system, and readonly items.
if we remove the -recurse powershell simply delete the main folder without checking inside the folder.
No: It follows from the above that you cannot delete a given nonempty folder unless you delete its contents first.
If you attempt that without -Recurse, you'll invariably get the confirmation prompt (or, in non-interactive scenarios, the call will fail outright).
technically isn't script will run faster without -recurse?
It also follows from the above that only an empty folder can be removed without -Recurse without triggering the confirmation prompt.
If you do also specify -Recurse when targeting an empty folder, hypothetically unnecessary work of testing whether child items exist could be performed. In practice, Remove-Item's implementation always performs this test, whether or not you pass -Recurse.
Even with both -Recurse and -Force specified, overall removal may fail:
... due to insufficient file-system permission held by the current user relative to the target folder and its contents.
... intermittently, due to running on Windows versions older than Windows 10 20H2 (I don't know that Windows Server version that corresponds to), because file-system item deletion there was inherently asynchronous(!), resulting in intermittent failure to fully delete a given target folder, namely if deletion of an item inside the folder hadn't completed yet by the time deletion of the folder itself was attempted: see this answer for details and a workaround.
when you use Remove-Item on a dir tree that holds files ... and do NOT use -Recurse, you will get the standard confirmation prompt. so using that parameter makes it run without the delay from the "do you really want to do this?" prompt.
this is one of the reasons that some folks prefer to pipe the output of Get-ChildItem -Recurse to Remove-Item.

Export-Csv - Access to the path 'C:\export.csv' is denied

I'm getting the information I need out of the line, although when I go to export the information, I get an error.
When I run this code:
get-process | Export-csv -Path "C:\export.csv" -NoTypeInformation
I get this error:
Export-csv : Access to the path 'C:\export.csv' is denied.
At line:1 char:14
+ get-process | Export-csv -Path "C:\export.csv" -NoTypeInformation
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How can I export to CSV?
You need to use an admin console or change the location of the csv file to C:\temp or something. The home drive require admin permissions.
EDIT:
The elevation requirement is only with system directories like:
C:\
C:\Windows
C:\Program Files
C:\Program Files (x86)
C:\Users
Notice that you can change C:\Users\<YourUserName> but not any other directories under C:\Users. Windows was built for multiple users even if you may be the only one using it. The above directories are common for all users and changing its contents would effectively change the Windows environment for other users too since windows rely on the integrity of these directories. Allowing a normal user to delete/modify/add files to these could have dangerous results for the OS and other people who use it.
So it tries to makes sure that only an Admin user is authorized to make changes to it. It is also the same reason why you get prompted for admin permissions when installing a software. It is installed to C:\Program Files or C:\Program Files (x86), make changes to the registry and is available to all users of that computer. Same with removing it. If a program does not require to do that, it doesn't require admin privileges. Eg: Portable softwares. Some programs only use the user directory or users temp directory C:\Users\<Username>\AppData\Local\Temp. Such programs are only available to the user that installed it.
If you have a custom directory like C:\myGames, adding files to it wont require elevation. So C:\Temp is just another directory like that. You will also notice that C:\ will let a normal user create a folder but not a file.
SUMMARY: Any changes that affect other user directories or the windows environment will require admin rights. Others don't.
In my case, the error occurred because I failed to specify the file name. The correct syntax is;
Export-Csv -path ".\targetList.csv"
and not -path "."

Powershell Dot Slash .\ Starts at the root of a drive

Note: I'm using the built-in PowerShell ISE as my environment
I got a funny issue with dot slash on Powershell. All of my scripts run from a certain folder and there are subfolders that contain data that is needed for them to run.
For example, my scripts are saved at c:\users\chris\posh
Most of the time, I will call input and send output to subfolders like this...
c:\users\chris\posh\inputs
c:\users\chris\posh\output
Therefore I'll have scripts examples that look like this for inputs and outputs:
$hbslist = Get-Content .\inputs\HBS-IP.txt
write-output "$($lat),$($long)" | Out-File .\Outputs\"LatLong.csv" -Append
Lately, when I run the scripts, it cannot locate my files or exe's that I call on. That's because it's trying to look at P:/ instead of c:\users\chris\posh when using .\
Powershell also starts in my P:\ (mapped share drive) for some reason and I cannot figure out as to why my PC is running this way.
It might be a policy on your machine which changes your home directory. You can check the home directory with:
echo $env:HOME
This happens often on corporate machines. If you want to set it back for your powershell environment, you can set it in your profile.ps1.
This is typically stored at:
c:\Users\<Name>\Documents\WindowsPowershell\profile.ps1

How to run a powershell script at active directory login

I created a group policy in In Group Policy Management Editor, in the navigation pane, expand User Configuration, expand Policies, expand Windows Settings, and then click Scripts (Logon/Logoff). I made a logon script as a ps1 file:
copy-item "\\server1\Pictures\background.jpg" -Destination "C:\screensaver\" -Recurse
I added that ps1 file in the powershell scripts part of the group policy and set it to run powershell scripts first.
I didn't use any parameters which may be causing the issue?
I need each computer to have that c:\screensaver\background.jpg image when they login.
It's the only group policy applied to that OU, all the PCs are Windows 10, and the domain controllers are Windows 2012 r2.
In my opinion creating a (PowerShell-) logon-script for copying a file is not a great solution and out-of-date nowadays.
Make your life easier and use group-policy-preferences for this task. You don't have to create scripts for that.
Open the Group Policy Management Console, select your policy, open the "Preferences"-Node and select "Files". Create a new element and select the source- and the target (as shown below).
After that reboot the client and the file should get copied without coding.
Sounds like there's two parts to implementing your request. Before doing any of the following, make sure that you can log in as one of the users, and manually perform the steps you want the script to complete (to make sure any user restrictions aren't holding you up). So, make sure you can navigate to the remove image location \\server1\Pictures\background.jpg, and copy it to the local folder C:\screensaver.
Copying the file to the target machine. You provided the contents of your PS1 file as copy-item "\server1\Pictures\background.jpg" -Destination "C:\screensaver\" -Recurse. I believe you'll want to have two slashes "\\" at the beginning of your \server1 string, resulting in "\\server1\Pictures\background.jpg" (the two slashes make this a valid UNC path). Additionally, you included the -Recurse parameter. I don't understand the need for this parameter, based off of the documentation, accessible via the command Get-Help Copy-Item -Full.
-Recurse [<SwitchParameters>]
Indicates that this cmdlet performs a recursive copy.
I would suggest that you include the -Force parameter. If you ever update that image, the next time a user logs on, they'll receive the updated image. Without the -Force parameter, the command might not overwrite the existing image on disk. Also, you shouldn't need the trailing slash on the -Destination parameter. I would suggest the command resemble:
Copy-Item "\\server1\Pictures\background.jpg" -Destination "C:\screensaver\" -Force
Configuring the wallpaper via Group Policy The first link I found via Google Search set windows 10 wallpaper via group policy with anything that looked like useful steps was some grouppolicy.biz website. I haven't been able to test them, but the main point being that you'll need to make sure that you're actually telling the computer to use the wallpaper you've copied into place.
If you make sure that you've addressed the above items, then it should work for you. There may be some considerations for the first time a user logs in, if the image isn't copied over, then the wallpaper may not display until the second time they log in.

PowerShell - Trouble copying items remotely with invoke-command and copy-item

I have hundreds of computers on domain I am responsible for and I want to copy a file from a file server to their hard drives locally. If I script this to initiate the copy from my (separate) computer it works just fine via something like;
Copy-Item -LiteralPath \\FILESERVER01\Share\Files\Win7_64\File_to_copy.txt -Destination \\WORKSTATION01\c$\Users\USER\Desktop\ -Force }
However I'd like the script to initiate a copy from the file server to the workstation on the workstation via invoke-command so this isn't done on my machine using something (I assume is) like this:
Invoke-Command -ComputerName WORKSTATION01 -ScriptBlock { Copy-Item -LiteralPath \\FILESERVER01\Share\Files\Win7_64\File_to_copy.txt -Destination \\WORKSTATION01\c$\Users\USER\Desktop\ -Force }
But doing this consistently gives me the error citing the source as the issue - Cannot find path '\FILESERVER01\Share\Files\Win7_64\File_to_copy.txt' because it does not exist. I have access to this network shared path from all machines (via Domain Admin rights), so I believe this is something like a syntax error or problem with the way the UNC path is being resolved but despite reviewing several topics on this I just can't determine what I'm doing wrong with this since I'm using the same UNC paths in the same commands outside the invoke-command cmdlet (and from a PowerShell session on WORKSTATION01) with no issues.
I've tried reviewing and attempting solutions from this link, and also this link. But I can't tell if its a slightly different use case or if I just cant figure out how to adjust the syntax to make it work for me but the Cannot find path error persists
I've tried using New-PSDrive, prefixing the UNC path with "FileSystem:" and even taking the explicitly shared folders out entirely and using only the full path using administrative shares but I just seem to be missing something.
Can anyone shed some light on what I'm missing here?