Powershell Invoke-Command Remove-Item Remote Server - powershell

I want to delete files on a particular folder of a remote server. I execute the following in Powershell:
Invoke-Command -Computer 'compname1' -ScriptBlock {Remove-Item -$args -force } -ArgumentList 'c:\BizTalkDeployment'
I get the following error:
Cannot find drive. A drive with the name '-c' does not exist.
c:\BizTalkDeployment is the correct path on server compname1.
Can anyone please explain what I've done wrong?

Remove the - in front of $args and re-run the script. You might even try changing the script block to:
Remove-Item -Path $args[0]

You could also remove the folder using a UNC path:
Remove-Item \\compname1\c$\BizTalkDeployment -force

Related

Powershell - "Copy-item" command in scriptblock of Invoke-Command

I need to copy file from one remote server to other using powershell script.
What I have tried :-
While i use following powershell commands it's work fine.(means file copied from one server to other)
But while i use following script it gives error "cannot find path..." as follows
Actually, file is exist at that path.
I have tried to refer following stack-overflow already question-answer
Error with PowerShell command for copying file to remote server with credential
'Session' Parameter is null or empty in PowerShell script
powershell remote
Invoke-Command with remote session: Cannot validate argument on parameter
Unable to copy a binary to a remote Azure VM
PowerShell Command to Copy File on Remote Machine
I have also tried to get help using
Get-Help Invoke-Command
Question :-
How can i use "Copy-Item" command inside "Invoke-Command(Scriptblock)" in script(2) to copy file?
Is there any better way to achieve this(means best practice)?
Invoke-Command has the parameter -ArgumentList wich can be used to supply the values of local variables in the remote session. The Problem is: it's just the VALUE of the variable. No file!
What you can do:
Use Get-Content -Raw on small files to save the contant in a variable. On the target system create a New-Item with the -Value of that file. However thats not very efficent.
Example:
$txt = Get-Content -Raw -Path "C:\test\oldFile.txt"
$Session = New-PSSession 127.0.0.1
Invoke-Command -Session $Session -ScriptBlock { Param($Txt) New-Item -Path c:\test\newFile.txt -Value $txt } -ArgumentList $txt
#Get-PSSession | Remove-PSSession
Result:
Verzeichnis: C:\test # Sry german OS
Mode LastWriteTime Length Name PSComputerName
---- ------------- ------ ---- --------------
-a---- 03.09.2020 12:23 658033 newFile.txt 127.0.0.1
What you should do:
I think your use of Copy-Item -ToSession $Session is the right way to do it. It's litteraly made just for your purpose. The downside is, that the target directory needs to exist. But you need a PSSession for both cmdlets anyway. So you can use Invoke-Command with the same PSSession. First Create a PSSession. Use Invoke-Command to create you directory. Then use Copy-Item to move your file to the right place. Finally you can use Invoke-Command to do some finishing steps. And don't forget to Remove-PSSession when you are done:
$DestinationPath = "C:\test"
Invoke-Command -Session $Session -ScriptBlock { Param($Destination) New-Item -Path $Destination -ItemType Directory } -ArgumentList $DestinationPath
Copy-Item -Path "C:\test\oldFile.txt" -ToSession $Session -Destination "c:\test\newFile.txt"
Invoke-Command -Session $Session -ScriptBlock { write-host "Do some stuff" }
$Session | Remove-PSSession

How to get PS script to access folders that need admin access

I'm a desktop support tech for my company, and we often have a good bit of repetitive troubleshooting we perform such as clearing temp files and cache from C\windows\temp, local appdata temp folder, as well as google and IE cache/cookies. I was writing a powershell script to do this all in one go, and it does what it is supposed to. The only problem is that when I am on a user's computer, I have to actually access the windows temp and local appdata folders first and then run the script for it to work. I believe this is because those two folders require admin access to get into. Since I'm an admin I can put my creds in to access the folders just fine, but I'm having trouble finding some code to insert in order to allow the powershell script to gain access to those folders. Note: I do have a command at the beginning of the script that launches powershell as admin, but that seems to not be enough. My code is below, any insight on this would be terrific. (Looks like my comment hashtags in the code turned the comments bold, apologies)
# Runs the below script with PowerShell in Admin mode
Start-Process "$psHome\powershell.exe" -verb runas -ArgumentList "-file fullpathofthescript"
# Clears google chrome cache
Remove-Item -Path "C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Cache\*" -verb runas -Recurse -Force -ErrorAction SilentlyContinue
# Clears IE cookies
Remove-Item -Path "C:\Users\*\AppData\Roaming\Microsoft\Windows\Cookies\*" -verb runas -Recurse -Force -ErrorAction SilentlyContinue
# Clears the "windows\temp" folder
Remove-Item -Path "C:\Windows\Temp\*" -verb runas -Recurse -Force -ErrorAction SilentlyContinue
# Clears the user's local temp folder
Remove-Item -Path "C:\Users\*\AppData\Local\Temp\*" -verb runas -Recurse -Force -ErrorAction SilentlyContinue"
You can use the -Credential parameter to prompt for the local admin credentials which should allow you to delete in the C:\Windows\* location, assuming ACLs have not be messed with.
Remove-Item -Path "C:\Windows\Temp\*" -Credential (Get-Credential) -Recurse -Force -ErrorAction SilentlyContinue
Putting in the ErrorAction is stopping you from seeing the below error as well.
Remove-Item : A positional parameter cannot be found that accepts argument 'runas'.

