简体   繁体   English

Invoke-Command 脚本块内的写入输出

[英]Write-Output inside Invoke-Command scriptblock

Below is a script I'm working on to get all SQL-jobs into a CSV-file.下面是我正在编写的将所有 SQL 作业放入 CSV 文件的脚本。 The script itself is working great but I have trouble with the error-handling.脚本本身运行良好,但我在错误处理方面遇到了麻烦。 I can't figure out how to get the Out-File inside the Catch-block to print to the file on my local machine instead of the remote machine I'm running the Invoke-Command to.我不知道如何让 Catch 块内的 Out-File 打印到我的本地机器上的文件,而不是我正在运行 Invoke-Command 的远程机器上。 How do I accomplish this?我该如何做到这一点?

Thanks谢谢

PS. PS。 The script is written out fully as much as possible for non experienced co-workers convenience为了方便没有经验的同事,脚本尽可能完整地写出来

$sqlServers = @("TEST1","TEST2")

$filePath = [Environment]::GetFolderPath("Desktop")

$dateToday = Get-Date -Format “yyMMdd HH:mm"
$dateTodayFile = Get-Date -Format “yyMMdd"

Write-Output "$dateToday $sqlServers" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append

$output = Invoke-Command -ComputerName $sqlServers -ScriptBlock{

    Try
    {
        Import-Module sqlserver -ErrorAction Stop
    }
    Catch
    {
        Write-Output "$dateToday ERROR $env:computername" |
            Out-File "$filePath\Log$dateTodayFile.txt" -Append
        Exit
    }
    $instances = $env:computername | Foreach-Object {Get-ChildItem -Path "SQLSERVER:\SQL\$_"}

    ForEach ($instance in $instances){

        Try
        {
        $instanceName = $instance.InstanceName
        Get-SqlAgentJob -ServerInstance "$env:computername\$instanceName" -ErrorAction Stop |
            Where-Object {$_.IsEnabled -eq "True" -and $_.LastRunDate -gt [DateTime]::Today.AddDays(-2) -and $_.OwnerLoginName -match "TEST"} |
                Select-Object @{Name=‘Job name‘;Expression={$_.Name}},
                    @{Name=‘Description‘;Expression={$_.Description}},
                    @{Name=‘Instance‘;Expression={$_.Parent -Replace '[][]'}},
                    @{Name=‘Run outcome‘;Expression={$_.LastRunOutcome}},
                    @{Name=‘Run date‘;Expression={$_.LastRunDate}},
                    @{Name=‘Run duration‘;Expression={$_.LastRunDuration}},
                    @{Name=‘Job creator‘;Expression={$_.OwnerLoginName}},
                    @{Name=‘Runs on a schedule‘;Expression={$_.HasSchedule}},
                    @{Name='Schedule Type';Expression={$_.JobSchedules -join ','}}
        }
        Catch
        {
            Write-Output "$dateToday ERROR $env:computername\$instanceName" |
                Out-File "$filePath\Log$dateTodayFile.txt" -Append
            Exit
        }
    }
}
$output | Select-Object -Property * -ExcludeProperty PSComputerName,RunSpaceID,PSShowComputerName |
    Sort-Object "Job name" |
        Export-Csv $filePath\SQLJobInvent$dateTodayFile.csv -NoTypeInformation -Delimiter ";" -Encoding UTF8

Write-Output "$dateToday $filePath" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append
Write-Output "----------------------------------------" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append

Your primary issue is scope.您的主要问题是 scope。

The $dateToday , $filePath and $dateTodayFile are all declared on the local machine, but you're trying to use them on the remote computer (script block) where they are undefined. $dateToday$filePath$dateTodayFile都在本地计算机上声明,但您试图在未定义的远程计算机(脚本块)上使用它们。

There are a few ways to get your variables passed to the remote computer, below are two:有几种方法可以将变量传递到远程计算机,以下是两种:

# Add desired variable to ArgumentList and define it as a parameter
Invoke-Command -ComputerName $sqlServers -ArgumentList $dateToday,$filePath,$dateTodayFile -ScriptBlock {
  param(
    $folderPath,
    $filePath,
    $dateTodayFile
  )  
  # Do something with our injected variables
  Write-Output "$dateToday ERROR $env:computername" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append
}

OR或者

# In PS ver >= 3.0 we can use 'using'
Invoke-Command -ComputerName $serverName -ScriptBlock {Write-Output $using:dateToday}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM