How to run a powershell script at active directory login - powershell

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.

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.

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

Get-ChildItem File Sorting

I have a script that I run at my work that uses get-childitem to get all the files of a certain type in a storage drive and sorts and moves them to an archive drive. I'd like to automate this process to run once everyday but I realized I would have a problem in doing so.
Occasionally, when this script is run a file or two will still be in the process of transferring over to our storage drive. If I let the script move this file while it is still being transferred from our customer, it gets corrupted and won't open later.
I know how to filter based on file type and date and other basic parameters, but I'm not entirely sure how I tell this script to exclude files that are currently growing in size.
Below is what I'm currently using to filter what I want to move:
$TargetType = "*.SomeFileType"
$TargetDrive = "\\Some\UNC\Path"
Get-ChildItem $targetdrive\$targettype | ForEach-Object {$_.fullname} | Sort-Object | out-file $outStorageMove
Also, at the moment I'm putting everything that get-childitem finds into a text file, that gets invoked later so that I can manually edit what I want it to move. I'd like to get rid of this step if at all possible.
So, move is essentially copy and delete.
So, like gvee state, Copy-Item is a better option, to get you past your stated concern, monitor for the copy to complete. My addition would be to delete once the copy is done and you have verified the copy.
Or use Bits as a job to do this.
Using Windows PowerShell to Create BITS Transfer Jobs
https://msdn.microsoft.com/en-us/library/windows/desktop/ee663885(v=vs.85).aspx
You can use PowerShell cmdlets to create synchronous and asynchronous Background Intelligent Transfer Service (BITS) transfer jobs.
All of the examples in this topic use the Start-BitsTransfer cmdlet. To use the cmdlet, be sure to import the module first. To install the module, run the following command: Import-Module BitsTransfer. For more information, type Get-Help Start-BitsTransfer at the PowerShell prompt.

Powershell: Get the default directory from inside a cmdlet

I'm writing a powershell cmdlet. From inside of my cmdlet BeginProcessing() method, I want to be able to retrieve the the directory that was the default directory at the time the cmdlet was invoked.
Example:
If the user does this:
cd \myDirectory
invoke-mycmdlet
I want for my code to know that the default shell directory was c:\myDirectory.
When I access Environment.CurrentDirectory, it's always c:\windows\system32
I've seen a similar post on SO where the poster needed to set Environment::Current directory from inside the shell using get-location. That won't work for me.
Basically, my cmdlet does some file system stuff, and I want the user to be able to just cd\ into a directory, and execute my cmdlet, with it operating on the directory that they switched into -- just like you would expect it to work from the old Command Console.
You might want to try this instead, CurrentLocation.Path could also point to other provider paths, such as the registery.
this.SessionState.Path.CurrentFileSystemLocation.Path
You know, I always seem to find it right after I post -- regardless of how long I spent looking before reaching for SO!
So, my cmdlet inherits from PsCmdlet. I found that I could get the path I wanted from
this.SessionState.Path.CurrentLocation.Path
(where "this" is a cmdlet class that inherits from PsCmdlet)
Try the Get-Location cmdlet. It should be the script's current executing location, rather than the powershell host startup folder.

Get-ChildItem is not showing all files in a folder

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.