powershell computer information script - powershell

I need to create a powershell script you can double-click on (64-bit computer) and it will output to a .txt file in the same location as the powershell script to generate information on:
Computer name/model/serial no.
C drive size/available disk space on the C drive
Which version operating system the computer is running
Who is currently logged onto the computer
So far (but it's not quite working) I've got:
$computerSystem = get-wmiobject Win32_ComputerSystem
$computerOS = get-wmiobject Win32_OperatingSystem
$computerHDD = Get-WmiObject Win32_LogicalDisk -Filter drivetype=3
$txtObject = New-Object PSObject -property #{
'PCName' = $computerSystem.Name
'Model' = $computerSystem.Model
'SerialNumber' = $computerBIOS.SerialNumber
'HDDSize' = "{0:N2}" -f ($computerHDD.Size/1GB)
'HDDFree' = "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size)
'OS' = $computerOS.caption
'SP' = $computerOS.ServicePackMajorVersion
'User' = $computerSystem.UserName
}
$txtObject | Select PCName, Model, SerialNumber, HDDSize, HDDFree, OS, SP, User | Get-Process | Out-File 'system-info.txt' -NoTypeInformation -Append

$PSScriptRoot = current location where your script is launched, so if you specify it in the save path like Out-File "$PSScriptRoot\system-info.txt", it will be saved at the same location as the script
Get-Process can't be used at this position
NoTypeInformation does not exist as a parameter of Out-File
$computerSystem = get-wmiobject Win32_ComputerSystem
$computerOS = get-wmiobject Win32_OperatingSystem
$computerHDD = Get-WmiObject Win32_LogicalDisk -Filter drivetype=3
$txtObject = New-Object PSObject -property #{
'PCName' = $computerSystem.Name
'Model' = $computerSystem.Model
'SerialNumber' = $computerBIOS.SerialNumber
'HDDSize' = "{0:N2}" -f ($computerHDD.Size/1GB)
'HDDFree' = "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size)
'OS' = $computerOS.caption
'SP' = $computerOS.ServicePackMajorVersion
'User' = $computerSystem.UserName
}
$txtObject | Select-Object PCName, Model, SerialNumber, HDDSize, HDDFree, OS, SP, User | Out-File "$PSScriptRoot\system-info.txt" -Append

Related

I want to get details of task manger users tab about ram and cpu utilization

