我使用 pwsh 代码连接到远程计算机以生成 CSV 文件。
- 我通过 Invoke-command 执行此操作,代码运行良好,在服务器上生成 CSV 文件。
- CSV 文件的名称是动态生成的。
但是,我无法将该文件从远程计算机复制到本地计算机。
有没有办法在 Invoke-command 中使用复制项目?
请提供建议/指导。
下面给出了代码片段。
# Target Server
$TargetServer = "xxx.xxx.xxx.xxx"
# Capture the VM credentials
$creds = Get-Credential -Title "Enter admin Password" -UserName admin
# Create session
$session = New-PSSession -ComputerName $TargetServer -Credential $creds
$scriptBlock = {
# Attempt Install
Install-Module -Name Join-Object
# Attempt Import
Import-Module -Name Join-Object
# IP Address
$ipAdress = (Get-NetIPAddress -AddressFamily IPV4).IPAddress[0]
# Set the CSV file name
$lastLogonReportName = "LastLogonReport__" + $ipAdress + "__" + (get-date -Format "dd MMM yyyy_dddd") + ".csv"
... ...
... ...
... ...
... ...
$Output
# Set Location to user's Downloads folder
Set-Location -Path $HOME\Downloads
$Output | Export-Csv -Path ./$lastLogonReportName
# Copy-Item $lastLogonReportName -Destination "D:\" -FromSession $Session
}
Invoke-Command -ComputerName $TargetServer -Credential $creds -ScriptBlock $scriptBlock
最佳答案
您绝对可以使用Copy-Item
来实现此目的,但还有一种更简单的方法:
# Create session
$session = New-PSSession -ComputerName $TargetServer -Credential $creds
$scriptBlock = {
# Set the CSV file name
$date = Get-Date -Format "dd MMM yyyy"
# IP Address
$ipAdress = (Get-NetIPAddress -AddressFamily IPV4).IPAddress[0]
$lastLogonReportName = "LastLogonReport__${ipAdress}__$date.csv"
# Destination
$destination = Join-Path "$HOME\Downloads" -ChildPath $lastLogonReportName
$Output | Export-Csv -Path $destination -NoTypeInformation
$Output # => Send this Object to be captured on locahost
}
$params = @{
Session = $session
ScriptBlock = $scriptBlock
}
$captureThisObject = Invoke-Command @params
PS /> $captureThisObject # => Is your CSV on localhost
如果您想使用Copy-Item
,请让Invoke-Command
返回主机上存储CSV的路径,然后(从调用外部)您调用Copy-Item -FromSession
:
# Create session
$session = New-PSSession -ComputerName $TargetServer -Credential $creds
$scriptBlock = {
# Set the CSV file name
$date = Get-Date -Format "dd MMM yyyy"
# IP Address
$ipAdress = (Get-NetIPAddress -AddressFamily IPV4).IPAddress[0]
$lastLogonReportName = "LastLogonReport__${ipAdress}__$date.csv"
# Destination
$destination = Join-Path "$HOME\Downloads" -ChildPath $lastLogonReportName
$Output | Export-Csv -Path $destination -NoTypeInformation
$destination # => Send this Path to be captured on locahost
}
$params = @{
Session = $session
ScriptBlock = $scriptBlock
}
$remotePath = Invoke-Command @params
Copy-Item -Path $remotePath -Destination path/to/csvHere.csv -FromSession $session
关于powershell - 在 PowerShell 中的调用命令 session 中将文件从远程计算机复制到本地计算机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70309952/