简体   繁体   English

如何在 python 中运行 Powershell 脚本

[英]How to run a Powershell script in python

So my question is how do I run a PowerShell script in python, with passable variables from python, then have the python run the PowerShell script, and then from there have specific variables from the PowerShell script pass to the python script.所以我的问题是如何在 python 中运行 PowerShell 脚本,并使用来自 python 的可传递变量,然后让 882765404344488 运行 PowerShell 脚本,然后从那里将特定变量从 882730794414488 脚本 7 传递给 4584 脚本 7

What I have already is each code working separately.我已经拥有的是每个代码单独工作。 As you can see I am passing in hidden variables from a .ini file and from there I am trying to pass the compList to Powershell.如您所见,我正在从.ini文件传递隐藏变量,然后我试图从那里将compList传递给 Powershell。

I am not confident that I am running the command right to call PowerShell and pass the args in my python script我不确定我是否正在运行命令来调用 PowerShell 并在我的 python 脚本中传递参数

preferences = configparser.ConfigParser()
preferences.read('config.ini')

hostName = preferences.get('Directory', 'hostName')
port = preferences.get('Directory', 'port')
serviceName = preferences.get('Directory', 'serviceName')
usr = preferences.get('Credentials', 'userName')
pswrd = preferences.get('Credentials', 'password')
compList = preferences.get('ComputerList', 'compList')
compList = list(compList.split(","))

p = subprocess.Popen(["powershell.exe", r"C:\Users\pecorgx\TestPS1.ps1", 'arg1 @("compList")'], stdout=sys.stdout)
p.communicate()

My PowerShell Script:我的 PowerShell 脚本:

$ArrComputers =  $arg1


