Parameters will not be used with Invoke-Command remotely, -computername comes back null - host

I would like to know how to pass parameters with the Invoke-Command to be used within a script to run remotely.
enter code here
Param(
[string]$cname = (Read-Host "Computer Name?") ,
[string]$event = (Read-Host "What event?") ,
[string]$eventfilter = (Read-Host "What key word are you looking for?") '
[string]$amount = (Read-Host "How many events do you want to see?")
)
Invoke-Command -cn $cname -ScriptBlock {Get-EventLog -cn $cname -LogName $event -Message "*$eventfilter*" -Newest $amount | FT -Wrap}
I would like to know if this is possible and what I would need to do to fix this script?
Thanks

$cname = Read-Host "Computer Name?"
$event = Read-Host "What event?"
$eventfilter = Read-Host "What key word are you looking for?"
$amount = Read-Host "How many events do you want to see?"
Invoke-Command -cn $cname -ScriptBlock {Get-EventLog -cn $using:cname -LogName $using:event -Message "*$eventfilter*" -Newest $using:amount | FT -Wrap}

Related

How do I change my powershell script to GUI

I have recently started taking online Active Directory courses and in the process, I have developed a script for moving computers between OUs. The script is fine and running, but I was wondering if someone can help me change it to GUI(exe) file.
I have looked around and it does not seem there is a good place to provide a nice explanation. Code is below:
...script searches a computer given a keyword. user selects one of the computers listed after search. script then searches an OU based on a keyword input from user. Then, then uses chooses an option of the OUs listed after search. Script then moves the computer to that OU.
Import-Module ActiveDirectory
$computerName = Read-Host -Prompt 'Enter The Name of The Computer You Want To Move'
$temp = Get-ADComputer -filter "Name -like '*$computerName*'" -Properties DistinguishedName | Select-Object -Property DistinguishedName
#$comp[0].DistinguishedName.Split("=").Split(",")[1]
Function Select-Computer
{
$counter = 0
Write-Host "Select Item"
foreach ($c in $temp)
{
write-host "$counter :" $c.DistinguishedName.Split("=").Split(",")[1]
$Counter++
}
[ValidateNotNullOrEmpty()]
$Selection = Read-Host -Prompt 'Choose the computer you want to move'
return $temp[$Selection]
}
$returned = Select-Computer
$computerLocation = $returned.DistinguishedName
$keyword = Read-Host -Prompt "Enter a keyword of the OU you want to move to"
$find = Get-ADOrganizationalUnit -Filter "Name -like '*$keyword*'" -Properties DistinguishedName | Select-Object -Property DistinguishedName
Function Select-OU
{
$counter = 0
Write-Host "Select the OU"
foreach ($ou in $find)
{
$canonicalName = Get-ADOrganizationalUnit -Identity $ou.DistinguishedName -Properties CanonicalName | Select-Object CanonicalName
write-host "$counter :" $ou.DistinguishedName.Split("=").Split(",")[1] in "$canonicalName".Split("=").Replace("#", "").Replace("{", "").Replace("}", "").Replace("CanonicalName", "")
#DistinguishedName.Split("=").Replace("OU", "").Replace(",", "/")
#
$Counter++
}
[ValidateNotNullOrEmpty()]
$Selection = Read-Host -Prompt 'Choose the target you OU'
return $find[$Selection]
}
$return = Select-OU
$targetOU = $return.DistinguishedName
Move-ADObject -Identity "$computerLocation" -TargetPath "$targetOU" -Verbose

How can i divide copying files into priorities to copy different files

