【问题标题】:using invoke-command to create files on a remote server使用调用命令在远程服务器上创建文件
【发布时间】:2018-02-23 16:42:41
【问题描述】:

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

我需要根据在本地服务器上使用调用命令获取的文件名在远程服务器上创建一个文件。

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

我需要做的是以下

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

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

非常感谢 保罗

【问题讨论】:

  • 不确定谁评论了这个问题,但我正在尝试使用 Powershell 编写远程文件,与此用例非常相似,感谢您发布@Liffeyman

标签: powershell invoke-command


【解决方案1】:

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

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

脚本执行以下操作:

# 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
}

(未测试)

【讨论】:

  • 非常感谢您,如果您在都柏林,请告诉我,我会给您买一品脱的
  • 嗨 TessellatingHeckler 对于触发器文件,如果我想从文件末尾删除一个序列号,我需要从 $newFileName = $triggerFile.Name.Substring(1 ) 非常感谢保罗
  • @Liffeyman 我要说正则表达式,它看起来像涂鸦,但如果文件像“trigger 123.txt”,那么像 $newFileName = $triggerFile.Name -replace '\s*\d+(?=\.)' 这样的东西会让它“触发。文本”。如果它没有扩展名并且只是“trigger123”,那么-replace '\s*\d+$' 只取最后的数字。希望其中一个能做到。
猜你喜欢
  • 1970-01-01
  • 2017-08-16
  • 2021-01-03
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
相关资源
最近更新 更多