下面脚本中的“CD”命令在本地机器上而不是远程执行。 怎么了?
Add-PSSnapin Windows.ServerBackup -ErrorAction SilentlyContinue set-item wsman:\localhost\Client\TrustedHosts -value 81.xxx.xx.xx $WBResult = $WBSummary.LastBackupResultHR $WBErrorMsg = $WBJob.ErrorDescription + "`n" + $WBSummary.DetailedMessage $User = "administrator" $File = "C:\Users\jsapsford\Desktop\Password.txt" $cred = New-Object -TypeName System.Management.Automation.PSCredential ` -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString) If ($WBResult -eq 0) { $WBResult = "Successful"} Else {$WBResult = "Failed"} if ($WBResult -eq "Succesful") {$text = 'document.write("Succesful");'} Else {$text = 'document.write("Failed");'} $serverconnection = New-PSSession -ComputerName 81.xxx.xx.xx -Credential $cred Enter-PSSession -Session $serverconnection cd C:\website\ $text | Out-File 'company.txt'
基本上,我试图做的是连接到服务器使用远程PowerShell,然后打算光盘到C:\网站,并创build一个名为company.txt的文件,但是发生了什么是它正在执行cd C:\website和$text | Out-File 'company.txt' $text | Out-File 'company.txt'本地机器上运行脚本的$text | Out-File 'company.txt'而不是远程机器。 有谁知道为什么?
Enter-PSSession通常用于交互式命令行的使用。 对于脚本化的远程调用,使用Invoke-Command有两个主要的PowerShell远程模式。
Invoke-Command -ComputerName ... -ScriptBlock { ... }适用于一次性调用。 请注意-computername 。 使用这个参数模式会造成每次调用连接和authentication的成本。 这是很方便的,你不需要记得清理任何东西。
在原始问题中切换到New-PSSession提供了一个可以重复使用的更持久的连接,指定-Session而不是ComputerName 。 为了保持良好的资源卫生状况,您需要在完成后删除会话。 我通常使用try/finally模式。
无论哪种情况,请在ScriptBlock工作。 你可以$using:text | Out-File c:\website\company.txt来做$using:text | Out-File c:\website\company.txt $using:text | Out-File c:\website\company.txt块内。 using范围限定符允许您引用调用上下文中的variables。
对不起,这将是一个垃圾的答案,但我最终废除了整个事情,并重新开始,而不是创buildvariables,然后携带它等现在创build本地机器上的文本文件,然后将其传输到服务器通过FTP更容易的方法来做到这一点。 如果你想让我上传我现在使用的代码,我会但是直到感兴趣的显示不好,现在就离开它。 感谢所有的帮助