Im trying to build a way to create a folder structure in windows automatically absed on a job number and how many parts they will need. im able to get the code functioning to the point where i make the main folder, the sub folder and the sub folder in the folders with a part in it. the thing im looking to do however is transfer a different part into each folder based on priorities
There are max 7 priorities and that needs to be divided by how many parts so example would be there are 4 parts with 4 priorities.. (in this sample code it creates the sales folder, then puts a folder underneath it called conveyors then puts 4 folders in the conveyors folder with a number ) id like that to put four different parts in four different folders based on that how many priorities)
tried diving priorities but that wont work as i cant understand how to store an array to do what im asking
powershell
$salesorder = read-host -prompt 'What is the customer name and salesorder number? (ex.. turnkey - 3335)'
$jobnumber = read-host -prompt 'what is the Plant folder plus job number? (ex... 930-12345)'
$foldername = $jobnumber + " - " + $salesorder
#$conveyornumber = read-host -prompt "what is the number for conveyors? " + " - "
$priority = read-host -prompt "how many priorities are there?"
##************************* setting variables for second level basic Folder Structure *********************************
$partpath = '\\wal-file\public\sullivan\sully_temp_part.ipt'
$layout = 'D0100 - Layout'
$footprint = 'D0101 - Footprint'
$equipment = 'D01xx - Equipment'
$Guarding = 'D85xx - Guarding'
$conveyor = 'D60xx - Conveyors'
$platform = 'D90xx - Platforms'
#*************************** creating new variables based on folder name stylings *************************************
$workdir = new-item -path "C:\vault_workspace\Temp_vault\wendt\" -name $foldername -itemtype 'directory' -force
$layoutdir = new-item -path $workdir -name $layout -itemtype 'directory'
$layoutfilename = $layoutdir -join '.ipt'
#*************************** setting work directory input **************************************************************
new-item -path $layoutdir -name "$salesorder.ipt" -itemtype "file"
$footprintdir = new-item -path $workdir -name $footprint -itemtype 'directory'
$conveyordir = new-item -path $workdir -name $conveyor -itemtype 'directory'
#looping statement to create multiple folders
$conveyorinput = read-host -prompt "how many conveyors need to be made?"
for ($i = 1; $i -le $conveyorinput; $i++){"{0:D2}" -f $number} { [system.io.directory]::CreateDirectory("$conveyordir\D51$I")}
start-sleep -seconds 5
#creating multiple files
$conveyorarray = Get-ChildItem $conveyordir | Where-Object {$_.PSChildname} | Foreach-Object {$_.Name}
foreach ($path in $conveyorarray) {copy-item -path $partpath -destination "$conveyordir\$path\$jobnumber-4-$path-DUmmy-A0.ipt "}
i tried a few things all with mixed results no here close to what im looking to d. i tried goodling it but i couldnt figure out a way to implement anything close to what im asking some form of If statement would probably do it, but where would i put it and how would it work?
Thanks for any help
This is just a suggestion, can you look at adding functions so your code is readable. I can't see what you want. Can you also pepper it with output if you need to see what is going on Write-Host. I don't know what a sully sample is or how it is related to this so my guess is it's a folder or an ipt file? I can't read the code code-readability as it doesn't convey what you intend to to as far as I can tell beyond creating directories? If you can leave out the 'sully sample' language and use widget I think we could understand it better. Such as I need 4 Widget files for 4 people to look at?
# powershell
$salesorder = read-host -prompt 'What is the customer name and salesorder number? (ex.. turnkey - 3335)'
$jobnumber = read-host -prompt 'what is the Plant folder plus job number? (ex... 930-12345)'
$foldername = $jobnumber + " - " + $salesorder
#$conveyornumber = read-host -prompt "what is the number for conveyors? " + " - "
$priority = read-host -prompt "how many priorities are there?"
##************************* setting variables for second level basic Folder Structure *********************************
# Dunno what this file is or how it got here?
$partpath = '\\wal-file\public\sullivan\sully_temp_part.ipt'
$layout = 'D0100 - Layout'
$footprint = 'D0101 - Footprint'
$equipment = 'D01xx - Equipment' #Are these meant to be numbers or x character?
$Guarding = 'D85xx - Guarding'
$conveyor = 'D60xx - Conveyors'
$platform = 'D90xx - Platforms'
#*************************** creating new variables based on folder name stylings *************************************
$folderArray = #() # of things you want to keep track of
function CreateNewFolder() {
param(
$path = "C:\vault_workspace\Temp_vault\wendt\",
$name = $foldername,
[switch] $force
)
$newDirectory = new-item -path $path -name $name -itemtype 'directory' -force:$force
Write-Host "Adding $name to FolderArray"
$folderArray.Add($newDirectory)
return $newDirectory
}
$workdir = CreateNewFolder -path "C:\vault_workspace\Temp_vault\wendt\" -name $foldername -force
#$workdir = new-item -path "C:\vault_workspace\Temp_vault\wendt\" -name $foldername -itemtype 'directory' -force
$layoutdir = CreateNewFolder -path $workdir -name $layout
#$layoutdir = new-item -path $workdir -name $layout -itemtype 'directory'
$layoutfilename = $layoutdir -join '.ipt' # Why are we joining the directory to ipt?
#*************************** setting work directory input **************************************************************
new-item -path $layoutdir -name "$salesorder.ipt" -itemtype "file"
#$footprintdir = new-item -path $workdir -name $footprint -itemtype 'directory'
$footprintdir = CreateNewFolder -path $workdir -name $footprint
$conveyordir = new-item -path $workdir -name $conveyor -itemtype 'directory'
#looping statement to create multiple folders
$conveyorinput = read-host -prompt "how many conveyors need to be made?"
for ($i = 1; $i -le $conveyorinput; $i++){
# This just gets printed out?
"{0:D2}" -f $number
}
{
[system.io.directory]::CreateDirectory("$conveyordir\D51$I")
}
start-sleep -seconds 5
#creating multiple files
$conveyorarray = Get-ChildItem $conveyordir | Where-Object {
$_.PSChildname
} | Foreach-Object {
#{
Name = $_.Name
FullName = $_.FullName
}
}
foreach ($path in $conveyorarray) {
$name = $_.Name
$fullName = $_.Name
$destination = '{0}\{1}\{2}-4-{3}-Dummy-A0.ipt' -f $conveyordir, $name, $jobnumber, $path
copy-item -path $fullName -destination $destination # "$conveyordir\$path\$jobnumber-4-$path-DUmmy-A0.ipt "
}
so i actually changed the suyntax around completely but i was able to do the following
$salesorder = read-host -prompt 'What is the customer name and salesorder number? (ex.. turnkey - 3335)'
$jobnumber = read-host -prompt 'what is the Plant folder plus job number? (ex... 930-12345)'
$topleveldir = new-item -path "C:\vault_workspace\Temp_vault\wendt\" -name "M$jobnumber - $salesorder" -ItemType 'directory'
$subfolders = "D0100 - Layout", "D0101 - Footprint", "D01xx - Equipment","D85xx - Guarding", "D60xx - Conveyors", "D90xx - Platforms", "D09XX - Chutes"
foreach($subfolder in $subfolders){new-item -path "$topleveldir" -name $subfolder -type directory }
#$partpath = '\\wal-file\public\sullivan\sully_temp_part.ipt'
#p1
$p1conveyorinput = read-host -prompt "how many p1 conveyors need to be made?"
for ($i = 1; $i -le $p1conveyorinput; $i++) {
$p1c = "{0:D2}" -f $i
[system.io.directory]::CreateDirectory("$topleveldir\D60xx - Conveyors\D61$p1c-p1")
copy-item -path "\\wal-file\public\sullivan\sully_temp_part.ipt" -destination "$topleveldir\D60xx - Conveyors\D61$p1c-p1\D61$p1c-p1-dummy.ipt" -force
}
start-sleep -seconds 1
the only issue i run into is how to loop back into that last statement
#p1
$p1conveyorinput = read-host -prompt "how many p1 conveyors need to be made?"
for ($i = 1; $i -le $p1conveyorinput; $i++) {
$p1c = "{0:D2}" -f $i
[system.io.directory]::CreateDirectory("$topleveldir\D60xx - Conveyors\D61$p1c-p1")
copy-item -path "\\wal-file\public\sullivan\sully_temp_part.ipt" -destination "$topleveldir\D60xx - Conveyors\D61$p1c-p1\D61$p1c-p1-dummy.ipt" -force
}
start-sleep -seconds 1
for as many priorities there are without copying and changing the variables (which im going to do for now because it functions)