I have following script, i want to get each users details of ram and cpu utilization separately in csv file. but from this script i am getting all users details in a single line instead of individually user based resources utilization details in csv file.
This is my Powershell code
GC c:\List.txt | % {
$xl = New-Object -ComObject "Excel.Application"
$xl.Visible = $true
$xl.DisplayAlerts = $false #for debugging, no prompts to save, etc.
$ConvertToGB = (1024 * 1024 * 1024)
$wkbk = $xl.Workbooks.Add()
$sheet = $wkbk.WorkSheets.Item(1)
$sheet.Name = "Transposed"
$Comp = $_
If (Test-Connection $Comp -Quiet) {
$Luser = (Get-WmiObject -class win32_process -Filter "Name='Explorer.exe'" -ComputerName $Comp |
% {$_.GetOwner().User} | Sort-Object -Unique) -join ","
$Mem = GWMI -Class win32_operatingsystem -computername $COMP
New-Object PSObject -Property #{
Server = $Comp
"CPU_Usage" = "$((GWMI -ComputerName $COMP win32_processor | Measure-Object -property LoadPercentage -Average).Average)"
"Memory_Usage" = "$("{0:N2}" -f ((($Mem.TotalVisibleMemorySize - $Mem.FreePhysicalMemory)*100)/ $Mem.TotalVisibleMemorySize)) %"
"DiskSpace" = "$("{0:N2}" -f (Get-WmiObject -Class win32_logicaldisk -ComputerName $COMP -Filter "DriveType = 3"| Select-Object "Size","FreeSpace"))"
#$Comp = ($disk.Size / $ConvertToGB),($disk.FreeSpace / $ConvertToGB)
"logged_Users" = $Luser
}
}
Else {
}
$results = Get-Service -Name *bits*| Select Server #,"CPU usage","Memory usage","DiskFreeSpace","logged Users"
$column = 1
$row = 1
foreach ($psRow in $results) {
foreach ($item in $psRow.PSObject.Properties) {
$sheet.Cells.Item($row, $column) = $item.Name
$column++
#$sheet.Cells.Item($row, $column) = $item."CPU","Memory_Usage","DiskSpace","logged_Users"
$row++
$column--
}
} }
$obj =New-Object PSObject -Property #{
Server = $Comp
"CPU_Usage" = "$((GWMI -ComputerName $COMP win32_processor | Measure-Object -property LoadPercentage -Average).Average)"
"Memory_Usage" = "$("{0:N2}" -f ((($Mem.TotalVisibleMemorySize - $Mem.FreePhysicalMemory)*100)/ $Mem.TotalVisibleMemorySize)) %"
"DiskSpace" = Get-WmiObject -Class win32_logicaldisk -ComputerName $COMP -Filter "DriveType = 3"| Select-Object "Size","FreeSpace"
#$Comp = ($disk.Size / $ConvertToGB),($disk.FreeSpace / $ConvertToGB)
"logged_Users" = $Luser
}
Write-Output "DiskSpace, $($obj.DiskSpace.Size), $($obj.DiskSpace.FreeSpace)"
Write-Output "Server, $($obj.Server)"
Write-Output "Memory_Usage, $($obj.Memory_Usage)"
Write-Output "logged_Users, $($obj.logged_Users)"
Write-Output "CPU_Usage, $($obj.CPU_Usage)"
$obj | ConvertTo-Csv
These are the results i am getting
Memory_Usage : 91.90 %
CPU_Usage : 99
Server : 127.0.0.1
logged_Users : user1,user2,user3,userA
DiskSpace : {#{Size=718642417664; FreeSpace=317923561472}, #{Size=214747312128; FreeSpace=182724562944}, #{Size=26507997184; FreeSpace=3710320640},
#{Size=1099511627776; FreeSpace=989560467456}}
I need this type of result in csv
logged users | Memory Usage in MB | CPU Usage % |
User1 25300 8
User2 33658 15
User3 48793 7
UserA 23564 5
why don't you use select-object? I can't test it b/c your script doesn't have the full code for me to test it, but it would be a little something like:
get-psdrive | Where Free* | Select-Object Name, #{Name='UsedGB'; Expression={$_.Used/1GB}}, #{Name='FreePerc'; Expression={'{0:p0}' -f((($_.Used)/1GB) / (($_.Free + $_.Used)/1GB))}}, #{Name='TotalSize'; Expression={($_.Free + $_.Used)/1GB}}
Result:
Name UsedGB FreePerc TotalSize
---- ------ -------- ---------
A 192.771030426025 81% 238.473628997803
C 336.458614349365 36% 930.742183685303
D 7043.1279296875 95% 7452.00390625
E 110.902645111084 47% 238.473628997803
You can use this to build the table you want.
From there, to export it to csv; I would assume you can export it with a pipe follow by export-csv -path (Destination + file name) -NoTypeInformation

Powershell CSV Output Issue

Can anyone assist my with explanation as to why I get System.String[] as my Gateway output in the CSV file but it works fine in the ISE view/window.
$testcomputers = Get-Content -Path 'C:\Users2\101.txt'
$exportLocation = 'C:\Users2\PingResults.csv'
# Test connection to each computer before getting the inventory info
foreach ($computer in $testcomputers) {
if (Test-Connection -ComputerName $computer -Quiet -count 1){
Add-Content -value $computer -path C:\Users2\OnlineComputers.txt
}else{
Add-Content -value $computer -path C:\Users2\OfflineComputers.txt
}
}
#Specify the list of PC names in the line below
$ArrComputers = Get-Content -Path 'C:\Users2\OnlineComputers.txt'
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
$computerHDD = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter drivetype=3
$computerGateway = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Computer $Computer -Filter “IPEnabled=TRUE”
write-host "System Information for: " $computerSystem.Name -BackgroundColor DarkCyan
"-------------------------------------------------------"
"Manufacturer: " + $computerSystem.Manufacturer
"Model: " + $computerSystem.Model
"Serial Number: " + $computerBIOS.SerialNumber
"CPU: " + $computerCPU.Name
"HDD Capacity: " + "{0:N2}" -f ($computerHDD.Size/1GB) + "GB"
"HDD Space: " + "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size) + " Free (" + "{0:N2}" -f ($computerHDD.FreeSpace/1GB) + "GB)"
"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)
"Gateway: " + $computerGateway.DefaultIPGateway
""
"-------------------------------------------------------"
#Build the CSV file
$csvObject = New-Object PSObject -property #{
'PCName' = $computerSystem.Name
'Manufacturer' = $computerSystem.Manufacturer
'Model' = $computerSystem.Model
'Service Tag' = $computerBIOS.SerialNumber
'RAM' = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB)
'HDDSize' = "{0:N2}" -f ($computerHDD.Size/1GB)
'HDDFree' = "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size)
'CPU' = $computerCPU.Name
'OS' = $computerOS.caption
'SP' = $computerOS.ServicePackMajorVersion
'User' = $computerSystem.UserName
'Last_Reboot' = $computerOS.ConvertToDateTime($computerOS.LastBootUpTime)
'Gateway' = $computerGateway.DefaultIPGateway
}
#Export the fields you want from above in the specified order
$csvObject | Select PCName, Manufacturer, Model, OS, SerialNumber, CPU, Ram, User, Last_Reboot, HDDSize, HDDFree, Gateway | Export-Csv 'C:\Users2\results.csv' -NoTypeInformation -Append
}
Here is the ISE output
System Information for: WS101161
-------------------------------------------------------
Manufacturer: Dell Inc.
Model: OptiPlex 5070
Serial Number: 7HF8T13
CPU: Intel(R) Core(TM) i5-9500 CPU # 3.00GHz
HDD Capacity: 237.96GB
HDD Space: 67.87% Free (161.51GB)
RAM: 15.79GB
Operating System: Microsoft Windows 10 Pro, Service Pack: 0
User logged In:
Last Reboot: 04/28/2022 17:40:52
Gateway: 10.170.1.250
-------------------------------------------------------
And here is the CSV output (User being empty is okay, nobody is signed into this PC at the moment)
"PCName","Manufacturer","Model","OS","SerialNumber","CPU","RAM","User","Last_Reboot","HDDSize","HDDFree","Gateway"
"WS101161","Dell Inc.","OptiPlex 5070","Microsoft Windows 10 Pro",,"Intel(R) Core(TM) i5-9500 CPU # 3.00GHz","15.79",,"4/28/2022 5:40:52 PM","237.96","67.87%","System.String[]"
Thank you for the assistance!
asdasdasd
The main issue that answers your question, the property DefaultIPGateway of the Win32_NetworkAdapterConfiguration class is of the type string[]:
DefaultIPGateway
Data type: string array
You need to convert it to string so that Export-Csv can handle it:
PS /> #{ Gateway = $computerGateway[0].DefaultIPGateway } | ConvertTo-Csv
"Gateway"
"System.String[]"
PS /> #{ Gateway = [string] $computerGateway[0].DefaultIPGateway } | ConvertTo-Csv
"Gateway"
"192.168.0.1"
It is also worth noting that $computerGateway may return an array of IPs in which case you should join them:
$computerGateway.DefaultIPGateway -join ', '
Aside from that, there are other issues with your code, for example all Division operations on $computerHDD:
$computerHDD.Size / 1GB
Will throw this exception if the host has more than one Physical Disk:
InvalidOperation: Method invocation failed because [System.Object[]] does not contain a method named 'op_Division'.
Test-NetConnection is not reliable to tell you if you can or cannot connect to a remote host, there may be a firewall blocking ICMP packets and you may have been able to still connect it since the protocol being used in your code is WinRM (WinRM HTTP uses port 5985 and WinRM HTTPS uses port 5986).
Your code can also be invoked in parallel instead of going one host at a time, Invoke-Command is the best alternative as Lee_Dailey mentions in his helpful comment.
Sending information to the console (Write-Host) will only slow your script down, I've removed all instances of console output.
Appending to a file with Export-Csv -Append on each iteration of your loop will also slow your script down, the more Disk I/O the slower the code will be, it is better to collect all output first in memory and then writing to a file once.
Lastly, Get-WmiObject should be replaced by Get-CimInstance. All the WMI Cmdlets are no longer in circulation in newer versions of PowerShell (PowerShell Core). And the CIM Cmdlets have been available since PowerShell 3. No reason to use WMI over CIM.
With all that being said, this is how I would approach your script:
$unavaibleHosts = [System.Collections.Generic.List[string]]::new()
$session = foreach($computer in Get-Content -Path 'C:\Users2\101.txt') {
try {
New-PSSession $computer -ErrorAction Stop
}
catch {
$unavaibleHosts.Add($computer)
}
}
Invoke-Command -Session $session -HideComputerName -ScriptBlock {
$computerSystem = Get-CimInstance Win32_ComputerSystem
$computerBIOS = Get-CimInstance Win32_BIOS
$computerOS = Get-CimInstance Win32_OperatingSystem
$computerCPU = Get-CimInstance Win32_Processor
$computerHDD = Get-CimInstance Win32_LogicalDisk -Filter drivetype=3
$computerGateway = Get-CimInstance -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE
$hddSize = $computerHDD.ForEach{ "[{0} {1:N2}]" -f $_.DeviceID, ($_.Size / 1GB) } -join ' | '
$hddFree = $computerHDD.ForEach{ "[{0} {1:P2}]" -f $_.DeviceID, ($_.FreeSpace / $_.Size) } -join ' | '
# output from these 2 would look like this:
# HDDSize : [C: 236.76] | [D: 931.51]
# HDDFree : [C: 73.30%] | [D: 81.43%]
[pscustomobject]#{
'PCName' = $computerSystem.Name
'Manufacturer' = $computerSystem.Manufacturer
'Model' = $computerSystem.Model
'Service Tag' = $computerBIOS.SerialNumber
'RAM' = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory / 1GB)
'HDDSize' = $hddSize
'HDDFree' = $hddFree
'CPU' = $computerCPU.Name
'OS' = $computerOS.caption
'SP' = $computerOS.ServicePackMajorVersion
'User' = $computerSystem.UserName
'Last_Reboot' = $computerOS.LastBootUpTime
'Gateway' = $computerGateway.DefaultIPGateway -join ','
}
} | Select-Object * -ExcludeProperty RunspaceId | Export-Csv 'C:\Users2\results.csv' -NoTypeInformation
Remove-PSSession $session
$unavaibleHosts # => Is here for you to troubleshoot the failed connections.
# https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-networkadapterconfiguration
# DefaultIPGateway
# Data type: string array
# Access type: Read-only
# Qualifiers: MappingStrings ("Win32Registry|System\\CurrentControlSet\\Services|Parameters|DefaultGateway")
# Array of IP addresses of default gateways that the computer system uses.
# Example: "192.168.12.1 192.168.46.1"
# Your case
$computerGateway = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Computer "DESKTOP-9EPNRSP" -Filter "IPEnabled=TRUE"
$csvObject = New-Object PSObject -property #{
'Gateway' = $computerGateway.DefaultIPGateway
}
$csvObject.Gateway.GetType().FullName
# Convert to String
$computerGateway = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Computer "DESKTOP-9EPNRSP" -Filter "IPEnabled=TRUE"
$csvObject = New-Object PSObject -property #{
'Gateway' = "$($computerGateway.DefaultIPGateway)"
}
$csvObject.Gateway.GetType().FullName
#Take first element
$computerGateway = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Computer "DESKTOP-9EPNRSP" -Filter "IPEnabled=TRUE"
$csvObject = New-Object PSObject -property #{
'Gateway' = $computerGateway.DefaultIPGateway[0]
}
$csvObject.Gateway.GetType().FullName
#Generate with comma sepparated - █ Recommended █
$computerGateway = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Computer "DESKTOP-9EPNRSP" -Filter "IPEnabled=TRUE"
$csvObject = New-Object PSObject -property #{
'Gateway' = [string]::Join(",", $computerGateway.DefaultIPGateway)
}
$csvObject.Gateway.GetType().FullName
Output
System.String[]
System.String
System.String
System.String