Clear-Host
foreach ($Computer in $ArrComputers) 
{
    $computerSystem = get-wmiobject Win32_ComputerSystem -Computer $Computer
    $computerBIOS = get-wmiobject Win32_BIOS -Computer $Computer
    $computerOS = get-wmiobject Win32_OperatingSystem -Computer $Computer
    $computerCPU = get-wmiobject Win32_Processor -Computer $Computer
    $hdds = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter drivetype=3
        write-host "System Information for: " $computerSystem.Name -BackgroundColor DarkCyan
        "-------------------------------------------------------"
        "Manufacturer: " + $computerSystem.Manufacturer
        "Model: " + $computerSystem.Model
        "Serial Number: " + $computerBIOS.SerialNumber
        "CPU: " + $computerCPU.Name
        foreach ($computerhdd in $hdds) { "HDD Drive Letter: " + $computerhdd.DeviceID + "HDD Capacity:" + "{0:N2}" -f ($computerHDD.Size/1GB) + "GB" + " HDD Space: " + "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size) }
        "RAM: " + "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB) + "GB"
        "Operating System: " + $computerOS.caption + ", Service Pack: " + $computerOS.ServicePackMajorVersion
        "User logged In: " + $computerSystem.UserName
        "Last Reboot: " + $computerOS.ConvertToDateTime($computerOS.LastBootUpTime)
        ""
        "-------------------------------------------------------"
}

I think I am passing this correctly but I want the Powershell to pass back to my python script我想我传递的是正确的,但我希望 Powershell 传回我的 python 脚本

$computerSystem.TotalPhysicalMemory/1GB
$computerSystem.Manufacturer
$computerSystem.Model
$computerBIOS.SerialNumber
$computerCPU.Name

and I want this var $computerHDD.Size/1GB to be passed into a list to be also passed to my python script我希望这个 var $computerHDD.Size/1GB被传递到一个列表中,也被传递到我的 python 脚本

EDIT: I decided to just use .txt to pass commands.编辑:我决定只使用.txt来传递命令。 I made $myOBJ = "" | Select "computer"我做了$myOBJ = "" | Select "computer" $myOBJ = "" | Select "computer" then made $myOBJ.computer = [string](....) with (...) being things I want to pass back out after the script has ran Would love to know a solution to use without having a third party help $myOBJ = "" | Select "computer"然后制作了$myOBJ.computer = [string](....) with (...)是我想在脚本运行后传回的东西 很想知道一个无需使用的解决方案第三方帮助

Here is simplified example of your use case:这是您的用例的简化示例:

import subprocess;
process=subprocess.Popen(["powershell","Get-Childitem C:\\Windows\\*.log"],stdout=subprocess.PIPE);
result=process.communicate()[0]
print (result)

Of course the above is just printing out a directory list, but you just replace that command with your.ps1 script path.当然,上面只是打印出一个目录列表,但您只需将该命令替换为您的 .ps1 脚本路径即可。

Also, as noted in my comment, why not just use the...另外,正如我在评论中指出的那样,为什么不直接使用...

# Get specifics for a module, cmdlet, or function
(Get-Command -Name Get-ComputerInfo).Parameters
(Get-Command -Name Get-ComputerInfo).Parameters.Keys
Get-help -Name Get-ComputerInfo -Examples
Get-Help -Name Get-ComputerInfo -Detailed
Get-help -Name Get-ComputerInfo -Full
Get-help -Name Get-ComputerInfo -Online

Get-ComputerInfo -Property '*'

... cmdlet, to collect this info and select the properties you want? ... cmdlet,以收集此信息和 select 您想要的属性? Only running the other collectors for info that Get-ComputerInfo does not provide.仅针对Get-ComputerInfo未提供的信息运行其他收集器。

There is also the built-in...还有内置的...

Get-PhysicalDisk
Get-Volume

... cmdlets to get storage information. ... 用于获取存储信息的 cmdlet。

How about constructing your output details this way...以这种方式构建您的 output 详细信息如何...

Clear-Host
$env:COMPUTERNAME | 
ForEach-Object{
    $computerSystem = Get-wmiobject Win32_ComputerSystem -ComputerName $PSItem
    $computerBIOS   = Get-wmiobject Win32_BIOS -ComputerName $PSItem
    $computerOS     = Get-wmiobject Win32_OperatingSystem -ComputerName $PSItem
    $computerCPU    = Get-wmiobject Win32_Processor -ComputerName $PSItem


    (
        $ComputerInfo = [PSCustomObject]@{
                            Manufacturer    = $computerSystem.Manufacturer
                            Model           = $computerSystem.Model
                            SerialNumber    = $computerBIOS.SerialNumber
                            CPU             = $computerCPU.Name 
                            RAM             = [math]::Round($($computerSystem.TotalPhysicalMemory/1GB), 3)
                            OperatingSystem = "$($computerOS.caption), Service Pack: $($computerOS.ServicePackMajorVersion)"
                            LoggedOnUser    = $env:USERNAME  
                            LastReboot      = $computerOS.ConvertToDateTime($computerOS.LastBootUpTime) 
                        }
    )

    (
        $StorageInfo = [PSCustomObject]@{
                            DeviceID      = (Get-Volume).DriveLetter
                            Size          = Get-Volume | ForEach {[math]::Round($($PSitem.Size/1GB), 3)}
                            SizeRemaining = Get-Volume | ForEach {[math]::Round($($PSitem.SizeRemaining/1GB), 3)}
                        }
    )
}

... or combine and ouput this way ...或以这种方式组合并输出

Clear-Host
$env:COMPUTERNAME | 
ForEach-Object{
    $ComputerSystem  = Get-wmiobject Win32_ComputerSystem -ComputerName $PSItem | 
                       Select-Object -Property Manufacturer, Model, UserName

    $ComputerBIOS    = Get-wmiobject Win32_BIOS -ComputerName $PSItem| 
                       Select-Object -Property SerialNumber

    $ComputerOS      = Get-wmiobject Win32_OperatingSystem -ComputerName $PSItem  | 
                       Select-Object -Property Caption, ServicePackMajorVersion, 
                       @{
                            Name       = 'LastReboot'
                            Expression = {$PSItem.ConvertToDateTime($PSItem.LastBootUpTime)}
                       }

    $ComputerCPU     = Get-wmiobject Win32_Processor -ComputerName $PSItem | 
                       Select-Object -Property Name

    $ComputerStorage = Get-WmiObject Win32_LogicalDisk -ComputerName $PSItem -Filter drivetype=3 | 
                       Select-Object -Property DeviceID, 
                       @{
                           Name        = 'Size'
                           Expression = {[math]::Round($($PSitem.Size/1GB), 3)}
                       }, 
                       @{
                           Name        = 'FreeSpace'
                           Expression = {[math]::Round($($PSitem.FreeSpace/1GB), 3)}
                       }


    $ComputerDetails = New-Object -Type PSObject

    $ComputerSystem, $ComputerBIOS, $ComputerOS, $ComputerCPU, $ComputerStorage | 
    ForEach-Object {
        $CurObj = $PSItem 
        $PSItem | 
        Get-Member | 
        Where-Object {$PSItem.MemberType -match 'NoteProperty'} | 
        ForEach-Object {
            $NewMember = $PSItem.Name
            $ComputerDetails | 
            Add-Member -MemberType NoteProperty -Name $NewMember -Value $CurObj.$NewMember
        }
    }
}
$ComputerDetails

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

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