Return variable value from second powershell script to first PowerShell script?

大城市里の小女人 提交于 2019-12-20 06:38:44

问题


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
}

Now I have a second script which is:

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

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

回答1:


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


来源:https://stackoverflow.com/questions/43061369/return-variable-value-from-second-powershell-script-to-first-powershell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!