The PowerShell `CRUD` operations explained
Tags: webdev, beginners, powershell
Published: 2022-11-30 18:18:20

## Table of Contents

- [Overview](#overview)
- [Create](#create)
- [Read](#read)
- [Update](#update)
- [Delete](#delete)
- [Conclusion](#conclusion)
- [Resources](#resources)

## Overview

In programming, CRUD is an acronym that stands for CREATE, READ, UPDATE, and DELETE. These are the major operations which are performed by databases.

In this article, we will be looking at how we can implement the basic command line operations (creating or deleting files/folders) in PowerShell using the `CRUD` concept.

**CRUD** - Create, Read, Update, Delete

Before we begin, in the following tables, you will see 4 columns:

| Alias | Alternatives | Command        | Description      |
| ----- | ------------ | -------------- | ---------------- |
| `cd`  | `chdir`      | `Set-Location` | Change directory |

which means:

- **Alias** - a shorter version of the command
- **Alternatives** - alternative versions to alias
- **Command** - the full command
- **Description** - a brief description of what the command does

With that out of the way, let's get started!

## Create

| Alias | Alternatives | Command    | Description        |
| ----- | ------------ | ---------- | ------------------ |
| `ni`  | -            | `New-Item` | Create a file      |
| `md`  | `mkdir`      | `New-Item` | Create a directory |

Officially, the `New-Item` command is used to create both a file or a directory. That said, as a lazy programmer, `ni` and `md` are my go-to commands for doing the same, but faster.

When you need to create a file/folder in the _current directory_, use a dot `(.)` as the path, or don't specify the `-Path` parameter at all.

```powershell
# short version
C:\> ni "test.txt"

# long version
C:\> New-Item -Path . -Name "test.txt" -ItemType "file"
```

If you want to go with the `New-Item` method, you need to specify the `-Path`, `-Name`, and `-ItemType` parameters. Note that the `-ItemType` accepts 2 values: `file` and `directory`.

```powershell
C:\> New-Item -Path "C:\root\Documents" -Name "fileName.txt | folderName" -ItemType "file | directory"
```

## Read

| Alias   | Alternatives | Command         | Description            |
| ------- | ------------ | --------------- | ---------------------- |
| `ii`    | `iex`        | `Invoke-Item`   | Open a file/folder     |
| `start` | `saps`       | `Start-Process` | Open a file/folder     |
| `ls`    | `gci`, `dir` | `Get-ChildItem` | List files and folders |
| `cat`   | -            | `Get-Content`   | Read a file            |

### Invoke-Item vs Start-Process

While the both commands act almost the same, there is a slight difference between them.

- `Invoke-Item` - performs the default action specified by the file type
- `Start-Process` - opens the executable file with the default application

Basically, you will use the `Invoke-Item` command to open a file, and the `Start-Process` to run a command. However, if you want to dive deeper into each command, you can read the following articles:

- [Invoke-Item](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/invoke-item?view=powershell-7.1)
- [Start-Process](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.1)

A quick example of how to use them:

```powershell
# Invoke-Item
C:\> ii "test.txt"

# Start-Process
C:\> start "test.exe"
```

If you try to change the extension of the file, you will see that the command will still work, becuase of either the default action or the default application specified.

```powershell
# Invoke-Item
C:\> ii "test.exe"

# Start-Process
C:\> start "test.txt"
```

### Get-ChildItem

The `Get-ChildItem` (or `ls`) command is used to list all the files and folders in the current directory. You can also provide a path to the `-Path` parameter to list the files and folders in a different directory.

```powershell
C:\> ls

    Directory: C:\root

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         1/1/2021   1:00 AM              14 test.txt
```

### Get-Content

The `Get-Content` command is used to read a file and show what's inside.

```powershell
C:\> cat "C:\root\test.txt"
Hello, World!
```

## Update

| Alias | Alternatives    | Command        | Description              |
| ----- | --------------- | -------------- | ------------------------ |
| `cd`  | `chdir`         | `Set-Location` | Change directory         |
| `ren` | `rename`, `rni` | `Rename-Item`  | Rename files and folders |
| `cp`  | -               | `Copy-Item`    | Copy files and folders   |
| `mv`  | `mi`, `move`    | `Move-Item`    | Move files and folders   |

### `cd`

For me, the `cd` is the most used command. It's used to move between directories.

- to go back to parent directory, use `cd ..`
- to go to the root directory, use `cd \` or `cd /`
- to go to a specific directory, use `cd "C:\path\"`
- to go to the D drive, use `D:` or `cd D:`
- to go to the current directory, use `cd .` (I don't know why you would want to do that even though you are already there).

```powershell
C:\> cd "root"
C:\root> cd "Documents"
C:\root\Documents> cd ..
C:\root> D:
D:\> cd "projects"
D:\projects> cd C:
C:\root>
```

Notice that when you move to the D drive while being in the `C:\root\` directory and come back to the C drive, you will be still in the previous directory you were in (`C:\root\`), not in the root directory (`C:\`). Because when moving to another drive, the current directory in the previous drive will be saved, which can come very handy in most cases.

### `ren`

The `ren` or `Rename-Item` command, as you might have guessed, is used to rename a file or a folder. You can also use the `rename` or `rni` aliases.

THe `ren` command takes 2 parameters: `-Path` and `-NewName`. You can either use them or omit them and just provide the path and the new name.

```powershell
# long version
C:\> ren -Path "C:\root\old.txt" -NewName "next.txt"

# short version
C:\> ren "C:\root\old.txt" "next.txt"
```

### `cp` and `mv`

The `cp` and `mv` commands are used to copy and move files and folders. They both take 2 parameters: `-Path` and `-Destination`.

```powershell
C:\> cp -Path "C:\root\old.txt" -Destination "C:\root\new.txt"
C:\> mv -Path "C:\root\old.txt" -Destination "C:\root\new.txt"
```

Just like the `ren` command, you can omit the `-Path` and `-Destination` parameters.

```powershell
C:\> cp "old.txt" "new.txt"
C:\> mv "old.txt" "new.txt"
```

> **Note:** When moving a file and providing the new file name instead of folder name, the file will be renamed. It is true for the `cp` command as well.

## Delete

| Alias   | Alternatives         | Command       | Description                 |
| ------- | -------------------- | ------------- | --------------------------- |
| `rm`    | `del`, `erase`, `ri` | `Remove-Item` | Remove files and folders    |
| `rmdir` | -                    | `Remove-Item` | Remove a directory          |
| `cli`   | `clc`                | `Clear-Item`  | Clear the content of a file |

### `rm`

The `rm` command is used to delete many different types of items, including files, folders, registry keys, variables, aliases, and functions.

Let's see some examples:

Delete everything in the directory:

```powershell
C:\> rm "C:\root\examples\*"
```

Delete only files with an extension name `.txt`:

```powershell
C:\> rm "C:\root\examples\*.txt"
```

Delete everything except the `.txt` files:

```powershell
C:\> rm "C:\root\examples\*.*" -Exclude "*.txt"
```

There are many more cool examples which you can find in the [official documentation](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-item?view=powershell-7.1).

### `cli`

The `cli` command clears the content of a file. It won't delete the file, but rather remove everything inside of it.

```powershell
# get the content
C:\> cat "C:\root\test.txt"
Hello, World!

# clear the content
C:\> cli "C:\root\test.txt"

# get the content again
C:\> cat "C:\root\test.txt"
C:\>
```

## Conclusion

In this article, we have covered the essential basic commands with the CRUD concept in mind. I hope you have learned something new and useful. If you have any questions or suggestions, feel free to leave a comment below. Thanks for reading!

## Resources

- [PowerShell Documentation](https://docs.microsoft.com/en-us/powershell/)
- [Table of Basic PowerShell Commands](https://devblogs.microsoft.com/scripting/table-of-basic-powershell-commands/)