While reading data is usually fine, PowerShell is also a great automation engine that's able to change a system configuration. We'll explore a couple of cmdlets that will, in some form, change your system configuration.
Introducing change to systems
Getting ready
In order to follow this recipe, you should have completed the installation of PowerShell Core for your operating system. You should prepare a virtual machine for testing purposes since the cmdlets used in this recipe will inadvertently change your system configuration.
How to do it...
Please perform the following steps:
- Review the output of Get-Command -Verb New,Set,Remove,Register,Unregister,Start,Stop to review some of the more frequently used cmdlets.
- Execute $file = New-TemporaryFile to create a temporary file.
- Use 'SomeContent' | Set-Content -Path $file to change the file contents.
- Use 'More content!' | Add-Content -Path $file to append data to the file.
- Review the contents with $file | Get-Item | Get-Content -Path.
- Lastly use $file | Remove-Item -Verbose to get rid of the file again.
- Use $ping = Start-Process -FilePath ping -ArgumentList 'packtpub.com' -PassThru.
- Use $ping | Stop-Process -PassThru to stop the background process.
- Use Start-Job -Name Sleepy { Start-Sleep -Seconds 100; Get-Date}.
- Have a look at the job with Get-Job -Name Sleepy—is it ready to deliver the data?
- Use Get-Job -Name Sleepy | Wait-Job to wait for the results.
- Lastly, use Get-Job -Name Sleepy | Receive-Job -Keep to gather the results.
- As an alternative, try $job = Get-ChildItem -Recurse -Force -Path $home & and $job | Wait-Job | Receive-Job.
- Clean up any remaining jobs by closing PowerShell or executing $job | Remove-Job; Get-Job -Name Sleepy | Remove-Job.
How it works...
There're many verbs in PowerShell that indicate changes such as New, Set, and Remove. Many of those cmdlets also return objects for the data that's altered or created. If one of those parameters doesn't provide output such as Stop-Process, you can try using the PassThru parameter if it is available. It usually means that objects will be returned.
In the recipe, you can see the usual flow between different cmdlets. The file can be created, modified, and removed using the pipeline and cmdlets related to each other. In Chapter 2, Reading and Writing Output, we'll see how pipeline input is usually processed.
With the new parameter, &, you can start a background job, much like the forking parameter on Linux. The job results can be collected later as well.
There's more...
There're countless cmdlets that change a running system, some of which we will see in this book. Be sure to have a look at the PowerShell repository on GitHub and the documentation on https://docs.microsoft.com/en-us/ to get all available information before ruining your weekend or your colleague's on-call shift.
See also
- The official documentation: https://docs.microsoft.com/powershell
- The official code: https://github.com/powershell/powershell