Questions tagged [powershell]

PowerShell is a cross-platform command line and scripting utility from Microsoft. Use this tag for questions about writing and executing PowerShell scripts ONLY. Programming questions specific to the cross-platform version PowerShell Core (Windows, macOS, and Linux) should be tagged [powershell-core]. Questions about system administration should be asked on Super User or Server Fault.

Questions about Windows administration tasks involving PowerShell should be asked on Super User or Server Fault. On-topic questions are for writing scripts ONLY

Windows PowerShell

is an interactive shell and scripting language originally included with Microsoft Windows 7 and Microsoft Windows Server 2008 R2 and above. It includes a command-line shell (Windows PowerShell) for interactive use, an underlying scripting environment to run scripts away from the command-line and a GUI script editing / debugging environment (Windows PowerShell ISE). See: Getting Started with Windows PowerShell.

As a language, has syntax for literal arrays and hashtables, support for regexes, pattern matching, and string expansion. It's built on the .NET framework so it has Unicode support, can be locale/culture aware, and can access .NET framework methods directly.

As a command-line shell, it is designed around cmdlets named in the form {Verb}-{Noun}, intending that the same kinds of commands work across many domains. E.g. Get-Date returns the current date, and Get-Process returns an array of objects representing running processes which can be piped to other commands that work with process objects. Many commands and keywords have short aliases to reduce typing.

As a system management environment, Windows components and Microsoft products have been extended to provide native PowerShell interfaces as part of creating a unified managing system for Windows systems, including:

Third-party vendors also offer PowerShell integration, including:

takes the Unix idea of piping text between programs and manipulating text, and enhances it by piping .NET object instances around. Because objects carry type information (e.g. dates and times), and complex state (e.g. properties and methods, hashtables, parsed XML data, and live network sockets) this makes many tasks easy that would be difficult or impractical to do by passing text between programs.

Along with interacting with the PowerShell console or the PowerShell ISE, there are also several third-party IDE options including Sapien's PrimalScript ISE.

Example Usage

# List all processes using > 100 MB of PagedMemory in descending sort order (v3_
C:\PS> Get-Process | Where PagedMemorySize -GT 100MB | Sort -Descending

# PowerShell can handle numbers and arithmetic
C:\PS> (98.6 - 32) * 5/9
37

# Production orientation allows experimentation and confirmation
C:\PS> Get-ChildItem C:\Users\John *.bak -r |
           Where {$_.LastWriteTime -gt (Get-Date).AddDays(-7)} |
           Remove-Item -WhatIf
What if: Performing operation "Remove File" on Target "C:\Users\John\foo.bak"

C:\PS> Get-Process iexp* | Stop-Process -Confirm

Confirm
Are you sure you want to perform this action?
Performing operation "Stop-Process" on Target "iexplore (7116)".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is Y):

Common Gotchas

Executing EXE files via a path with spaces requires quoting the path and the use of the call operator - &

C:\PS> & 'C:\Program Files\Windows NT\Accessories\wordpad.exe'

Calling PowerShell functions does not require parenthesis or comma separated arguments. PowerShell functions should be called just like a cmdlet. The following examples demonstrates the problem caused by this issue e.g.:

C:\PS> function Greet($fname, $lname) {"My name is '$lname', '$fname' '$lname'"}
C:\PS> Greet('James','Bond') # Wrong way to invoke this function!!
My name is '', 'James Bond' ''

Note that both 'James' and 'Bond' are packaged up as a single argument (an array) that is passed to the first parameter. The correct invocation is:

C:\PS> Greet James Bond
My name is 'Bond', 'James' 'Bond'

Note that in PowerShell 2.0, the use of Set-StrictMode -version 2.0 will catch this type of problem.

PowerShell Profiles

Another common issue when moving files from a user machine into a production environment is the profile setting discrepancy. A user's machine might have a profile.ps1 defined inside this folder

%UserProfile%\Documents\WindowsPowerShell

The profile file is used to define certain commands are automatically executed prior to running a script. Common commands might include adding a PowerShell snap-in. To minimize this type of confusion between environments, it is recommended to run tests with the PowerShell command line via the -NoProfile flag. This will ensure the profile script is not executed.

More information on profiles can be found here.

Extensible functionalities

One of the great features of PowerShell is its extensibility: we can add functionality by importing modules which are a package of cmdlets, functions, and aliases specialized on a particular domain (such as database administration, virtual machine administration, etc.).

Here are the most commonly used modules by the community:

  • PSReadLine PSReadLine replaces the command line editing experience in PowerShell.exe "PSReadLine replaces the command line editing experience in PowerShell.exe for versions 3 and up." Included in Windows 10.

  • Powertab "PowerTab offers enhanced tab expansion for PowerShell."

  • PSCX "PowerShell Community Extensions (PSCX) is aimed at providing a widely useful set of additional cmdlets, providers, aliases, filters, functions, and scripts for Windows PowerShell that members of the community have expressed interest in but haven't been added to PowerShell yet."

PowerShell Core

