使用Invoke-Command在远程服务器上创建文件



我是PowerShell的新手和各种脚本,并已完成以下任务。

我需要使用Invoke-command在本地服务器上挑选的文件名上在远程服务器上创建文件。

WinRM在远程服务器上配置并运行。

我需要发生的是以下

在Server1上,放置了一个触发文件夹。Server1上的PowerShell将文件名传递到Server2上的PowerShell。Server2上的PowerShell然后根据名称创建文件。

我的头被融化在寻找灵感的表格中,任何帮助将不胜感激

非常感谢Paul

我认为,如果您是脚本的新手,那么会增加很多额外复杂性的东西是存储和处理Invoke-Command的凭据。如果您可以在Server2上制作共享文件夹,并且只需写一个PowerShell脚本。

无论哪种方式,一种相当简单的方法是Server1上的一个计划任务,该任务每5分钟运行PowerShell脚本,带有自己的服务用户帐户。

脚本做类似的事情:

# 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:triggerfilefolderpath"
# 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 '\server2share' -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
}

(未经测试(

最新更新