How to export information about the monitor to a csv file using PowerShell?

I am new to PowerShell and am struggling to write a script to export the UserFriendlyName (see the code below) for three monitors. Here is what I have so far:
$monitors = Get-WmiObject -Namespace root\wmi -Class wmiMonitorID
Get-CimInstance -Namespace root\wmi -ClassName wmimonitorid -ComputerName $ComputerName |
foreach {
$Object = New-Object PSObject -Property #{
MonitorName = ($monitors.UserFriendlyName -notmatch '^0$' | foreach {[char]$_}) -join ""
MonitorSerial = ($monitors.serialnumberid -notmatch '^0$' | foreach {[char]$_}) -join ""
}
}
$Object | Select MonitorName,MonitorSerial
$Object | Export-Csv -append -force /Computer.csv -NoTypeInformation
The result that I am getting:
MonitorName MonitorSerial
----------- -------------
27B1DELL P2717HDELL P2717H GUHJBHA018695YKNFG6CQAGLLYKNFG71KAPTL
I would like to have each monitor name and serial number under their own column (Monitor 1, Monitor 2, Monitor 3 and the same for serial number) but the values are together. Any help is much appreciated.
I am hoping to have the above incorporated with this:
$computerSystem = Get-CimInstance CIM_ComputerSystem
$computerBIOS = Get-CimInstance CIM_BIOSElement
$computerOS = Get-CimInstance CIM_OperatingSystem
$computerCPU = Get-CimInstance CIM_Processor
$computerHDD = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID = 'C:'"
Get-CimInstance -Namespace root\wmi -ClassName wmimonitorid -ComputerName $ComputerName |
foreach {
$Object = New-Object PSObject -Property #{
"Computer Name" = $computerSystem.Name
"Operating System" = $computerOS.caption + ", Service Pack: " + $computerOS.ServicePackMajorVersion
"Manufacturer" = $computerSystem.Manufacturer
"Model" = $computerSystem.Model
"Serial Number" = $computerBIOS.SerialNumber
"CPU" = $computerCPU.Name
"HDD Capacity" = "{0:N2}" -f ($computerHDD.Size/1GB) + "GB"
"RAM" = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB) + "GB"
"User logged In" = $computerSystem.UserName
}
}
$Object | Export-Csv -append -force /Computer.csv -NoTypeInformation
Something does not seem right with your code. You should be adding each monitor to an array or a list.
$monitors = Get-WmiObject -Namespace root\wmi -Class wmiMonitorID
$allMonitors = #()
Get-CimInstance -Namespace root\wmi -ClassName wmimonitorid -ComputerName $ComputerName |
foreach {
$Object = [PSCustomObject]#{
MonitorName = ($monitors.UserFriendlyName -notmatch '^0$' | foreach {[char]$_}) -join ""
MonitorSerial = ($monitors.serialnumberid -notmatch '^0$' | foreach {[char]$_}) -join ""
}
$allMonitors += $Object
}
$allMonitors | Select MonitorName,MonitorSerial
$allMonitors | Export-Csv -append -force /Computer.csv -NoTypeInformation

