如何启动job foreach ip和coostiate ip for文件名称

发布于 2025-02-09 20:08:23 字数 886 浏览 3 评论 0 原文

我有一个脚本来自在这里这是工作:

function CaptureWeight {
    Start-Job -Name WeightLog -ScriptBlock {
        filter timestamp {
            $sw.WriteLine("$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_")
        }

        try {
            $sw = [System.IO.StreamWriter]::new("$using:LogDir\$FileName$(Get-Date -f MM-dd-yyyy).txt")
            & "$using:PlinkDir\plink.exe" -telnet $using:SerialIP -P $using:SerialPort | TimeStamp
        }
        finally {
            $sw.ForEach('Flush')
            $sw.ForEach('Dispose')
        }
    }
}

i' D希望让他违反IP地址列表,同时还具有与IP关联的名称来设置每个文件的文件名。我在想 $ name = myFilename $ name.ip = 1.1.1.1 以及使用$ filename和$ serialip的东西,但尚未能够让任何接近工作或找到足够接近我想要的示例的示例。

谢谢

I have a script from here, this is the job :

function CaptureWeight {
    Start-Job -Name WeightLog -ScriptBlock {
        filter timestamp {
            $sw.WriteLine("$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_")
        }

        try {
            $sw = [System.IO.StreamWriter]::new("$using:LogDir\$FileName$(Get-Date -f MM-dd-yyyy).txt")
            & "$using:PlinkDir\plink.exe" -telnet $using:SerialIP -P $using:SerialPort | TimeStamp
        }
        finally {
            $sw.ForEach('Flush')
            $sw.ForEach('Dispose')
        }
    }
}

I'd like to get his to run against a list of IP addresses while also having a name associated with the IP to set the file name for each file. I was thinking something like $Name = Myfilename and $name.IP = 1.1.1.1 and using those in place of $FileName and $SerialIP, but have yet to be able get anything close to working or find an example close enough to what I'm trying for.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

扛刀软妹 2025-02-16 20:08:23

这是您可以用 hash表 AS theo 在他的帮助评论中提到。请注意,没有阈值/therottlelimit参数 start-threadjob 由于作业在不同的过程中运行,因为您已经评论了/ runspaces ,没有内置的方式来控制多少个工作可以在同时。如果您愿意控制这个,则需要自己编码。

# define IPs as Key and FileName as Value
$lookup = @{
    '1.2.3.4'      = 'FileNameForThisIP'
    '192.168.1.15' = 'AnotherFileNameForTHatIP'
}

# path to directory executable
$plink = 'path\to\plinkdirectory'
# path to log directory
$LogDir = 'path\to\logDirectory'
# serial port
$serialport = 123

$jobs = foreach($i in $lookup.GetEnumerator()) {
    Start-Job -Name WeightLog -ScriptBlock {
        filter timestamp {
            $sw.WriteLine("$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_")
        }
        
        try {
            $path = Join-Path $using:LogDir -ChildPath ('{0}{1}.txt' -f $using:i.Value, (Get-Date -f MM-dd-yyyy))
            $sw = [System.IO.StreamWriter]::new($path)
            $sw.AutoFlush = $true
            & "$using:plink\plink.exe" -telnet $using:i.Key -P $using:serialPort | TimeStamp
        }
        finally {
            $sw.ForEach('Dispose')
        }
    }
}

$jobs | Receive-Job -AutoRemoveJob -Wait

哈希表的另一种替代方法可能是使用CSV(要么来自 import-csv 或用 conversfrom-csv )。

Here is one way you could do it with a hash table as Theo mentioned in his helpful comment. Be aware that Jobs don't have a Threshold / ThrottleLimit parameter as opposed to Start-ThreadJob or ForEach-Object -Parallel since jobs run in a different process as you have already commented instead of instances / runspaces, there is no built-in way to control how many Jobs can run at the same time. If you wish have control over this you would need to code it yourself.

# define IPs as Key and FileName as Value
$lookup = @{
    '1.2.3.4'      = 'FileNameForThisIP'
    '192.168.1.15' = 'AnotherFileNameForTHatIP'
}

# path to directory executable
$plink = 'path\to\plinkdirectory'
# path to log directory
$LogDir = 'path\to\logDirectory'
# serial port
$serialport = 123

$jobs = foreach($i in $lookup.GetEnumerator()) {
    Start-Job -Name WeightLog -ScriptBlock {
        filter timestamp {
            $sw.WriteLine("$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_")
        }
        
        try {
            $path = Join-Path $using:LogDir -ChildPath ('{0}{1}.txt' -f $using:i.Value, (Get-Date -f MM-dd-yyyy))
            $sw = [System.IO.StreamWriter]::new($path)
            $sw.AutoFlush = $true
            & "$using:plink\plink.exe" -telnet $using:i.Key -P $using:serialPort | TimeStamp
        }
        finally {
            $sw.ForEach('Dispose')
        }
    }
}