Remote installation of exe using powershell

I have a script to copy a file to remote servers C:\temp and also to execute the exe file remotely. But the problem here is, it is copying .exe file to c:\temp of the remote machine, but not executing the exe.
Can anyone help me to correct here ?
ForEach ($Computer in Get-Content C:\scripts\servers.txt)
{
Copy-Item -Path '\\serverA\c$\scripts\Firefox Setup 52.0.1.exe' -Destination \\$Computer\c$\temp\;
Invoke-Command -AsJob -ComputerName $Computer -ScriptBlock { & "C:\temp\Firefox Setup 52.0.1.exe -ms" }
}
Try this,
Step by step breif explation is given for Installing-remote-software using Powershell

Copy files from UNC path to C:\ and Program files (x86) folder within a remotly generated New-PSSession

I am writing a script, that creates a new VM, connects to it via New-PSSession and runs serveral Commands to alter a few settings and copy folders from a UNC path to the local C: and C:\Program files (x86).
Everything works fine expect the copy part - I get an error saying
permission denied.
I run the script itself as domain admin and the credentials I pass also has domain admin rights.
For example:
$source = '\\server\share'
$cred = Get-Credential
$pss = New-PSSession -ComputerName "$computername" -Credential $cred
Invoke-Command -Session $pss -ScriptBlock {
Copy-Item "$source\FOLDER" -Destination 'C:\FOLDER' -Recurse -Force -
Credential
$cred
Even if I pass the cedentials it fails. A quick search results in "use robocopy", but in my opinion it must be possible to copy files from a UNC path to a local directory with PowerShell even if that directory is basically protected by Microsoft.
I think you need to pass the variable to the remote session:
invoke-Command -Session $pss -Args $source -ScriptBlock{Copy-Item "$args[0]\FOLDER" ...}
otherwise $source is considered a variable in the remote session and since it doesn't exist there ps will try to copy from \Folder
You can try to use -ToSession parametr without entering to PSSession.
$ses = New-PSSession -ComputerName WorkStation
Copy-Item -ToSession $ses -Destination C:\users\TempUser\Documents\ -Path '\\10.0.0.1\share\' -Recurse
My solution for Copy-Item is:
-Destination $($(dir "env:programfiles(x86)").value + "\Avest\AvPCM_nces\")

Robocopy commands to copy a file to over 50 remote machines

I started looking at robocopy yesterday to try to copy and overwrite a file from one destination to many remote computers. I've tried Robocopy to copy files to a remote machine but it doesn't work. I get the same error as the person in the link. Does anybody have any suggestions or lead me in the right way ? thank you so much !
You could just use PowerShell for this. It has an inefficiency issue wherein it would copy one at a time but that shouldnt be an issue for 50ish machines. This could help if you made a PowerShell script
$computers = Get-Content "C:\filewithcomputers.txt"
$fileToCopy = "C:\filetocopy.txt"
ForEach($computer in $Computers){
Copy-Item -Path $fileToCopy -Destination "\\$computer\C`$\Temp"
}
The would copy the file $fileToCopy to each server in the file C:\filewithcomputers.txt assuming that the file contained a list of computer with each one on its own line. The file would be copied to the temp folder on each machine. Update the paths as required for your scenario. I only suggest this since you tagged powershell-remoting. If you are not adept with PowerShell maybe someone else can give you a better answer more of what you are looking for. Using RoboCopy for one file seemed tedious.
If you wanted to check to see if a folder exists and is accessible you could do something like this.
$computers = Get-Content "C:\filewithcomputers.txt"
$fileToCopy = "C:\filetocopy.txt"
ForEach($computer in $Computers){
$destinationx86 = "\\$computer\C`$\Program Files (x86)"
$destination = "\\$computer\C`$\Program Files"
If(Test-Path $destinationx86){
# Copy this to Program Files (x86)
Copy-Item -Path $fileToCopy -Destination $destinationx86
} Else {
# Copy this to Program Files
Copy-Item -Path $fileToCopy -Destination $destination
}
}
If you need to connect with different credentials, you can use
$credential = Get-Credential
New-PSDrive -Name "Computer01" -PSProvider FileSystem -Root "\\Computer01\Share" -Credential $credential -Scope global
Now you can copy to e.g. Computer01:\Folder01\
If you have set your environment up to support PSRemoting and have placed the file in a file share you can use PowerShell Remoting to instruct many computers to retrieve the file themselves nearly simultaneously with Invoke-Command. You can limit the number of simultaneous actions using -ThrottleLimit depending on the size of the source file and how robust the network/server are:
$computers = Get-Content "C:\filewithcomputers.txt"
$originalsource = "\\fileserver\shared\payload.exe"
$originaldestination = "c:\"
$scriptblockcontent = {
param($source,$destination)
Copy-Item -Path $source -Destination $destination
}
Invoke-Command –ComputerName $Computers –ScriptBlock $scriptblockcontent `
–ThrottleLimit 50 -ArgumentList $originalsource,$originaldestination