【问题标题】:Return variable value from second powershell script to first PowerShell script?从第二个powershell脚本返回变量值到第一个PowerShell脚本?
【发布时间】:2017-03-28 05:37:13
【问题描述】:

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

$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 输出来创建一个 CSV 文件,其中包含第一个 PowerShell 脚本中的代码:

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

【问题讨论】:

  • Get-WmiObject -Class Win32_logicaldisk -ComputerName $servername

标签: powershell scripting export-to-csv


【解决方案1】:

不要让事情变得比他们需要的更复杂。使用管道和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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多