Powershell File database comparison with drive letter variable input [duplicate]

This question already has an answer here:
Pass object[] into a function in PowerShell
(1 answer)
Closed 4 years ago.
I'm building a tool that will scan my files and a friend's files. We will use this to make sure we have the same files in our databases. The script I have so far has a variable input issue. For some reason, the PowerShell script fails on my drive letter input. Anyone have any ideas?
Here is my script:
{
function Show-Menu {
param (
[string] $Title = "Andy's Manual Database Tool"
)
Clear-Host
Write-Host ""
Write-Host "================ $Title ================"
Write-Host ""
Write-Host -f Green "1. Andys Files listing"
Write-Host -f green "2. Reids files listing"
Write-Host -f Red "3. Dark Matter Testing"
Write-Host "4. Convert .txt to .csv"
Write-Host "5. Convert Blank File to .csv"
Write-Host "6. Convert .csv to .txt"
}
Function Body {
Show-Menu
Write-Host ""
$Input = Read-Host "Please make a selection"
if ($Input -eq "1") {
Clear-Host
$root = Read-Host -Prompt 'Specify the location of Database? Example format: C:\*'
$y = read-host -Prompt 'Input file types. Format Example: " .jpg,.mp4,.mp3,.pdf .... " Do * for all'
$z = Read-Host -Prompt 'Your Save file name will be? Examples: Movies database , Music database , audiobooks.'
Get-ChildItem -Path $root -File -Recurse *.$y | Select-Object -Property Name | Export-Csv -NoTypeInformation $z Andy.csv
}
if ($Input -eq "2") {
Clear-Host
$root = Read-Host -Prompt 'Specify the location of Database? Example format: C:\*'
$y = read-host -Prompt 'Input file types. File Format Examples: " .jpg,.mp4,.mp3,.pdf .... " Do * for all'
$z = Read-Host -Prompt 'Your Save file name will be? Examples: Movies database , Music database , audiobooks.'
Get-ChildItem -Path $root -File -Recurse *.$y | Select-Object -Property Name | Export-Csv -NoTypeInformation $z' From Reid.csv'
}
if ($Input -eq "3") { Get-Process | Stop-Process }
if ($Input -eq "4") {
Clear-Host
Get-ChildItem *.txt | rename-item -newname { $_.name -replace ".txt",".csv" }
}
if ($Input -eq "5") {
Clear-Host
Get-ChildItem * -Exclude *.ps1,*.CSV,*.TXT | rename-item -newname { "$($_.name).CSV" }
}
if ($Input -eq "6") {
Clear-Host
Get-ChildItem *.csv | rename-item -newname { $_.name -replace ".csv",".txt" }
}
Write-Host 'Complete! ^_^'
Start-Sleep -seconds 5
Body
}
Body
}
This issue is here, from the script above:
$root = Read-Host -Prompt 'Specify the location of Database? Example format: C:\*'
$y = read-host -Prompt 'Input file types. Format Example: " .jpg,.mp4,.mp3,.pdf .... " Do * for all'
$z = Read-Host -Prompt 'Your Save file name will be? Examples: Movies database , Music database , audiobooks.'
Get-ChildItem -Path $root -File -Recurse *.$y |
Select-Object -Property Name |
Export-Csv -NoTypeInformation $z Andy.csv
I'm using $root as an input for my drive letter or location path which is the problem.
There a few minor issues.
$z Andy.csv Needs to be changed to "$z Andy.csv". You will notice when you ran this before you would of received the following message:
Export-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value
"Andy.csv" to type "System.Char". Error: "String must be exactly one
character long."
Get-ChildItem -Path $root -File -Recurse *.$y Needs to be changed to Get-ChildItem -Path "$root" -Recurse -Include "*$y" - You are prompting the user to put in file extension with .<extension> (assigned to $y) then you are trying to filter with $y
Ex:$y = read-host -Prompt 'Input file types. Format Example: " .jpg,.mp4,.mp3,.pdf .... " Do * for all'
Issue: "*.$y" this would equal "..extension". Your results would then be 0 (unless you had a file with ..jpg or something like that)
Corrected:
if ($Input -eq "1") {
Clear-Host
$root = Read-Host -Prompt 'Specify the location of Database? Example format: C:\*'
$y = read-host -Prompt 'Input file types. Format Example: " .jpg,.mp4,.mp3,.pdf .... " Do * for all'
$z = Read-Host -Prompt 'Your Save file name will be? Examples: Movies database , Music database , audiobooks.'
Get-ChildItem -Path "$root" -Recurse -Include "*$y" | Select Name | Export-Csv -NoTypeInformation "$z Andy.csv"
}
You should be able to correct the rest of your script following the "Corrected" example.
EDIT:
Credit to TheIncredible1
There are automatic variables that should never be used other than for their intended purpose. In your case $Input:
Contains an enumerator that enumerates all input that is passed to a
function. The $input variable is available only to functions and
script blocks (which are unnamed functions). In the Process block of a
function, the $input variable enumerates the object that is currently
in the pipeline. When the Process block completes, there are no
objects left in the pipeline, so the $input variable enumerates an
empty collection. If the function does not have a Process block, then
in the End block, the $input variable enumerates the collection of all
input to the function.
However, in this case it should not effect your outcome. But, it is a very bad habit to get into and is best to be avoided.