$jobs | Receive-Job -AutoRemoveJob -Wait

The other alternative to the hash table could be to use a Csv (either from a file with Import-Csv or hardcoded with ConvertFrom-Csv).

风为裳 2025-02-16 20:08:23

在此处添加我以前答案的另一种选择,使用 runspacepool 实例具有内置的一种并发和重新启动的方式。

using namespace System.Management.Automation.Runspaces

try {
    # define number of threads that can run at the same time
    $threads = 10

    # define IPs as Key and FileName as Value
    $lookup = @{
        '1.2.3.4'      = 'FileNameForThisIP'
        '192.168.1.15' = 'AnotherFileNameForTHatIP'
    }

    # path to directory executable
    $plink  = 'path\to\plinkdirectory\'
    # path to log directory
    $LogDir = 'path\to\logDirectory'
    # serial port
    $port   = 123

    $iss    = [initialsessionstate]::CreateDefault2()
    $rspool = [runspacefactory]::CreateRunspacePool(1, $threads, $iss, $Host)
    $rspool.ApartmentState = 'STA'
    $rspool.ThreadOptions  = 'ReuseThread'

    # session variables that will be intialized with the runspaces
    $rspool.InitialSessionState.Variables.Add([SessionStateVariableEntry[]]@(
        [SessionStateVariableEntry]::new('plink', $plink, '')
        [SessionStateVariableEntry]::new('serialport', $port, '')
        [SessionStateVariableEntry]::new('logDir', $LogDir, '')
    ))
    $rspool.Open()

    $rs = foreach($i in $lookup.GetEnumerator()) {
        $ps = [powershell]::Create().AddScript({
            param($pair)

            filter timestamp {
                $sw.WriteLine("$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_")
            }

            try {
                $path = Join-Path $LogDir -ChildPath ('{0}{1}.txt' -f $pair.Value, (Get-Date -f MM-dd-yyyy))
                $sw = [System.IO.StreamWriter]::new($path)
                $sw.AutoFlush = $true

                & "$plink\plink.exe" -telnet $pair.Key -P $serialPort | TimeStamp
            }
            finally {
                $sw.ForEach('Dispose')
            }
        }).AddParameter('pair', $i)

        $ps.RunspacePool = $rspool

        @{
            Instance    = $ps
            AsyncResult = $ps.BeginInvoke()
        }
    }

    foreach($r in $rs) {
        try {
            $r.Instance.EndInvoke($r.AsyncResult)
            $r.Instance.Dispose()
        }
        catch {
            Write-Error $_
        }
    }
}
finally {
    $rspool.ForEach('Dispose')
}

Adding here another alternative to my previous answer, using a RunspacePool instance which has built-in a way of concurrency and enqueuing.

using namespace System.Management.Automation.Runspaces

try {
    # define number of threads that can run at the same time
    $threads = 10

    # define IPs as Key and FileName as Value
    $lookup = @{
        '1.2.3.4'      = 'FileNameForThisIP'
        '192.168.1.15' = 'AnotherFileNameForTHatIP'
    }

    # path to directory executable
    $plink  = 'path\to\plinkdirectory\'
    # path to log directory
    $LogDir = 'path\to\logDirectory'
    # serial port
    $port   = 123

    $iss    = [initialsessionstate]::CreateDefault2()
    $rspool = [runspacefactory]::CreateRunspacePool(1, $threads, $iss, $Host)
    $rspool.ApartmentState = 'STA'
    $rspool.ThreadOptions  = 'ReuseThread'

    # session variables that will be intialized with the runspaces
    $rspool.InitialSessionState.Variables.Add([SessionStateVariableEntry[]]@(
        [SessionStateVariableEntry]::new('plink', $plink, '')
        [SessionStateVariableEntry]::new('serialport', $port, '')
        [SessionStateVariableEntry]::new('logDir', $LogDir, '')
    ))
    $rspool.Open()

    $rs = foreach($i in $lookup.GetEnumerator()) {
        $ps = [powershell]::Create().AddScript({
            param($pair)

            filter timestamp {
                $sw.WriteLine("$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_")
            }

            try {
                $path = Join-Path $LogDir -ChildPath ('{0}{1}.txt' -f $pair.Value, (Get-Date -f MM-dd-yyyy))
                $sw = [System.IO.StreamWriter]::new($path)
                $sw.AutoFlush = $true

                & "$plink\plink.exe" -telnet $pair.Key -P $serialPort | TimeStamp
            }
            finally {
                $sw.ForEach('Dispose')
            }
        }).AddParameter('pair', $i)

        $ps.RunspacePool = $rspool

        @{
            Instance    = $ps
            AsyncResult = $ps.BeginInvoke()
        }
    }

    foreach($r in $rs) {
        try {
            $r.Instance.EndInvoke($r.AsyncResult)
            $r.Instance.Dispose()
        }
        catch {
            Write-Error $_
        }
    }
}
finally {
    $rspool.ForEach('Dispose')
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文