powershell create folder in other userprofile with administrative privilege - powershell

i have a user with standard right, and i need to run a powershell script with admin right to do something, and finnaly create a folder and copy a single file in current logged userprofile.
How i can do this?
example:
C:\Users\USERNAME\FOO\FOO.TXT
i do this but, obviusly, create the folder in my admin profile
# DO SOMETHINGS BEFORE
$directory = $env:USERPROFILE + 'FOO'
if(!(Test-Path -Path $directory)){
New-Item -Path $env:USERPROFILE -Name "FOO" -ItemType "directory"
}
Copy-Item "testo.txt" -Destination $directory
# Copy-Item "arDigiCore.ini" -Destination $arDigiSign
Thanks in advance
EDIT:
1 - i run my powershell script, logged like standard user (e.g. user1), like a admin (e.g. admin1).
2 - the script install a program, and before end, check and in case create a folder in the path C:\Users\users1\foo
NB: I do not know before the name of the user logged in to execute the program

You can use query.exe to pull the current users. Then filter the active user that isn't you.
$user = (((& query user) | ? {$_ -like "*active*" -and $_ -notlike "AdminUserName"}).trim() -Replace '\s+',' ' -Split '\s')[0]
#Credit to Jaap Brasser https://gallery.technet.microsoft.com/scriptcenter/Get-LoggedOnUser-Gathers-7cbe93ea
then convert to a SID and match to the SID returned from Win32_UserProfile
$NTUser = New-Object System.Security.Principal.NTAccount($user)
$SID = ($NTUser.Translate([System.Security.Principal.SecurityIdentifier])).value
$directory = (gcim Win32_UserProfile | ? {$_.sid -eq $SID}).localpath
if(!(Test-Path -Path (Join-Path $directory FOO))){
New-Item -Path $Directory -Name "FOO" -ItemType "directory"
}
Copy-Item "testo.txt" -Destination (Join-Path $directory FOO)

Related

How to copy file from network path to local appdata for each remote PC

So i have a file with PC's and their respective users in a CSV called test.csv; the file looks like this:
Computer, User
pcname1, john.doe
pcname2, jane.doe
My script looks like this
$list = Import-Csv -Path C:\temp\test.csv
ForEach ($Computer in $list) {
Copy-Item -Path \\domain.local\SYSVOL\domain.local\scripts\copyfile.txt -Destination \\$list.Computer\C$\Users\$list.User\AppData\Local\filedepot\
}
The Copy-Item works if i manually enter the PC name and username in the variables.
But as soon as i use the $list. it doesn't work..
If i use echo it does show me the correct data so it does pick up the right info..
Not sure why this doesn't work, any help is appreciated
Use objects, no need to lookup the list twice
$list = Import-Csv -Path C:\temp\test.csv
Foreach($l in $list){
$computer = $l.Computer
$user = $l.User
$sourcepath = "\\domain.local\SYSVOL\domain.local\scripts\copyfile.txt"
$destinationpath = "\\$computer\C$\Users\$user\AppData\Local\filedepot"
If(Test-Path -Path $destinationpath){
Copy-Item -Path $sourcepath -Destination $destinationpath -Force
}Else{
Write-Host "Destination path not found - $destinationpath" -ForegroundColor Red
}
}

Powershell Create-item creates multiple folders on list

Location.csv Sample I'm trying to create a single folder by prompting the user for userID and the group used to map the home folder.
The below script creates the user's home folder in each location and not in the location matching the prompt.
Running the script without the foreach loop doesn't work.
$Locations = Import-Csv "C:\Scripts\CreateHomeFolder\Location.csv"
$UserName = Read-Host "Enter User Logon Name"
$UserGroup = Read-Host "Enter User's Home drive group"
foreach($Location in $Locations.Location){
if ($Locations.Groups -eq $UserGroup){
New-Item -Name $UserID -Path $Locations.Location -ItemType Directory -Verbose
}
}
what am I doing wrong here?
As commented, you have the variables wrong. The iterating variable is $location and in each iteration it is an object taken from the array $locations.
Use
foreach($Location in $Locations){
if ($Location.Groups -eq $UserGroup){
New-Item -Name $UserID -Path $Location.Location -ItemType Directory -Verbose
}
}
went back to the drawing board, refined my google search and found the solution to be:
$Locations = Import-Csv "C:\Scripts\CreateHomeFolder\Locations.csv" | Where-Object Groups -eq $UserGroup | select Location
New-Item -Name $UserName -Path $Locations.Location -ItemType Directory -Verbose
Theo's helpful answer addresses your immediate problem.
Your own answer improves on your original approach, though by not using
select -ExpandProperty Location - note the use of -ExpandProperty (select is the built-in alias for the Select-Object cmdlet) - it creates unnecessary duplication (and processing overhead) by having to refer to Location twice.
Another option is to use direct property access:
New-Item -Name $UserName -ItemType Directory -Verbose -Path (
(
Import-Csv C:\Scripts\CreateHomeFolder\Locations.csv |
Where-Object Groups -eq $UserGroup
).Location
)