Since 2016, an open-source and cross-platform (Windows, macOS, and Linux) version of PowerShell has been in alpha and then beta state. Achieving general availability in 2018, PowerShell Core is built on the .NET Core Framework. Questions about functionality specific to PowerShell Core should be tagged .

Resources

114499 questions
20
votes
5 answers

Powershell select-object skip multiple lines?

Can i skip multiple lines with the -skip option? gc d:\testfile.txt | select -skip 3 works but what to do if i want to delet line 3-7 ??
icnivad
  • 2,231
  • 8
  • 29
  • 35
20
votes
3 answers

Powershell config assembly redirect

I have a custom .NET assembly with some powershell cmdlets than I use for common domain related tasks. I've just created a new cmdlet that references a 3rd party library that has a reference to Newtonsoft.Json 4.5.0.0. However one of my other…
user303754
  • 459
  • 3
  • 11
20
votes
9 answers

Reverse elements via pipeline

Is there a function that reverses elements passed via pipeline? E.g.: PS C:\> 10, 20, 30 | Reverse 30 20 10
dharmatech
  • 8,979
  • 8
  • 42
  • 88
20
votes
1 answer

Powershell ConvertTo-JSON missing nested level

It looks like Powershell cuts off data when exporting to JSON if it nests too deep. My object hierchy looks like this: Main Object Metadata More Metadata Collection of Other object Sources Collection of data used by these…
nlowe
  • 999
  • 4
  • 11
  • 26
20
votes
3 answers

Convert seconds to hh:mm:ss,fff format in PowerShell

I have a string representing a time in seconds and milliseconds. I want to convert it to a string in the format "hh:mm:ss,fff". My solution still has the flaw that hours less than 10 are shown with one decimal instead of two: PS> $secs =…
nixda
  • 2,654
  • 12
  • 49
  • 82
20
votes
4 answers

Determine XML Node Exists

This is probably simple, but I'm trying to determine if a node exists in an XML document. I thought I found an answer in this post, How to check whether a node exists or not using powershell without getting exception?, but I didn't get it to work.…
mack
  • 2,715
  • 8
  • 40
  • 68
20
votes
7 answers

Download URL content using PowerShell

I am working in a script, where I am able to browse the web content or the 'url' but I am not able to copy the web content in it & download as a file. This is what I have made so far: $url =…
Arindam
  • 201
  • 1
  • 3
  • 5
20
votes
5 answers

Read Excel sheet in Powershell

The below script reads the sheet names of an Excel document.... How could I improve it so it could extract all the contents of column B (starting from row 5 - so row 1-4 are ignored) in each worksheet and create an object? E.g. if column B in…
methuselah
  • 12,766
  • 47
  • 165
  • 315
20
votes
5 answers

Powershell. Create a class file to hold Custom Objects?

I use Powershell's custom-object command to hold data points. Custom-object creates just one object and assigns a variable to it. Can Powershell go one step further and create new classes from which objects can be made? In the examples below, I…
Bagheera
  • 1,358
  • 4
  • 22
  • 35
20
votes
2 answers

Powershell Select-String -pattern -notMatch

I have lines - echo $LocalAdmins Administrator Domain-Administrator daemon SomeUser Line 1-3 should be same although there could be situation where Domain-Administrator doesn't exist so simply counting lines won't help because User…
Phoneutria
  • 351
  • 4
  • 9
  • 17
20
votes
5 answers

Powershell Remoting with credential

While running remoting commands like Enable-PsSession, Invoke-command etc. we need to provide credentials with those commands. I don't want to provide the credentials every time while executing these command. Also lets say I stored the username in…
usr021986
  • 3,421
  • 14
  • 53
  • 64
20
votes
3 answers

Accessing values of object properties in PowerShell

I'm going through an array of objects and I can display the objects fine. $obj displays each object in my foreach loop fine. I'm trying to access the object fields and their values. This code also works fine: $obj.psobject.properties To just see…
starcodex
  • 2,198
  • 4
  • 22
  • 34
20
votes
4 answers

Selecting attributes in xml using xpath in powershell

I am trying to use powershell and XPath to select the name attribute shown in the below xml example. $xml_peoples= $file.SelectNodes("//people") foreach ($person in $xml_peoples){ echo $person.attributes #echo…
user1044585
  • 493
  • 2
  • 5
  • 19
20
votes
4 answers

ConvertFrom-Json max length

I have a problem using PowerShell v3 when converting JSON strings over 2MB in size. The default limit in JSON serializer used by PowerShell is set to 2MB which explains the error. However when I deserialize object using ConvertFrom-Json on a…
Jammes
  • 291
  • 1
  • 4
  • 8
20
votes
5 answers

PowerShell get a list of network machines

I want to write a PS script, that would go through all machines it can find on a local network, take a look at "SomeDirectory" and if a file there exists, overwrite it with a new version for a UNC path.. The First problem is getting a list of PC's…
Marty
  • 3,485
  • 8
  • 38
  • 69
1 2 3
99
100