summaryrefslogtreecommitdiff
path: root/content/posts/basic-tasks-to-get-you-started-automating-with-powershell.md
blob: 932accc0d397c680bbf1608e13e8abae2c9fc288 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
---
title: "Basic tasks to get you started automating with Powershell"
date: 2024-04-05T22:00:00+02:00
tags: ['Powershell']
draft: true
---

Here are 10 common tasks that you will need to master when automating in Powershell (or any language for that matter).

## 1. Reading and writing files

```powershell
# Let's write something to a file
PS> "Hello, World!" | Out-File -FilePath myfile.txt

# Read contents of file
PS> Get-Content -Path myfile.txt
Hello, World!

# Shorthand
PS> gc myfile.txt
Hello, World!
```

## 2. Working with data

### Convert Powershell object to JSON

```powershell
PS> $myobj = [PSCustomObject]@{
> Name = "dotpwsh"
> Homepage = "https://dotpwsh.com"
> Twitter = "@moiaune"
> }
PS> $myobj | ConvertTo-Json
{
  "Name": "dotpwsh",
  "Homepage": "https://dotpwsh.com",
  "Twitter": "@moiaune"
}
```

### Convert JSON string to Powershell object

```powershell
PS> $jsonData = @"
> {
>   "Name": "dotpwsh",
>   "Homepage": "https://dotpwsh.com",
>   "Youtube": "https://youtube.com/@moiaune"
> }
> "@
PS> $jsonData
{
  "Name": "dotpwsh",
  "Homepage": "https://dotpwsh.com",
  "Youtube": "https://youtube.com/@moiaune"
}
PS> $jsonData | ConvertFrom-Json

Name    Homepage            Youtube
----    --------            -------
dotpwsh https://dotpwsh.com https://youtube.com/@moiaune

```

### Convert CSV string to Powershell object

```powershell
PS> $csvData = @"
> name,homepage,twitter
> dotpwsh,https://dotpwsh.com,@moiaune
> "@
PS> $csvData
name,homepage,twitter
dotpwsh,https://dotpwsh.com,@moiaune
PS> $csvData | ConvertFrom-Csv

name    homepage            twitter
----    --------            -------
dotpwsh https://dotpwsh.com @moiaune
```

### Convert Powershell object to CSV

```powershell
PS> $myobj = [PSCustomObject]@{
> Name = "dotpwsh"
> Homepage = "https://dotpwsh.com"
> Twitter = "@moiaune"
> }
PS> $myobj | ConvertTo-Csv
"Name","Homepage","Twitter"
"dotpwsh","https://dotpwsh.com","@moiaune"
```


## 3. Interacting with REST API's


## 4. Archiving and extracting files


## 5. Working with Regular Expresions