I'm trying to create a simple file operations API for remote machine using PowerShell from C#.
I am able to Copy-Item to and from remote machine by first creating New-PSSession and executing the Copy-Item cmdlet with an additional parameter -ToSession/-FromSession $s, where $s is a variable generated by the New-PSSession.
I am looking for a way to do the same with removing, adding and moving items, but I'm already stuck with Removing part. MSDN does not specify any specific parameter in place of -ToSession/-FromSession - is there any other way to remove a file using PSSession? I would like to limit "ways" of connecting to remote host to a bare minimum.
Disclaimer: I am able to create a remote PowerShell client in C# and run commands remotely, but I'd rather keep the control of the process on client, not the host.
From what I understood, this is what you want to do:
If you want to type the path:
Invoke-Command -Session $PSSession -Command {Remove-Item c:\windows}
or
Using the path as variable, you need to utilize the $Using: keyword. This works PoShv3 or higher.
$Path = 'C:\Windows'
Invoke-Command -Session $PSSession -Command {Remove-Item $Using:Path}
or
If you need to go classic, you can pass the variables into the scriptblock by the -argumentlist parameter. You can pick them up inside the scriptblock by either $args array, or by a parameter block. Of course, the variable names inside the scriptblock can differ from the outside ones.
$Path = 'C:\Windows'
Invoke-Command -Session $PSSession -Command {Param($Path) Remove-Item $Path} -ArgumentList $path
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With