Powershell equivalent of DOS %~dp0 command

Hello Folks!
Does anyone know of a way to output the directory path of the powershell file being executed is located?  I'm using SCCM to install applications via a script which means the source files (inlcuding the script) will be ran from multiple distribution
points and I don't want to point to one particular server's source files.
In Dos or Batch scripts this is done by %~dp0filename.msi.  Is there a way to do this via Powershell?
Thanks in adavance!!

If you're using PowerShell version 3.0 or later, this is in an automatic variable called $PSScriptRoot.
In PowerShell 2.0, that variable didn't exist, but you could get at the same information through $MyInvocation.  For example:
$scriptRoot = Split-Path -Path $MyInvocation.MyCommand.Path

Similar Messages

  • What is the powershell equivalent of unix Export command?

    my unix code is like this
    abc=test1 ; export abc
    xyz=test2 ; export xyz
    i want above script is to be converted into powershell??

    It varies depending on which browser you're using. In Safari, choose Preferences from the Safari menu, click on the Privacy tab, and then on Details.
    (101212)

  • B Installing 9 brings up DOS SETUP command window then fails

    Installing 9 starts and then a DOS SETUP command box appears, asking to insert Disk 1 DOS Install floppy in drive a: It then fails to do the 9 install, no matter what I do. It simply fails ! I tried installing in SAFE MODE, but still does the same thing. Cannot get any help on this from several XP forums, or from Microsoft. Any ideas ?

    Errol, you've asked this question several times without getting a
    response - presumably because nobody can fathom your setup.
    If the PATH command in your boot sequence points to a directory
    containing a 'setup.exe', it looks like the installer picks that one
    instead of the right one. Try temporarily renaming the wrong
    setup.exe or modifying PATH to force the installer to look in the
    right place.
    Noel

  • DOS/Windows command in app server

    I don't know if this is the correct forum.
    I want to know if there is a t-code or report to execute a DOS/Windows command in the application server.
    thanks all in advance.

    Hello Mauro,
    you can define an external command in SM69.
    Regards
    Gregor

  • Powershell send-mailmessage error - helo command rejected: need fully-qualified

    did you try the From and To email addresses in the format of
    "User01 "
    "User02 "
    Like the examples here?
    https://technet.microsoft.com/en-us/library/hh849925.aspx

    Hello,I need help with sending e-mails via Powershell using SMTP authentication. I've described the problem here on StackOverflow already:
    http://stackoverflow.com/questions/31542444/powershell-send-mailmessage-error-helo-command-rejected-...Re-pasting here: """I've read many sources regarding this issue, but no luck :/I am trying to use Powershell 4.0 (Windows server 2012 R2) to send e-mails via the Send-MailMessage commandlet in this way:PHP$From = "[email protected]"$To = "[email protected]"$Subject = "e-mail odeslany z powershellu :)"$Body = "..."$SMTPServer = "smtp.mydomain.cz"$SMTPPort = "587"$credentials = new-object Management.Automation.PSCredential “[email protected]”, (“xxxpasswordxxx” | ConvertTo-SecureString -AsPlainText -Force)Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer...
    This topic first appeared in the Spiceworks Community

  • Executing dos TYPE command Failure

    I am trying to execute the dos TYPE command from within Java. But I would like the output to go to a file, not to the screen. The following program sends the output to the screen, but not to the specified file. Why?
    It does actually create the file I want but it is empty.
    import java.io.*;
    class ExecuteCommand
         public static void main(String[] a) throws IOException
         Runtime rt = Runtime.getRuntime();
         Process p = rt.exec("cmd /c start type d:\\java\\billing\\test66.java>d:\\java\\billing\\outputFile.txt");
    Many thanks
    Akz

    Try this:
    Process p = rt.exec(new String {} { "cmd","/c","start","type" ,"d:\\java\\billing\\test66.java", ">d:\\java\\billing\\outputFile.txt" } );

  • Reproduce DOS 'tree' command to a real directory structure

    Hi guys,
    I have the output of a DOS 'tree' command (small example below). And I'm trying to reproduce the output of this command (directories and files) as another directory structure, I've tried several different things with no real luck. My biggest problem is that I'm unable to get the logic down to correctly nest directories. I was just wondering if anyone would be able to give me any code examples to help me out, it's a long shot as what I'm doing is pretty abstract, but any advice or code would be a great help.
    Thanks, aqzman
    +---Eagle Files
    |   |   DESCRIPTION
    |   |
    |   +---AnalogFE1
    |   |   |   ANALOGFE1C.brd
    |   |   |   ANALOGFE1C.sch
    |   |   |   ANALOGFE1D.sch
    |   |   |   ANALOGFE1E.brd
    |   |   |   ANALOGFE1E.s#1
    |   |   |   ANALOGFE1E.sch
    |   |   |   DESCRIPTION
    |   |   |   eagle.epf
    |   |   |
    |   |   +---V2
    |   |           ANALOGFE1B.b#1
    |   |           ANALOGFE1B.b#2
    |   |           ANALOGFE1B.b#3

    You need to read the group of directories and files in a recursive manner. If what you read is a directory, create that as a new directory where you are creating the new entries. If you read a file, then copy that file to the new directory you created.
    To get more information on recursive programming, use Google to search for explanations and examples.
    This tutorial has explanations and examples of reading directory entries and files, and creating directories and copying files.
    [http://java.sun.com/docs/books/tutorial/essential/io/index.html]
    Also read the File class API, as you will use the methods it provides.

  • Exchange Powershell return value from Get-command to variable.

    Hi
    I am trying to create a powershell-script for our monitoring-software.
    The script is supposed to establish a connection to our exchange-server mgmt-shell and execute this command:
    "Get-MailboxDatabaseCopyStatus"
    I have the connection in place, but am missing the knowledge of how to return the result of the command to my script, which I can then pass to our monitoring-software.
    (The script take 2 parameters - host and command eg. exch01.domain and Get-MailboxDatabaseCopyStatus).
    Current code:
    $statusAlive = "ScriptRes:Host is alive:"
    $statusDead = "ScriptRes:No answer:"
    $statusUnknown = "ScriptRes:Unknown:"
    $statusNotResolved = "ScriptRes:Unknown host:"
    $statusOk = "ScriptRes:Ok:"
    $statusBad = "ScriptRes:Bad:"
    $statusBadContents = "ScriptRes:Bad contents:"
    $pass = cat C:\securestring.txt | convertto-securestring
    $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "domain\administrator",$pass
    $host = $args[0]
    $command = $args[1]
    <#
    if (!$args[0]) {
    echo $statusUnknown"Host parameter is empty"
    exit
    if (!$args[1]) {
    echo $statusUnknown"Command parameter is empty"
    exit
    #>
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$host/powershell -Credential $cred
    Import-PSSession $session
    $command
    Remove-PSSession $session
    Now, how do I "catch" the value of the executed command and return it to a variable in the script?
    Best Regards,
    Soren

    Hmm.. doesnt seem to work quite right.
    I added "Echo $result" after "Remove-PSSession $session", but then I just get a bunch of information..
    Script tmp_c3a1c132-f4d9-4d61... {Get-IRMConfiguration, New-MailUser, Get-PublicFolderMigrationRequestSta...
    RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
    Identity : DB02 - Specielle\EXCHANGE01
    Id : DB02 - Specielle\EXCHANGE01
    Name : DB02 - Specielle\EXCHANGE01
    DatabaseName : DB02 - Specielle
    Status : Mounted
    InstanceStartTime : 01-03-2014 03:35:07
    LastStatusTransitionTime :
    MailboxServer : EXCHANGE01
    ActiveDatabaseCopy : EXCHANGE01
    ActiveCopy : True
    ActivationPreference : 1
    StatusRetrievedTime : 11-03-2014 08:30:15
    WorkerProcessId : 8124
    ActivationSuspended : False
    ActionInitiator : Unknown
    ErrorMessage :
    ErrorEventId :
    ExtendedErrorInfo :
    SuspendComment :
    RequiredLogsPresent :
    SinglePageRestore : 0
    ContentIndexState : Healthy
    ContentIndexErrorMessage :
    ContentIndexVersion : 1
    ContentIndexBacklog : 0
    ContentIndexRetryQueueSize : 0
    ContentIndexMailboxesToCrawl :
    ContentIndexSeedingPercent :
    ContentIndexSeedingSource :
    CopyQueueLength : 0
    ReplayQueueLength : 0
    ReplaySuspended : False
    ResumeBlocked : False
    ReseedBlocked : False
    MinimumSupportedDatabaseSchemaVersion : 0.121
    MaximumSupportedDatabaseSchemaVersion : 0.125
    RequestedDatabaseSchemaVersion : 0.125
    LatestAvailableLogTime :
    LastCopyNotificationedLogTime :
    LastCopiedLogTime :
    LastInspectedLogTime :
    LastReplayedLogTime :
    LastLogGenerated : 0
    LastLogCopyNotified : 0
    LastLogCopied : 0
    LastLogInspected : 0
    LastLogReplayed : 0
    LowestLogPresent : 0
    LastLogInfoIsStale : False
    LastLogInfoFromCopierTime :
    LastLogInfoFromClusterTime :
    LastLogInfoFromClusterGen : 0
    LogsReplayedSinceInstanceStart : 0
    LogsCopiedSinceInstanceStart : 0
    LatestFullBackupTime :
    LatestIncrementalBackupTime :
    LatestDifferentialBackupTime :
    LatestCopyBackupTime :
    SnapshotBackup :
    SnapshotLatestFullBackup :
    SnapshotLatestIncrementalBackup :
    SnapshotLatestDifferentialBackup :
    SnapshotLatestCopyBackup :
    LogReplayQueueIncreasing : False
    LogCopyQueueIncreasing : False
    ReplayLagStatus :
    DatabaseSeedStatus :
    OutstandingDumpsterRequests : {}
    OutgoingConnections :
    IncomingLogCopyingNetwork :
    SeedingNetwork :
    DiskFreeSpacePercent : 50
    DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
    DiskTotalSpace : 40 GB (42,946,523,136 bytes)
    ExchangeVolumeMountPoint :
    DatabaseVolumeMountPoint : E:\
    DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
    DatabasePathIsOnMountedFolder : False
    LogVolumeMountPoint : F:\
    LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
    LogPathIsOnMountedFolder : False
    LastDatabaseVolumeName :
    LastDatabaseVolumeNameTransitionTime :
    VolumeInfoError :
    IsValid : True
    ObjectState : Unchanged
    RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
    Identity : DB01 - Standard\EXCHANGE01
    Id : DB01 - Standard\EXCHANGE01
    Name : DB01 - Standard\EXCHANGE01
    DatabaseName : DB01 - Standard
    Status : Mounted
    InstanceStartTime : 01-03-2014 03:35:07
    LastStatusTransitionTime :
    MailboxServer : EXCHANGE01
    ActiveDatabaseCopy : EXCHANGE01
    ActiveCopy : True
    ActivationPreference : 1
    StatusRetrievedTime : 11-03-2014 08:30:15
    WorkerProcessId : 8140
    ActivationSuspended : False
    ActionInitiator : Unknown
    ErrorMessage :
    ErrorEventId :
    ExtendedErrorInfo :
    SuspendComment :
    RequiredLogsPresent :
    SinglePageRestore : 0
    ContentIndexState : Healthy
    ContentIndexErrorMessage :
    ContentIndexVersion : 1
    ContentIndexBacklog : 3
    ContentIndexRetryQueueSize : 0
    ContentIndexMailboxesToCrawl :
    ContentIndexSeedingPercent :
    ContentIndexSeedingSource :
    CopyQueueLength : 0
    ReplayQueueLength : 0
    ReplaySuspended : False
    ResumeBlocked : False
    ReseedBlocked : False
    MinimumSupportedDatabaseSchemaVersion : 0.121
    MaximumSupportedDatabaseSchemaVersion : 0.125
    RequestedDatabaseSchemaVersion : 0.125
    LatestAvailableLogTime :
    LastCopyNotificationedLogTime :
    LastCopiedLogTime :
    LastInspectedLogTime :
    LastReplayedLogTime :
    LastLogGenerated : 0
    LastLogCopyNotified : 0
    LastLogCopied : 0
    LastLogInspected : 0
    LastLogReplayed : 0
    LowestLogPresent : 0
    LastLogInfoIsStale : False
    LastLogInfoFromCopierTime :
    LastLogInfoFromClusterTime :
    LastLogInfoFromClusterGen : 0
    LogsReplayedSinceInstanceStart : 0
    LogsCopiedSinceInstanceStart : 0
    LatestFullBackupTime :
    LatestIncrementalBackupTime :
    LatestDifferentialBackupTime :
    LatestCopyBackupTime :
    SnapshotBackup :
    SnapshotLatestFullBackup :
    SnapshotLatestIncrementalBackup :
    SnapshotLatestDifferentialBackup :
    SnapshotLatestCopyBackup :
    LogReplayQueueIncreasing : False
    LogCopyQueueIncreasing : False
    ReplayLagStatus :
    DatabaseSeedStatus :
    OutstandingDumpsterRequests : {}
    OutgoingConnections :
    IncomingLogCopyingNetwork :
    SeedingNetwork :
    DiskFreeSpacePercent : 50
    DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
    DiskTotalSpace : 40 GB (42,946,523,136 bytes)
    ExchangeVolumeMountPoint :
    DatabaseVolumeMountPoint : E:\
    DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
    DatabasePathIsOnMountedFolder : False
    LogVolumeMountPoint : F:\
    LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
    LogPathIsOnMountedFolder : False
    LastDatabaseVolumeName :
    LastDatabaseVolumeNameTransitionTime :
    VolumeInfoError :
    IsValid : True
    ObjectState : Unchanged
    I am only interested in the 2 "ContentIndexState" - how can I pick these 2 out and put them into a variable?
    I though the command "Get-MailboxDatabaseCopyStatus" would only display these two, since it is what happens if I run the command inside PowerShell on the server itself.

  • Is it possible to run all Dos based command on Java ?

    hello friends
    I run Dos Commands on Java by following code
    try{
    Process p=Runtime.getRuntime().exec(new String[]{"cmd.exe","/c","dir"});
    }catch(Exception e){e.printStackTrace();}
    System.out.println("bye");
    If I run "mkdir" instead of "dir" folder is created in current directory. But in case of "dir" listing of file folders is not displayed to me . means "dir " is not running.
    could any body tell me what to do in this case
    thanks

    ejp wrote:
    'dir' is not an executable program. It is built-in to the command shell. The only way you can execute it is by feeding it to a shell via a batch file.Sorry 'ejp' but 'dir' can be run this way (I have just checked on XP) so there has to be something wrong with the way the OP is processing the results. Since he does not seem to process stdout or stderr and he does not wait for the process to complete I am betting he is falling foul of one or more of the traps. My best bet is that he is expecting a console window to open and the directory listing to appear in it.

  • Issue with variables and white space in powershell script that calls a command line command

    Guys,
    I have a question regarding this script. Each time I run it, it creates the share, but with a space after it. Also I need help figuring out how to put in the variable for the folder path.
    Below is the code
    $Users=Import-Csv C:\users2.csv
    foreach($User in $Users){
         $User.SNCORP
         $User.HPB
         $User
         cmd /c "net share "$User.SNCORP"=D:\Users\"$User.HPB" /grant:Everyone,FULL"
    The csv file looks like this
    HPB,SNCORP
    ccarter,carterch$
    This is my output in powershell
    PS C:\> .\shareflip.ps1
    carterch$
    ccarter
    HPB                                                         SNCORP
    ccarter                                                     carterch$
    The syntax of this command is:
    NET SHARE
    sharename
              sharename=drive:path [/GRANT:user,[READ | CHANGE | FULL]]
                                   [/USERS:number | /UNLIMITED]
                                   [/REMARK:"text"]
                                   [/CACHE:Manual | Documents| Programs | BranchCache | None]
              sharename [/USERS:number | /UNLIMITED]
                        [/REMARK:"text"]
                        [/CACHE:Manual | Documents | Programs | BranchCache | None]
              {sharename | devicename | drive:path} /DELETE
              sharename \\computername /DELETE
    Any help is greatly appreciated. 
    Christopher

    There is no need to use cmd /c. You should be able to use:
    net share "$($User.SNCORP)=D:\Users\$($User.HPB)" "/grant:Everyone,Full"
    Use showargs.exe (from the article) at the beginning of this line to see the command line PowerShell is actually running (very useful for troubleshooting).
    -- Bill Stewart [Bill_Stewart]

  • Is there an enhanced equivalent of crs_stat -t command in 11.2 ?

    DB version: 11.2.0.1
    Os : Solaris
    In 10gR2, we used
    crs_stat -tto check the status of cluster. Is there an enhanced equivalent of this command in 11.2 ?

    Thank you Rajesh. Do you set anything in putty (like increasing the row width) to make it more readable.
    The output look a bit messed up
    $ crsctl stat res -t -init
    NAME           TARGET  STATE        SERVER                   STATE_DETAILS
    Cluster Resources
    ora.asm
          1        ONLINE  ONLINE       fmtest1                  Started
    ora.cluster_interconnect.haip
          1        ONLINE  ONLINE       fmtest1
    ora.crf
          1        ONLINE  ONLINE       fmtest1
    ora.crsd
          1        ONLINE  ONLINE       fmtest1

  • Report script command equivalent for @relative calculation command

    HI ,
    We have a calculation script which has a fix statement like below :
         FIX( Grade, "w/o LO", "Line Options", AtLaunch, @DESCENDANTS("470.92"), @DESCENDANTS("Price Item"), @RELATIVE("Total Region", 0) )
    We are trying to make a reportscript which gives us the format of the set of database being calculated.
    So we are tranforming the above calc script commands into equivalent report script commands. We are struck with the @Relative command.
    Can somebody tell us what is the equivalent report script command for @Relative calculation script function.
    Regards
    OKU

    There's no direct analogue, but you can use the <LINK command along with <DESCENDANTS and <LEV to get pretty close. See: http://download.oracle.com/docs/cd/E10530_01/doc/epm.931/html_esb_techref/rwriter/link.htm
    JExport (if pre 9.3) or DATAEXPORT (if 9.3 or greater) may also be options and will in fact allow @RELATIVE to be used.
    Regards,
    Cameron Lackpour

  • Installing 9 brings up DOS SETUP command window !! Cannot continue

    I tried to install Reader 9. Just after the install starts, the command window appears with a title C:\DOS\SETUP and says "To install MS-DOS, Insert Disk 1 in drive A and press CNTRL+ALT+DEL. This will restart your computer and begin the Setup program. Or press ENTER to return to your command prompt."
    If I press Enter, the Adobe install simply stops and I am returned to the Windows desktop !!??
    My computer is a multiboot setup with XP Vista DOS and Ubuntu, all on seperate partitions. The default system is XP.

    This is boot.ini on my C drive.
    (The system actually boots via the Ubuntu partition, the picks up the Vista booting file)
    ;Warning: Boot.ini is used on Windows XP and earlier operating systems.
    ;Warning: Use BCDEDIT.exe to modify Windows Vista boot options.
    [boot loader]
    timeout=3
    default=multi(0)disk(0)rdisk(0)partition(3)\WINDOWS
    [operating systems]
    multi(0)disk(0)rdisk(0)partition(3)\WINDOWS="Microsoft Windows XP Professional" /FASTDETECT
    c:\="MS-DOS"

  • Opening PDF link through DOS start command

    Our software manager is asking if we can use a simple DOS command (embedded in a browser-like xaml interface) to open a PDF file to a hypertext link brought over from a FrameMaker source doc.
    I know that I can open a.pdf with DOS command "start a.pdf", but I am unsure (and cannot find) the syntax that I need to tell DOS to open the PDF to the "test1" hypertext link on page 3 of the PDF.
    Thanks for any help.
    best,
    Paul

    Check the "Parameters for Openinig PDF Files" document at <a<br />href="http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf">http://www.adob e.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf</a>. It says: <br /><br />When opening a PDF document from a command shell, you can pass the parameters to the open command using the /A switch with the following syntax:<br /><br /><Acrobat path> /A "<parameter>=<value>" "<PDF path>"<br /><br />For example:<br />Acrobat.exe /A "zoom=1000" "C:\example.pdf"<br /><br />Use the page or destination parameter (if you add destinations to the PDF). I tried it with the page parameter and it worked.<br /><br />--GMc

  • Lldb equivalent of gdb "directory" command for specifying source search path?

    Looking for the lldb equivalent of the gdb "directory" command to add search paths for finding missing source code files (due to moved directories). Or possibly similar functionality within xcode...
    Thanks in advance!

    Great, thanks for the pointer although according to the lldb console the "add" command needs a "substitution pair" argument and the "Insert" command needs a new "image search path" and the "target modules list" command only gives a list of dylib modules. I played around a bit and the construction resembles more of a dylib module search path .i.e it looks like you only can revert the module search path but not separate it from the source path.
    It would be nice to find out more details about different search-path capabilities within lldb. You don't happen to know where to find more thorough LLDB manuals or other useful documentation besides the "LLDB to GDB Command Map" (http://lldb.llvm.org/lldb-gdb.html) and the "LLDB Tutorial" (lldb.llvm.org/tutorial.html), do you? Also, any idea where to find the official doc pages for lldb. Unfortunately "http://lldb.llvm.org/docs.html" is still empty and I didn't find anything useful in the llvm github.

Maybe you are looking for