2

我使用 pwsh 代码连接到远程计算机以生成 CSV 文件。

  1. 我通过调用命令执行此操作,代码运行良好,在服务器上生成一个 CSV 文件。
  2. CSV 文件的名称是动态生成的。

但是,我无法将该文件从远程计算机复制到本地计算机。

有没有办法在调用命令中使用复制项?

请建议/指导。

代码片段如下所示。


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

1 回答 1

2

您绝对可以使用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
于 2021-12-10T20:49:14.213 回答