Search code examples
powershellinvoke-command

using invoke-command to create files on a remote server


I am new to powershell and all sorts of scripting and have been landed with the following task.

I need to create a file on a remote server based on the filename picked up on the local server using the invoke-command.

WinRM is configured and running on the remote server.

What i need to happen is the following

On Server1 a trigger file is placed folder. Powershell on Server1 passes the filename onto powershell on Server2. Powershell on Server2 then creates a file based on the name.

My heads been melted trolling through forms looking for inspiration, any help would be greatly appreciated

Many thanks Paul


Solution

  • I think if you're new to scripting, something that will add a lot of extra complexity is storing and handling credentials for Invoke-Command. It would be easier if you could make a shared folder on Server2 and just have one PowerShell script writing to that.

    Either way, a fairly simple approach is a scheduled task on Server1 which runs a PowerShell script, with its own service user account, every 5 minutes.

    Script does something like:

    # Check the folder where the trigger file is
    # assumes there will only ever be 1 file there, or nothing there.
    $triggerFile = Get-ChildItem -LiteralPath "c:\triggerfile\folder\path"
    
    # if there was something found
    if ($triggerFile)
    {
    
        # do whatever your calculation is for the new filename "based on"
        # the trigger filename, and store the result. Here, just cutting
        # off the first character as an example.
        $newFileName = $triggerFile.Name.Substring(1)
    
    
        # if you can avoid Invoke-Command, directly make the new file on Server2
        New-Item -ItemType File -Path '\\server2\share\' -Name $newFileName
        # end here
    
    
        # if you can't avoid Invoke-Command, you need to have
        # pre-saved credentials, e.g. https://www.jaapbrasser.com/quickly-and-securely-storing-your-credentials-powershell/
    
        $Credential = Import-CliXml -LiteralPath "${env:\userprofile}\server2-creds.xml"
    
        # and you need a script to run on Server2 to make the file
        # and it needs to reference the new filename from *this* side ("$using:")
        $scriptBlock = {
            New-Item -ItemType File -Path 'c:\destination' -Name $using:newFileName
        }
    
        # and then invoke the scriptblock on server2 with the credentials
        Invoke-Command -Computername 'Server2' -Credential $Credential $scriptBlock
        # end here
    
        # either way, remove the original trigger file afterwards, ready for next run
        Remove-Item -LiteralPath $triggerFile -Force
    }
    

    (Untested)