-
Notifications
You must be signed in to change notification settings - Fork 0
Classes
neztach edited this page Aug 31, 2023
·
2 revisions
| Code | Explanation |
class Person { |
|
[string] $FirstName |
Define a class property as a string |
[string] $LastName = 'Sullivan' |
Define a class property with a default value |
[int] $Age |
Define a class property as an integer |
Person() { |
Add a default constructor (no input parameters) for a class |
} |
|
Person([string] $FirstName) { |
Define a class constructor with a single string parameter |
$this.FirstName = $FirstName
} |
|
[string] FullName() {
return '{0} {1}' -f $this.FirstName, $this.LastName
}
} |
|
class Person {
[string] $FirstName
[string] $LastName = 'Sullivan'
[int] $Age
Person() {
}
Person([string] $FirstName) {
$this.FirstName = $FirstName
}
[string] FullName() {
return '{0} {1}' -f $this.FirstName, $this.LastName
}
} |
Full Class |
$Person01 = [Person]::new() |
Instantiate a new Person object. |
$Person01.FirstName = 'Trevor' |
Set the FirstName property on the Person object. |
$Person01.FullName() |
Call the FullName() method on the Person object. Returns 'Trevor Sullivan' |
class Server { |
Define a "Server" class, to manage remote servers. Customize this based on your needs. |
[string] $Name |
|
[System.Net.IPAddress] $IPAddress |
Define a class property as an IPaddress object |
[string] $SSHKey = "$HOME/.ssh/id_rsa" |
Set the path to the private key used to authenticate to the server |
[string] $Username |
Set the username to login to the remote server with |
RunCommand([string] $Command) { |
Define a method to call a command on the remote server, via SSH |
ssh -i $this.SSHKey $this.Username@$this.Name $this.Command
}
} |
|
class Server {
[string] $Name
[System.Net.IPAddress] $IPAddress
[string] $SSHKey = "$HOME/.ssh/id_rsa"
[string] $Username
RunCommand([string] $Command) {
ssh -i $this.SSHKey $this.Username@$this.Name $this.Command
}
} |
Full class |
$Server01 = [Server]::new() |
Instantiate the Server class as a new object |
$Server01.Name = 'webserver01.local' |
Set the "name" of the remote server |
$Server01.Username = 'root' |
Set the username property of the "Server" object |
$Server01.RunCommand("hostname") |
Run a command on the remote server |
neztach - PowerShell Public repo