powershell drives calculator

So I have the below code which works quite well but for some reason it's only calculating my D: drive and not also my C: drive?
$computerName = Get-Wmiobject Win32_ComputerSystem
$computerOS = Get-Wmiobject Win32_OperatingSystem
$computerHDD = Get-Wmiobject Win32_LogicalDisk -Filter drivetype=3
ForEach($HDD in $computerHDD){
$txtObject = New-Object PSObject -property #{
'ComputerName' = $computerName.Name
'ComputerModel' = $computerName.Model
'SerialNumber' = $computerName.SerialNumber
'HDDSize' = "{0:N2}" -f ($HDD.Size/1GB)
'HDDFree' = "{0:P2}" -f ($HDD.FreeSpace/$HDD.Size)
'OS' = $computerOS.caption
'OS_type' = $computerOS.OSArchitecture
'User' = $computerName.UserName
}
}
$txtObject | Select-Object ComputerName, ComputerModel, SerialNumber, HDDSize, HDDFree, OS, Os_type, User | Out-File "$PSSCriptRoot\computer_info.txt" -Append
seems like you would need to make an array. Try this...
$computerName = Get-Wmiobject Win32_ComputerSystem
$computerOS = Get-Wmiobject Win32_OperatingSystem
$computerHDD = Get-Wmiobject Win32_LogicalDisk -Filter drivetype=3
$output = #()
ForEach($HDD in $computerHDD){
$txtObject = New-Object PSObject -property #{
'ComputerName' = $computerName.Name
'ComputerModel' = $computerName.Model
'SerialNumber' = $computerName.SerialNumber
'HDDSize' = "{0:N2}" -f ($HDD.Size/1GB)
'HDDFree' = "{0:P2}" -f ($HDD.FreeSpace/$HDD.Size)
'OS' = $computerOS.caption
'OS_type' = $computerOS.OSArchitecture
'User' = $computerName.UserName
}
$output += $txtObject
}
$output | Select-Object ComputerName, ComputerModel, SerialNumber, HDDSize, HDDFree, OS, Os_type, User | Out-File "$PSSCriptRoot\computer_info.txt" -Append
You're overwriting $txtObject on every iteration of the loop, so your output only contains the drive from the final iteration. Instead, you should be initializing $txtObject as an array and then appending each drive's information to that:
$computerHDD = Get-Wmiobject Win32_LogicalDisk -Filter drivetype=3
$txtObject = #()
ForEach($HDD in $computerHDD){
$txtObject += New-Object PSObject -property #{
# ...
}
}
$txtObject | Select-Object ... | Out-File "$PSSCriptRoot\computer_info.txt" -Append
Better yet, you can eliminate the loop and the variable and just use the pipeline:
$computerName = Get-WmiObject Win32_ComputerSystem
$computerOS = Get-WmiObject Win32_OperatingSystem
Get-WmiObject Win32_LogicalDisk -Filter drivetype=3 `
| ForEach-Object -Process {
New-Object PSObject -Property #{
'ComputerName' = $computerName.Name
'ComputerModel' = $computerName.Model
'SerialNumber' = $computerName.SerialNumber
'HDDSize' = "{0:N2}" -f ($_.Size/1GB)
'HDDFree' = "{0:P2}" -f ($_.FreeSpace/$_.Size)
'OS' = $computerOS.caption
'OS_type' = $computerOS.OSArchitecture
'User' = $computerName.UserName
};
} | Out-File "$PSSCriptRoot\computer_info.txt" -Append
Note that New-Object above is nearly identical to your original code except $_ has to be used instead of $HDD.

How to make script run remotelly on computers?

I have written a script that is to collect hardware and software information from a forrest/domain. I've read several posts about running a PS-script from a computer on a server, but I want to do the opposite.
How do you know that a script is "remotely accesible".
I've seen this command beeing used:
Invoke-Command -ComputerName {serverName} –ScriptBlock { commands }
Is there any other alternatives than computername? I'm thinking that this is not exclussive as several computers can have the same name..
This is my script:
try{
$ConfirmPreference="none"
$error.clear()
$erroractionpreference = "silentlycontinue"
#Gets the date of this day, used as name for XML-file later.
$a = get-date -uformat "%Y_%m_%d"
#Saves computername to compname variable(HELPER)
$compname = gc env:computername
#Gets the path to directory for all saved files and folders
$scriptpath = Split-Path -parent $myinvocation.MyCommand.Definition
#PC Serial Number, is used as name for directory containing XML files for this computer.
$serialnr = gwmi win32_bios | select -Expand serialnumber
#Creates a folder with the name of the computers hardware serialnumber if it does not exist.
if(!(Test-Path -path $scriptpath\$serialnr)) {
New-item -path $scriptpath -name $serialnr -type directory
}
#Username
$username = gc env:username
#System Info
gwmi -computer $compname Win32_ComputerSystem | ForEach {$siname = $_.Name; $simanufacturer = $_.Manufacturer; $simodel = $_.Model}
#Graphic card
$gpuname = gwmi win32_VideoController | select -Expand Name
#Processor Info
gwmi -computer $compname Win32_Processor | ForEach-Object {$cpuname = $_.Name; $cpumanufacturer = $_.Manufacturer; $cpucores = $_.NumberOfCores; $cpuaddresswidth = $_.AddressWidth}
#Memory
$totalmem = 0
$memsticks = gwmi -Class win32_physicalmemory
foreach ($stick in $memsticks) { $totalmem += $stick.capacity }
$totalmem = [String]$($totalmem / 1gb) + " GB"
#Drive
$totalspace = 0
$totalsize = gwmi -Class win32_logicaldisk
foreach($size in $totalsize) { $totalspace += $size.size }
$totalspace = "{0:N2}" -f ($totalspace/1Gb) + " GB"
#Install time for windows OS
$utctime = get-wmiobject win32_OperatingSystem | select-object -expandproperty installDate
$installtime = [System.Management.ManagementDateTimeConverter]::ToDateTime($utctime);
$installtime = Get-Date $installtime -uformat "%d/%m/%Y %X"
#--------#
#XML-form
#--------#
try{
$erroractionpreference = "stop"
$template = "<computer version='1.0'>
<hardware>
<serialnumber>$serialnr</serialnumber>
<systeminfo>
<name>$siname</name>
<manufacturer>$simanufacturer</manufacturer>
<model>$simodel</model>
</systeminfo>
<drive>
<size>$totalspace</size>
</drive>
<memory>
<size>$totalmem</size>
</memory>
<gpu>
<name>$gpuname</name>
</gpu>
<cpu>
<name>$cpuname</name>
<manufacturer>$cpumanufacturer</manufacturer>
<id>cpuid</id>
<numberofcores>$cpucores</numberofcores>
<addresswidth>$cpuaddresswidth</addresswidth>
</cpu>
</hardware>
<software>
<user>
<name>$username</name>
</user>
<osinfo>
<caption></caption>
<installdate>$installtime</installdate>
<servicepack></servicepack>
</osinfo>
</software>
</computer>"
$template | out-File -force $ScriptPath\$serialnr\$a.xml
$systemroot = [System.Environment]::SystemDirectory
$xml = New-Object xml
$xml.Load("$ScriptPath\$serialnr\$a.xml")
}catch{
}
#OSInfo, software
$newosinfo = (#($xml.computer.software.osinfo)[0])
Get-WmiObject -computer $compname Win32_OperatingSystem |
ForEach-Object {
$newosinfo = $newosinfo.clone()
[String] $bitversion = $_.osarchitecture
$newosinfo.caption = [String]$_.caption + "" + $_.osarchitecture
$newosinfo.servicepack = $_.csdversion
$xml.computer.software.AppendChild($newosinfo) > $null
}
$xml.computer.software.osinfo | where-object {$_.caption -eq ""} | foreach-object {$xml.computer.software.RemoveChild($_)}
#-------Save and get content--------
$xml.Save("$scriptpath\$serialnr\$a.xml")
#$new = Get-Content $scriptpath\$serialnr\$a.xml
#-----------------------------------
if(!$?){
"An error has occured"
}
}catch{
[system.exception]
"Error in script: system exception"
}finally{
}
For the -ComputerName parameter, you can use NETBIOS name, IP address, or fully-qualified domain name. For more details, see Invoke-Command on TechNet.
Seems like your script is "only" saving the data on the machine it is running, you will probably want it to return something in order to be useful with Invoke-Command.