Copy first image file from subfolders into parent and rename

Inside a specific folder I have a few sub-folders, in each are stored image files.
I would like to copy the first image file from each sub-folder into the parent and rename it to the folder's name that it belongs.
I managed to write the following script with the information from several other questions on the site but there is something that is not working as expected. Running the script doesn't copy/rename any file.
$Root = (Get-Item -Path '.\' -Verbose).FullName #'
$Folders = Get-ChildItem -Path $Root -Directory
$Image = Get-ChildItem -Name -Filter *.* | Select-Object -First 1
Foreach($Fld in $Folders)
{
Copy-Item -Path "$($Fld.FullName)\$Image" -Destination "$Root\$($Fld.Name).jpeg"
}
Read-Host -Prompt "Press Enter to exit"
I want to be able to run the script from any folder, the paths must be relative and not absolute/hardcoded. I think the $Root variable achieves that purpose.
The sub-folders only contain image files, the filter *.* in the $Image Get-ChildItem is fine for the purpose as it will always pick an image. However the Copy-Item command will copy it with the jpeg extension, is it possible to check the image file extension and copy/rename accordingly? Perhaps with some If statements?
You're mistakenly getting the $image in your $root-directory since you are using the get-childitem without any -Path parameter. For your purpose you need Foreach $Fld (folder) seperately:
$Root = (Get-Item -Path '.\' -Verbose).FullName #'
$Folders = Get-ChildItem -Path $Root -Directory
Foreach($Fld in $Folders)
{
$Image = Get-ChildItem -Path $Fld -Name -Filter *.* | Select-Object -First 1
Copy-Item -Path "$($Fld.FullName)\$Image" -Destination "$Root\$($Fld.Name).jpeg"
}
Read-Host -Prompt "Press Enter to exit"
Here is you code a little shortened:
$Folders = Get-ChildItem -Directory # Without -path you are in the current working directory
Foreach($Fld in $Folders)
{
$Image = Get-ChildItem -Path $Fld -Filter *.* | Select-Object -First 1 # Without the -name you get the whole fileinfo
Copy-Item -Path $Image.FullName -Destination "$PWD\$($Fld.Name)$($Image.Extension)" # $PWD is a systemvariable for the current working directory
}
Read-Host -Prompt "Press Enter to exit"
You could be even bolder as the FullName of the folder contains the path:
Copy-Item -Path $Image.FullName -Destination "$($Fld.FullName)$($Image.Extension)"

How compare Home folders and Active Directory with copy/remove folders?

i working on one project and i have problem. Assignment: The powershell script must compare Home user folders on F:UserHome with AD by name. If name folder is same with name in ActiveDirectory, dont do anything and continue.
But if user isn't in AD, script must compare:
If home adressar contains data, move this adresar from F: to Synology NAS(it is another server).
If home adressar is empty, it can be remove/delete.
But i must sort this home adresar to 2 folders(UserToMove.txt/UserToRemove.txt) for my boss too - with the same conditions.
If you don't understand something, I can explain it again. It's very important for me.
Here is my script, which i create, but isn't working: - there's a mess in it
$homeDriveRoot = "F:\UserHome"
$leaversRoot = "\new storage on NAS"
$folders = Get-ChildItem $homeDriveRoot | Select -ExpandProperty Name
foreach($folder in $folders) {
$folder
#Compare by name
$u = Get-ADUser -identity $folder -Filter {Enabled -eq $true}|Select ExpandProperty Name
#If>0
if (($u).count -gt 0) {
#If empty - remove
if(($u) -eq $null){ Copy-Object -Path "$homeDriveRoot$_" -Destination C:\Users\branym.adm\desktop\remove.csv -Force}
#If<0 write to file
else{Copy-Object -Path "$homeDriveRoot$_" -Destination C:\Users\branym.adm\Desktop\active.csv -Force};
}
#If dont search
else { echo "lost $u folder"}
}
I think this may help you:
$homeDriveRoot = "F:\UserHome"
$leaversRoot = "\new storage on NAS"
# create two variables for the output text files. (they will end up on your desktop)
$removeFile = Join-Path -Path ([Environment]::GetFolderPath("Desktop")) -ChildPath 'UserToReMove.txt'
$moveFile = Join-Path -Path ([Environment]::GetFolderPath("Desktop")) -ChildPath 'UserToMove.txt'
# check if the destination folder in $leaversRoot exists. If not create it first
if (!(Test-Path -Path $leaversRoot -PathType Container)) {
New-Item -Path $leaversRoot -ItemType Directory | Out-Null
}
# get a list of all folders in the $homeDriveRoot.
# The items in the list are FolderInfo objects, not simply strings.
# If your PowerShell version is less than 3.0, write it like this:
# $folders = Get-ChildItem -Path $homeDriveRoot | Where-Object { $_.PSIsContainer }
$folders = Get-ChildItem -Path $homeDriveRoot -Directory
foreach($folder in $folders) {
# see if we can find an AD user with this SamAccountName
$user = Get-ADUser -Identity $folder.BaseName
if (!$user -or $user.Enabled -eq $false) {
# there is no active AD user found for this folder name
# test if the folder is empty or not
# by using Select-Object -First 1 the enumeration of files and/or folders stops at the first item
if ((Get-ChildItem -Path $folder.FullName -Force | Select-Object -First 1 | Measure-Object).Count -eq 0) {
# the folder is empty, so it can be deleted
# Add a line to the $removeFile
Add-Content -Path $removeFile -Value $folder.BaseName
Remove-Item -Path $folder.FullName -Force -Confirm:$false -WhatIf
}
else {
# the folder has items in it, so move it to NAS
# Add a line to the $moveFile
Add-Content -Path $moveFile -Value $folder.BaseName
Move-Item -Path $folder.FullName -Destination $leaversRoot -Force -WhatIf
}
}
}
Take off the -WhatIf switches from the Remove-Item and Move-Item cmdlets if the results are what you expect.
These switches are for testing and nothing actually gets moved or removed.

Delete contents of temp folder

I've got the following code snippet which currently removes everything in my temp directory and re-adds a new temp directory.
if($serverVersion.name -like "*2003*"){
$dir = "\\$server" + '\C$\WINDOWS\Temp\*'
remove-item $dir -force -recurse
if($?){new-item -path "\\$server\admin$\Temp" -Type Directory}
}
elseif($serverVersion.name -like "*2008*"){
$dir = "\\$server" + '\C$\Windows\Temp\*'
remove-item $dir -force -recurse
if($?){New-Item -Path "\\$server\admin$\Temp" -Type Directory}
}
I'm trying to slightly alter the code to where it will no longer delete the temp directory and instead simply remove all of the contents inside of temp. I added \* at the end of my $dir variable so that it tries to get all of the items inside of temp rather than deleting Temp itself. When I run this however I'm not deleting anything. What is wrong with my code?
This works for me, so long as you meet the pre-reqs and have full control over all files/folders under Temp
# Prerequisites
# Must have the PowerShell ActiveDirectory Module installed
# Must be an admin on the target servers
#
# however if you have no permissions to some folders inside the Temp,
# then you would need to take ownship first.
#
$Server = "server Name"
$dir = "\\$Server\admin$\Temp\*"
$OS = (Get-ADComputer $Server -Properties operatingsystem).operatingSystem
IF (($os -like "*2003*") -or ($os -like "*2008*"))
{
remove-item $dir -Recurse -force
}
According to the PowerShell help file for remove-item, the -recurse parameter is faulty. It recommends that you get-childitem and pipe to remove-item. See example from the help file below.
-------------------------- EXAMPLE 4 --------------------------
C:\PS>get-childitem * -include *.csv -recurse | remove-item
Figured out how to do this and figure it may be useful for someone in the future.
if($serverVersion.name -like "*2003*"){
$dir = "\\$server" + '\C$\WINDOWS\Temp'
Get-ChildItem -path $dir -Recurse | %{Remove-Item -Path $_.FullName -Force}
if($?){new-item -path "\\$server\admin$\Temp" -Type Directory}
}
elseif($serverVersion.name -like "*2008*"){
$dir = "\\$server" + '\C$\Windows\Temp'
Get-ChildItem -path $dir -Recurse | %{Remove-Item -Path $_.FullName -Force}
write-host "success?"
if($?){New-Item -Path "\\$server\admin$\Temp" -Type Directory}
}
Using get-childitem it will look at everything inside of Temp without deleting Temp itself.