EzDevInfo.com

powershell interview questions

Top powershell frequently asked interview questions

Equivalent of *Nix 'which' command in Powershell?

Does anyone know how to ask powershell where something is?
For instance "which notepad" and it returns the directory where the notepad.exe is run from according to the current paths.


Source: (StackOverflow)

How to pass an argument to a PowerShell script?

There's a PowerShell script named itunesForward.ps1 that makes the iTunes fast forward 30 seconds:

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + 30
}

It is executed with prompt line command:

powershell.exe itunesForward.ps1

Is it possible to pass an argument from the command line and have it applied in the script instead of hardcoded 30 seconds value?


Source: (StackOverflow)

Advertisements

Terminating a script in PowerShell

I've been looking for a way to terminate a PowerShell (PS1) script when an unrecoverable error occurs within a function. For example:

function foo() {
    # Do stuff that causes an error
    $host.Exit()
}

Of course there's no such thing as $host.Exit(). There is $host.SetShouldExit(), but this actually closes the console window, which is not what I want. What I need is something equivalent to Python's sys.exit() that will simply stop execution of the current script without further adieu.

Edit: Yeah, it's just exit. Duh.


Source: (StackOverflow)

Determine installed PowerShell version

How can I determine what version of PowerShell is installed on a computer, and indeed if it is installed at all?


Source: (StackOverflow)

How do you comment out code in PowerShell?

How do you comment out code in PowerShell (1.0 or 2.0)?


Source: (StackOverflow)

Setting Windows PowerShell path variable

So I have found out that setting the PATH environment variable affects only the old command prompt. PowerShell seems to have different environment settings. How do I change the environment variables for PowerShell (v1)?

Note:

I want to make my changes permanent, so I don't have to set it every time I run PowerShell. Does PowerShell have a profile file? Something like Bash profile on Unix?


Source: (StackOverflow)

powershell 2.0 try catch how to access the exception

This is the try catch in PowerShell 2.0

$urls = "http://www.google.com", "http://none.greenjump.nl", "http://www.nu.nl"
$wc = New-Object System.Net.WebClient 

foreach($url in $urls)
{
    try
    {
        $url
        $result=$wc.DownloadString($url)
    }
    catch [System.Net.WebException]
    {
        [void]$fails.Add("url webfailed $url")
    }  
}

but what I want to do is something like in c#

catch( WebException ex)
{
    Log(ex.ToString());
}

Is this possible?


Source: (StackOverflow)

How can I check if a string is null or empty in PowerShell?

Is there a built-in IsNullOrEmpty-like function in order to check if a string is null or empty, in PowerShell?

I could not find it so far and if there is a built-in way, I do not want to write a function for this.


Source: (StackOverflow)

Unix tail equivalent command in Windows Powershell

I have to look at the last few lines of a large file (typical size is 500MB-2GB). I am looking for a equivalent of Unix command tail for Windows Powershell. A few alternatives available on are,

http://tailforwin32.sourceforge.net/

and

Get-Content [filename] | Select-Object -Last 10

For me, it is not allowed to use the first alternative, and the second alternative is slow. Does anyone know of an efficient implementation of tail for PowerShell.


Source: (StackOverflow)

How to get current username in Windows Powershell?

How to get the current username in Windows Powershell?


Source: (StackOverflow)

How to run an EXE file in PowerShell with parameters with spaces and quotes

How do you run the following command in PowerShell?

C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"


Source: (StackOverflow)

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

I have a .ps1 file in which I want to define custom functions.

Imagine the file is called MyFunctions.ps1, and the content is as follows:

Write-Host "Installing functions"
function A1
{
    Write-Host "A1 is running!"
}
Write-Host "Done"

To run this script and theoretically register the A1 function, I navigate to the folder in which the .ps1 file resides and run the file:

.\MyFunctions.ps1

This outputs:

Installing functions
Done

Yet, when I try to call A1, I simply get the error stating that there is no command/function by that name:

The term 'A1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling
 of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:3
+ A1 <<<<
    + CategoryInfo          : ObjectNotFound: (A1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I must misunderstand some PowerShell concepts. Can I not define functions in script files?

Note that I have already set my execution policy to 'RemoteSigned'. And I know to run .ps1 files using a dot in front of the file name: .\myFile.ps1


Source: (StackOverflow)

How to concatenate strings and variables in PowerShell?

Suppose the following snippet:

$name = "Slim Shady"
Write-Host "My name is " + $name

I'd expect this snippet to show:

My name is Slim Shady

But instead it shows:

My name is + Slim Shady

Which makes me think the + operator isn't appropriate for concatenating strings and variables.

The above is a contrived example. In my actual case there is a variable $assoc with properties Id, Name, and Owner that I'd like to be part of the string.

How should you approach this with PowerShell?


Source: (StackOverflow)

Can't install nuget package because of "Failed to initialize the PowerShell host"

All of a sudden, I am getting this error when upgrading Nuget packages. None of the fixes that I have come across work. I am using Visual Studio 2013.

'Newtonsoft.Json 6.0.3' already installed.
Adding 'Newtonsoft.Json 6.0.3' to Tournaments.Notifications.
Successfully added 'Newtonsoft.Json 6.0.3' to Tournaments.Notifications.
Executing script file 'F:\My Webs\BasketballTournaments\MainBranch\packages\Newtonsoft.Json.6.0.3\tools\install.ps1'.
Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first.

Package Manager Console

Attempting to perform the InitializeDefaultDrives operation on the 'FileSystem' provider failed.

If I wait for the initialization to finish in the console I was able to add some packages.


Source: (StackOverflow)

How to handle command-line arguments in PowerShell

What is the "best" way to handle command-line arguments?

It seems like there are several answers on what the "best" way is and as a result I am stuck on how to handle something as simple as:

script.ps1 /n name /d domain

AND

script.ps1 /d domain /n name.

Is there a plugin that can handle this better? I know I am reinventing the wheel here.

Obviously what I have already isn't pretty and surely isn't the "best", but it works.. and it is UGLY.

for ( $i = 0; $i -lt $args.count; $i++ ) {
    if ($args[ $i ] -eq "/n"){ $strName=$args[ $i+1 ]}
    if ($args[ $i ] -eq "-n"){ $strName=$args[ $i+1 ]}
    if ($args[ $i ] -eq "/d"){ $strDomain=$args[ $i+1 ]}
    if ($args[ $i ] -eq "-d"){ $strDomain=$args[ $i+1 ]}
}
Write-Host $strName
Write-Host $strDomain

Source: (StackOverflow)