我是PowerShell和各种脚本的新手,已经完成了以下任务。
我需要根据使用invoke-command在本地服务器上获取的文件名在远程服务器上创建一个文件。
WinRM已在远程服务器上配置并运行。
我需要做的是以下
在Server1上,触发器文件位于文件夹中。 Server1上的Powershell将文件名传递给Server2上的powershell。然后,Server2上的Powershell将根据名称创建一个文件。
我的头被熔化,寻找灵感的形式,任何帮助将不胜感激
非常感谢 保罗
答案 0 :(得分:1)
我认为如果您不熟悉脚本,那么会增加许多额外复杂性的事情就是存储和处理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:\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
}
(未测试的)