Powershell array of list objects

I am trying to write a script which takes a text file of f5 LTM results and puts this into a searchable array so i can compare results from yesterday to today.
This is an example of the file;
MemberCount : 2
Name : /Common/blah1
Availability : AVAILABILITY_STATUS_GREEN
Enabled : ENABLED_STATUS_ENABLED
Status : The pool is available
MemberCount : 2
Name : /Common/blah2
Availability : AVAILABILITY_STATUS_GREEN
Enabled : ENABLED_STATUS_ENABLED
Status : The pool is available
So ideally I would like to make Name the unique field and the sort the list so i can compare the changes in status from yesterday to today.
Here is the code I am working on to email the results but it only provides line by line difference where I would rather get the object changes in the email.
Add-PSSnapIn iControlSnapIn
$f5_hosts = '192.168.x.x', '192.168.x.x'
$uid = 'xx'
$pwd ='xx'
foreach($f5_host in $f5_hosts){
$f5_host_out = $(get-date -f yyyyMMdd)+"_"+$f5_host+".txt"
$f5_host_out_yesterday = $((get-date).AddDays(-1).ToString('yyyyMMdd'))+"_"+$f5_host+".txt"
#Check login details and generate LTM output file for $f5_host
Initialize-F5.iControl -HostName $f5_host -Username $uid -password $pwd
Get-F5.LTMPool | out-file $f5_host_out
#// Check if EMP file for yesterday exists and send results else send error
if (Test-Path $f5_host_out_yesterday){
$f5_host_Result = compare-object -ReferenceObject (Get-Content $f5_host_out) -DifferenceObject (Get-Content $f5_host_out_yesterday )
$f5_host_out_yesterday+": file is Present!"
$Text_Body = $f5_host+": difference `r`n"
$Text_Body += ($f5_host_Result | out-string)
Send-MailMessage -to simon.thomason#racq.com.au -from simon.thomason#racq.com.au -subject $f5_host+": F5 Daily LTM Check" -body $Text_Body -smtpserver mailrelay.racqgroup.local
}else{
$f5_host_out_yesterday+": is not file is Present!"
Send-MailMessage -to simon.thomason#racq.com.au -from simon.thomason#racq.com.au -subject $f5_host+": Check failed" -body "Yesterday's file is not present" -smtpserver mailrelay.racqgroup.local
}
}
#Limit File retention to 30days.
$limit = (Get-Date).AddDays(-30)
#Get script location
$path = Get-Location
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
So as an output I would just want to see something like this in a email
Difference From yesterday to today
Yesterday
MemberCount : 2
Name : /Common/blah1
Availability : AVAILABILITY_STATUS_GREEN
Enabled : ENABLED_STATUS_ENABLED
Status : The pool is available
Today
MemberCount : 2
Name : /Common/blah1
Availability : AVAILABILITY_STATUS_RED
Enabled : ENABLED_STATUS_ENABLED
Status : The pool is available
Ok, on your second question, exporting and importing passwords, the encryption is done per user (and I'm pretty sure per machine), so you can't export it, and then have another account import it, but for just straight saving an encrypted password you can use these functions:
Function Out-EncryptedPasswordFile{
[cmdletbinding()]
Param(
[Parameter(Mandatory = $true)]
[string]$Password,
[Parameter(Mandatory = $true)]
[ValidateScript({If(Test-Path (Split-Path $_)){$true}else{Throw "Unable to create file, directory '$(Split-Path $_)\' does not exist."} })][String]$Path
)
ConvertTo-SecureString -AsPlainText $Password -Force | ConvertFrom-SecureString | Set-Content $Path -Encoding Unicode
}
#Usage Example
#Out-EncryptedPasswordFile TestP#ssw0rd c:\temp\password.txt
Function Import-EncryptedPasswordFile{
[cmdletbinding()]
Param(
[Parameter(Mandatory = $true)]
[ValidateScript({Test-Path $_})][string]$Path
)
$SSPassword = Get-Content $Path | ConvertTo-SecureString
$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($SSPassword)
[System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
}
#Usage Example
#Import-EncryptedPasswordFile C:\temp\password.txt
not certain if right or wrong but this gave the result I was looking for. json was just used so I could store the object and convert it back to powershell object.
Add-PSSnapIn iControlSnapIn
$f5_hosts = 'x.x.x.x', 'x.x.x.x'
$uid = 'xx'
$pwd ='xx'
foreach($f5_host in $f5_hosts){
$f5_host_out = $(get-date -f yyyyMMdd)+"_"+$f5_host+".json"
$f5_host_out_yesterday = $((get-date).AddDays(-1).ToString('yyyyMMdd'))+"_"+$f5_host+".json"
#Check login details and generate LTM output file for $f5_host
Initialize-F5.iControl -HostName $f5_host -Username $uid -password $pwd
Get-F5.LTMPool | ConvertTo-Json | out-file $f5_host_out
#// Check if EMP file for yesterday exists and send results else send error
if (Test-Path $f5_host_out_yesterday){
$f5_host_json_today = Get-Content -Raw $f5_host_out | ConvertFrom-Json
$f5_host_json_yesterday = Get-Content -Raw $f5_host_out_yesterday | ConvertFrom-Json
$f5_host_Result = Compare-Object -ReferenceObject ($f5_host_json_today | Sort-Object ) -DifferenceObject ($f5_host_json_yesterday | Sort-Object ) -property MemberCount, Name, Status, Availability, Enabled, Status | sort-object -property Name
#$f5_host_Result
$f5_host_out_yesterday+": file is Present!"
$Text_Body = $f5_host+": difference `r`n"
$Text_Body += ($f5_host_Result | out-string)
Send-MailMessage -to y#x -from y#x -subject $f5_host+": F5 Daily LTM Check" -body $Text_Body -smtpserver blah
}else{
$f5_host_out_yesterday+": is not file is Present!"
Send-MailMessage -to y#x -from y#x -subject $f5_host+": Check failed" -body "Yesterday's file is not present" -smtpserver blah
}
}
#Limit File retention to 30days.
$limit = (Get-Date).AddDays(-30)
#Get script location
$path = Get-Location
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

How to exit powershell invoked from psexec

I am trying to call a powershell script using psexec which connects to remote system
So from "Computer A" I call the batch file Aot.bat which is on "Computer B"
Aot.bat has a line which calls the powershell
powershell.exe %SystemRoot%\system32\aot.ps1 -ComputerName AotServ01 >>\Aot01\AOtShared\Yuma.txt;exit
I can see that the connection is made and powershell runs, but then it does not exit
So please advise what can be done or added
Aot.ps1 reads the Memory and CPU at the present Moment
[cmdletbinding()]
[cmdletbinding()]
param(
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName = $env:computername)
begin {
Get-Module –ListAvailable | import-module
Add-PSSnapin Citrix*
Set-executionpolicy -scope currentuser -executionpolicy unrestricted
$date = Get-Date -Format yyyMMdd
$Zip = "\\na02\KCRC\IRD_KFLOWRPT\Citrix_" + $date + "\Citrix_" + $date + ".txt"
$time = Get-Date -format F
}
process
{
foreach($Computer in $Computername)
{
$free = ( Get-WMIObject Win32_OperatingSystem -ComputerName $computer ).FreePhysicalMemory
$phys = ( Get-WMIObject Win32_OperatingSystem -ComputerName $computer ).TotalVisibleMemorySize
$Percentage = (($phys-$free)/$Phys) * 100
$proc =get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2
$cpu=($proc.readings -split ":")[-1]
write-host "`r`n*********************************************************************************"
write-host "`r`nComputer: " $computer
write-host "`r`n_________________________________________________________________________________"
write-host "`r`nPercentage Memory user Used: " $Percentage
write-host "`r`n"
write-host "`r`nPercentage CPU Used: " $cpu
write-host "`r`n_________________________________________________________________________________"
write-host "`r`n"
write-host $time
}
}
end
{
write-host "`r`n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
write-host "`r`n END OF FILE "
write-host "`r`n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
}
===============================================================================

Resources