将变量值从第二个Powershell脚本返回到第一个PowerShell脚本? [英] Return variable value from second powershell script to first PowerShell script?

查看:115
本文介绍了将变量值从第二个Powershell脚本返回到第一个PowerShell脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了1.ps1脚本,该脚本调用2.ps1脚本.调用2.ps1后,它会在$variable中给出一些结果.我希望将此$variable结果用于我的1.ps1中进行操作.

I created 1.ps1 script which calls 2.ps1 script. After calling 2.ps1 it give some result in $variable. I want this $variable result to be used in my 1.ps1 for manipulation.

$csv = Get-Content \\10.46.198.141\try\windowserver.csv
foreach ($servername in $csv) {
    $TARGET = $servername
    $ProfileName = "CustomPowershell"
    $SCRIPT = "powershell.exe -ExecutionPolicy Bypass -File '\\10.46.198.141\try\disk_space.ps1' '$servername'"
    $HubRobotListPath = "C:\Users\Automation\Desktop\hubrobots.txt"
    $UserName = "aaaaa"
    $Password = "aaaaaaa"
    $Domain = "SW02111_domain"
    $HubOne = "sw02111"
    #lots of code here
}

现在我有第二个脚本是

Param([string]$servername)

$hash = New-Object PSObject -Property @{
    Servername = "";
    UsedSpace = "";
    DeviceID = "";
    Size = "";
    FreeSpace = ""
}

$final =@()
$hashes =@()

$hash = New-Object PSObject -Property @{
    Servername = $servername;
    UsedSpace = "";
    DeviceID = "";
    Size = "";
    FreeSpace = ""
}

$hashes += $hash
$space = Get-WmiObject Win32_LogicalDisk

foreach ($drive in $space) {
    $a = $drive.DeviceID
    $b = [System.Math]::Round($drive.Size/1GB) 
    $c = [System.Math]::Round($drive.FreeSpace/1GB) 
    $d = [System.Math]::Round(($drive.Size - $drive.FreeSpace)/1GB) 
    $hash = New-Object PSObject -Property @{
        Servername = "";
        UsedSpace = $d;
        DeviceID = $a;
        Size = $b;
        FreeSpace = $c
    }
    $hashes += $hash
}

$final += $hashes

return $final

我想使用此$final输出使用第一个PowerShell脚本中的代码创建CSV文件:

I want to use this $final output to create a CSV file with code in the first PowerShell script:

$final | Export-Csv C:\Users\Automation\Desktop\disk_space.csv -Force -NoType

推荐答案

不要使事情变得比需要的复杂.使用管道并计算的属性.

Don't make things more complicated than they need to be. Use the pipeline and calculated properties.

Get-Content serverlist.txt |
    ForEach-Object { Get-WmiObject Win32_LogicalDisk -Computer $_ } |
    Select-Object PSComputerName, DeviceID,
        @{n='Size';e={[Math]::Round($_.Size/1GB)}},
        @{n='FreeSpace';e={[Math]::Round($_.FreeSpace/1GB)}},
        @{n='UsedSpace';e={[Math]::Round(($_.Size - $_.FreeSpace)/1GB)}} |
    Export-Csv disksize.csv -Force -NoType

这篇关于将变量值从第二个Powershell脚本返回到第一个PowerShell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