记录非交互式会话中的脚本



我一直在寻找一种方法来记录在powershell远程会话中运行的脚本,该方法与使用Start-Transcript类似。当我尝试从远程会话获取成绩单时,会创建成绩单文件,但文件中没有任何内容。

$servers = "ServerA"
$session = New-PSSession -ComputerName $servers -Credential $creds -Authentication Default -ErrorAction Stop
Invoke-Command -Session $session -ScriptBlock {
Start-Transcript -OutputDirectory D:LOGS
Set-Location c:scripts
Get-ChildItem
Stop-Transcript
Exit-PSSession
}
Remove-PSSession $session

Transcript文件在那里,但没有任何命令被记录。我知道这是因为在远程系统上执行的脚本块是非交互式会话。

其他人如何在远程脚本中记录成功/失败?

您不必在远程机器上编写日志文件。您可以在来电机器上收集所有信息,例如

$servers = "ServerA"
$session = New-PSSession -ComputerName $servers -Credential $creds -Authentication Default -ErrorAction Stop
$result = Invoke-Command -Session $session -ScriptBlock {
#Store result into variable
$data = Get-ChildItem -path c:scripts
#return variable
return $data
}
Remove-PSSession $session

调用方机器上的$result将包含从远程机器返回的数据(对象,包括远程机器的主机名(。

最新更新