To delete old files on our servers we run a remote command on the server using PowerShell and Invoke-Command
:
Invoke-Command {
Param($ServerPath)
Remove-Item -Path $ServerPath -Recurse -Force -Verbose
} -Computer servername -Credential $Credential -ArgumentList $ServerPath
# The parsed credentials are from a different user than the one who opened the
# shell
The command itself works as wanted. But this only writes the deleted files to the console, instead I want to forward it to an variable / file (preferably stored on the client executing the command).
I tried the following options without sucess:
Invoke-Command {
Param($ServerPath)
Remove-Item -Path $ServerPath -Recurse -Force -Verbose 4>>"%ScriptPath%\log.txt"
} -Computer servername -Credential $Credential -ArgumentList $ServerPath
Invoke-Command {
Param($ServerPath)
Remove-Item -Path $ServerPath -Recurse -Force -Verbose >>"%ScriptPath%\log.txt"
} -Computer servername -Credential $Credential -ArgumentList $ServerPath
Invoke-Command {
Param($ServerPath)
Remove-Item -Path $ServerPath -Recurse -Force -Verbose
} 4>>"%ScriptPath%\log.txt" -Computer servername -Credential $Credential -ArgumentList $ServerPath
$log = Invoke-Command {
Param($ServerPath)
Remove-Item -Path $ServerPath -Recurse -Force -Verbose
} -Computer servername -Credential $Credential -ArgumentList $ServerPath
$log = Invoke-Command {
Param($ServerPath)
return (Remove-Item -Path $ServerPath -Recurse -Force -Verbose)
} -Computer servername -Credential $Credential -ArgumentList $ServerPath
A workaround maybe could be to start a remote session to the server and execute there, but I don't want to start and cancel a remote session for just one command.
Does anyone know what I did wrong with forwarding?