Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. why cant I run powershell script from current directory

why cant I run powershell script from current directory

Scheduled Pinned Locked Moved C#
questioncsharpwindows-admindebuggingtools
14 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Sherzaad13291325
    wrote on last edited by
    #1

    the following is part for a c# code that I am working on:

    // Specify the PowerShell script filename
    powerShellScriptFilename = @"C:\Users\sherz\OneDrive\Downloads\enableTouchScreen.ps1";

    // Create process start info
    ProcessStartInfo psi = new ProcessStartInfo
    {
    FileName = "powershell.exe",
    Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{powerShellScriptFilename}\"",
    RedirectStandardInput = false,
    RedirectStandardOutput = false,
    RedirectStandardError = false,
    CreateNoWindow = true,
    UseShellExecute = true, //need to be set to true for 'Verb' to function
    Verb = "runas" //run application as Administrator
    //WorkingDirectory = Directory.GetCurrentDirectory()
    };

    // Create the process
    Process process = new Process { StartInfo = psi };

    // Start the process
    process.Start();

    With this above the script run as expected. The issue is if I move the script to the 'currentDirectory' (ie the Project debug folder) the script is not executed. I already tried updating 'powerShellScriptFilename' with the corresponding absolute path, script still worth execute. As the code works if I chose a different location, it seems to me that there may be some restriction or filepath length issue. My aim is to try and avoid hard coding the filepath to the script and I would like my program to pick its current directory to find the script and run it. How can I test/do that if it is not possible to do that from the debug folder? still quite new to C# but keen to learn! :)

    R J S S 4 Replies Last reply
    0
    • S Sherzaad13291325

      the following is part for a c# code that I am working on:

      // Specify the PowerShell script filename
      powerShellScriptFilename = @"C:\Users\sherz\OneDrive\Downloads\enableTouchScreen.ps1";

      // Create process start info
      ProcessStartInfo psi = new ProcessStartInfo
      {
      FileName = "powershell.exe",
      Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{powerShellScriptFilename}\"",
      RedirectStandardInput = false,
      RedirectStandardOutput = false,
      RedirectStandardError = false,
      CreateNoWindow = true,
      UseShellExecute = true, //need to be set to true for 'Verb' to function
      Verb = "runas" //run application as Administrator
      //WorkingDirectory = Directory.GetCurrentDirectory()
      };

      // Create the process
      Process process = new Process { StartInfo = psi };

      // Start the process
      process.Start();

      With this above the script run as expected. The issue is if I move the script to the 'currentDirectory' (ie the Project debug folder) the script is not executed. I already tried updating 'powerShellScriptFilename' with the corresponding absolute path, script still worth execute. As the code works if I chose a different location, it seems to me that there may be some restriction or filepath length issue. My aim is to try and avoid hard coding the filepath to the script and I would like my program to pick its current directory to find the script and run it. How can I test/do that if it is not possible to do that from the debug folder? still quite new to C# but keen to learn! :)

      R Offline
      R Offline
      Richard Deeming
      wrote on last edited by
      #2

      How about:

      powerShellScriptFilename = Path.GetFullPath("enableTouchScreen.ps1");

      ProcessStartInfo psi = new ProcessStartInfo
      {
      FileName = "powershell.exe",
      Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{powerShellScriptFilename}\"",
      RedirectStandardInput = false,
      RedirectStandardOutput = false,
      RedirectStandardError = false,
      CreateNoWindow = true,
      UseShellExecute = true, //need to be set to true for 'Verb' to function
      Verb = "runas" //run application as Administrator
      };

      Process process = Process.Start(psi);

      Beyond that, we need to know what "not working" means. Provide the full details of the error you're getting. If it's a PowerShell error, then you may need to provide the relevant parts of your PowerShell script as well.


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      S 1 Reply Last reply
      0
      • R Richard Deeming

        How about:

        powerShellScriptFilename = Path.GetFullPath("enableTouchScreen.ps1");

        ProcessStartInfo psi = new ProcessStartInfo
        {
        FileName = "powershell.exe",
        Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{powerShellScriptFilename}\"",
        RedirectStandardInput = false,
        RedirectStandardOutput = false,
        RedirectStandardError = false,
        CreateNoWindow = true,
        UseShellExecute = true, //need to be set to true for 'Verb' to function
        Verb = "runas" //run application as Administrator
        };

        Process process = Process.Start(psi);

        Beyond that, we need to know what "not working" means. Provide the full details of the error you're getting. If it's a PowerShell error, then you may need to provide the relevant parts of your PowerShell script as well.


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        S Offline
        S Offline
        Sherzaad13291325
        wrote on last edited by
        #3

        thank you. will try that when I get home. "not working" means not working. not much more I can provide as I receive/can see no errors. as you may have guessed from the fileames, the script enables my screentouch and that is how I know it was not successfull when I tried the current directory path. with the original directory path, I would be able to enable my screentouch...

        1 Reply Last reply
        0
        • S Sherzaad13291325

          the following is part for a c# code that I am working on:

          // Specify the PowerShell script filename
          powerShellScriptFilename = @"C:\Users\sherz\OneDrive\Downloads\enableTouchScreen.ps1";

          // Create process start info
          ProcessStartInfo psi = new ProcessStartInfo
          {
          FileName = "powershell.exe",
          Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{powerShellScriptFilename}\"",
          RedirectStandardInput = false,
          RedirectStandardOutput = false,
          RedirectStandardError = false,
          CreateNoWindow = true,
          UseShellExecute = true, //need to be set to true for 'Verb' to function
          Verb = "runas" //run application as Administrator
          //WorkingDirectory = Directory.GetCurrentDirectory()
          };

          // Create the process
          Process process = new Process { StartInfo = psi };

          // Start the process
          process.Start();

          With this above the script run as expected. The issue is if I move the script to the 'currentDirectory' (ie the Project debug folder) the script is not executed. I already tried updating 'powerShellScriptFilename' with the corresponding absolute path, script still worth execute. As the code works if I chose a different location, it seems to me that there may be some restriction or filepath length issue. My aim is to try and avoid hard coding the filepath to the script and I would like my program to pick its current directory to find the script and run it. How can I test/do that if it is not possible to do that from the debug folder? still quite new to C# but keen to learn! :)

          J Offline
          J Offline
          jschell
          wrote on last edited by
          #4

          Sherzaad13291325 wrote:

          move to the script

          Presumably you mean 'enableTouchScreen.ps1' for script. Several obvious possibilities. - You did not in fact move it. - You did not update the path in your code. - The path that you did update is wrong. - You did not recompile the code after updating the path. As one check for errors and probably one that I would always do in this type of code is to verify that the script (the path) exists before attempting to run it. Additionally I might be inclined to check permissions also. Doing both of the above is required if you intend for this code to eventually run in a Windows Service or a IIS App Pool.

          1 Reply Last reply
          0
          • S Sherzaad13291325

            the following is part for a c# code that I am working on:

            // Specify the PowerShell script filename
            powerShellScriptFilename = @"C:\Users\sherz\OneDrive\Downloads\enableTouchScreen.ps1";

            // Create process start info
            ProcessStartInfo psi = new ProcessStartInfo
            {
            FileName = "powershell.exe",
            Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{powerShellScriptFilename}\"",
            RedirectStandardInput = false,
            RedirectStandardOutput = false,
            RedirectStandardError = false,
            CreateNoWindow = true,
            UseShellExecute = true, //need to be set to true for 'Verb' to function
            Verb = "runas" //run application as Administrator
            //WorkingDirectory = Directory.GetCurrentDirectory()
            };

            // Create the process
            Process process = new Process { StartInfo = psi };

            // Start the process
            process.Start();

            With this above the script run as expected. The issue is if I move the script to the 'currentDirectory' (ie the Project debug folder) the script is not executed. I already tried updating 'powerShellScriptFilename' with the corresponding absolute path, script still worth execute. As the code works if I chose a different location, it seems to me that there may be some restriction or filepath length issue. My aim is to try and avoid hard coding the filepath to the script and I would like my program to pick its current directory to find the script and run it. How can I test/do that if it is not possible to do that from the debug folder? still quite new to C# but keen to learn! :)

            S Offline
            S Offline
            Sherzaad13291325
            wrote on last edited by
            #5

            Sherzaad13291325 wrote:

            the code works if I chose a different location, it seems to me that there may be some restriction or filepath length issue

            My suspicion was right! turns out is WAS a filepath length. Converted the 'fullpath' to its 'shortpath' and code is now running as it did before :)

            D 1 Reply Last reply
            0
            • S Sherzaad13291325

              Sherzaad13291325 wrote:

              the code works if I chose a different location, it seems to me that there may be some restriction or filepath length issue

              My suspicion was right! turns out is WAS a filepath length. Converted the 'fullpath' to its 'shortpath' and code is now running as it did before :)

              D Offline
              D Offline
              Dave Kreskowiak
              wrote on last edited by
              #6

              Based on the code you posted, no, it wasn't filepath length. The max length of a filepath is 260 characters. The max length of the Windows command line is 32K, and I seriously doubt your command line was that long.

              Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles. Dave Kreskowiak

              T J 2 Replies Last reply
              0
              • S Sherzaad13291325

                the following is part for a c# code that I am working on:

                // Specify the PowerShell script filename
                powerShellScriptFilename = @"C:\Users\sherz\OneDrive\Downloads\enableTouchScreen.ps1";

                // Create process start info
                ProcessStartInfo psi = new ProcessStartInfo
                {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{powerShellScriptFilename}\"",
                RedirectStandardInput = false,
                RedirectStandardOutput = false,
                RedirectStandardError = false,
                CreateNoWindow = true,
                UseShellExecute = true, //need to be set to true for 'Verb' to function
                Verb = "runas" //run application as Administrator
                //WorkingDirectory = Directory.GetCurrentDirectory()
                };

                // Create the process
                Process process = new Process { StartInfo = psi };

                // Start the process
                process.Start();

                With this above the script run as expected. The issue is if I move the script to the 'currentDirectory' (ie the Project debug folder) the script is not executed. I already tried updating 'powerShellScriptFilename' with the corresponding absolute path, script still worth execute. As the code works if I chose a different location, it seems to me that there may be some restriction or filepath length issue. My aim is to try and avoid hard coding the filepath to the script and I would like my program to pick its current directory to find the script and run it. How can I test/do that if it is not possible to do that from the debug folder? still quite new to C# but keen to learn! :)

                S Offline
                S Offline
                Sernjijj Kabral
                wrote on last edited by
                #7

                Yes, if nationality [wisdom], then it would recommend of vb has finally ended, as stipulated.

                1 Reply Last reply
                0
                • D Dave Kreskowiak

                  Based on the code you posted, no, it wasn't filepath length. The max length of a filepath is 260 characters. The max length of the Windows command line is 32K, and I seriously doubt your command line was that long.

                  Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles. Dave Kreskowiak

                  T Offline
                  T Offline
                  trønderen
                  wrote on last edited by
                  #8

                  You are right that the OP has not provided enough info for us to certainly conclude that it was a path length problem. But we certainly cannot reject it. Then file name of his script, "enableTouchScreen.ps1", is 21 chars. He reports that when it is moved to "the 'currentDirectory' (ie the Project debug folder)", it won't work. If the length of 'cd' exceeds 238 chars, the full script file name would exceed 260 chars. I certainly have seen project directory paths exceeding 238 chars; in my last job, the naming rules made it more or less the standard. What surprises me more is that the OP does not run into this problem with other files in his project as well. Maybe it is set up will all relative naming (and no tools expand it to an absolute path), or all files are located in other directories with shorter paths, or all the other tools are prepared for long file paths. 260 chars was the old DOS/FAT limit. As long as you use new Windows file system APIs that can handle longer NTFS paths, they can be up to approx. 32 Ki characters. The 260 length is not really in NTFS or Windows, but in individual programs using old APIs. These APIs have not been extended to long file names because lots of old program have allocated 261 chars for a file path buffer, frequently with no overrun check as that is the maximum length. If an old API used to return names limited by MAX_PATH after a minor update starts returning names of several hundred or thousand characters, then you would have a buffer overrun. It is a pity that the myth of Windows being limited to 260 chars are still living. It makes lots of programmers continue making 261 char allocations, and the old APIs that should have been marked as deprecated 20 years ago and removed 10 years ago. Backwards compatibility is great (and Windows is far better at it than competing OSes!) but sometimes it goes too far.

                  Religious freedom is the freedom to say that two plus two make five.

                  D 1 Reply Last reply
                  0
                  • D Dave Kreskowiak

                    Based on the code you posted, no, it wasn't filepath length. The max length of a filepath is 260 characters. The max length of the Windows command line is 32K, and I seriously doubt your command line was that long.

                    Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles. Dave Kreskowiak

                    J Offline
                    J Offline
                    jschell
                    wrote on last edited by
                    #9

                    Dave Kreskowiak wrote:

                    The max length of a filepath is 260 characters. The max length of the Windows command line is 32K

                    I didn't find an authoritative source but googling I did find recent posts that suggests that the length limit for Powershell scripts is 260 characters. Presumably the command execution would fail then. Probably with a return value of '2'? (File not found?).

                    1 Reply Last reply
                    0
                    • T trønderen

                      You are right that the OP has not provided enough info for us to certainly conclude that it was a path length problem. But we certainly cannot reject it. Then file name of his script, "enableTouchScreen.ps1", is 21 chars. He reports that when it is moved to "the 'currentDirectory' (ie the Project debug folder)", it won't work. If the length of 'cd' exceeds 238 chars, the full script file name would exceed 260 chars. I certainly have seen project directory paths exceeding 238 chars; in my last job, the naming rules made it more or less the standard. What surprises me more is that the OP does not run into this problem with other files in his project as well. Maybe it is set up will all relative naming (and no tools expand it to an absolute path), or all files are located in other directories with shorter paths, or all the other tools are prepared for long file paths. 260 chars was the old DOS/FAT limit. As long as you use new Windows file system APIs that can handle longer NTFS paths, they can be up to approx. 32 Ki characters. The 260 length is not really in NTFS or Windows, but in individual programs using old APIs. These APIs have not been extended to long file names because lots of old program have allocated 261 chars for a file path buffer, frequently with no overrun check as that is the maximum length. If an old API used to return names limited by MAX_PATH after a minor update starts returning names of several hundred or thousand characters, then you would have a buffer overrun. It is a pity that the myth of Windows being limited to 260 chars are still living. It makes lots of programmers continue making 261 char allocations, and the old APIs that should have been marked as deprecated 20 years ago and removed 10 years ago. Backwards compatibility is great (and Windows is far better at it than competing OSes!) but sometimes it goes too far.

                      Religious freedom is the freedom to say that two plus two make five.

                      D Offline
                      D Offline
                      Dave Kreskowiak
                      wrote on last edited by
                      #10

                      trønderen wrote:

                      260 chars was the old DOS/FAT limit. As long as you use new Windows file system APIs that can handle longer NTFS paths, they can be up to approx. 32 Ki characters. The 260 length is not really in NTFS or Windows, but in individual programs using old APIs.

                      And that's why I always say the limit is 260 characters. Yes, if using the new stuff, it's 32K, but developers, all too commonly, don't use the newer API's because the code they wrote at least a decade ago never gets updated. I've seen it way too often, even today.

                      Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles. Dave Kreskowiak

                      T 1 Reply Last reply
                      0
                      • D Dave Kreskowiak

                        trønderen wrote:

                        260 chars was the old DOS/FAT limit. As long as you use new Windows file system APIs that can handle longer NTFS paths, they can be up to approx. 32 Ki characters. The 260 length is not really in NTFS or Windows, but in individual programs using old APIs.

                        And that's why I always say the limit is 260 characters. Yes, if using the new stuff, it's 32K, but developers, all too commonly, don't use the newer API's because the code they wrote at least a decade ago never gets updated. I've seen it way too often, even today.

                        Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles. Dave Kreskowiak

                        T Offline
                        T Offline
                        trønderen
                        wrote on last edited by
                        #11

                        But by keeping that old myth alive (stating unconditionally that "The max length of a filepath is 260 characters", with no reservation, like an absolute truth), you contribute to the problem. Lots of programmers believe that as long as they allocate a 261 char buffer for the file name, they are safe and can handle all the paths there are. But they cannot. Windows software can create longer paths, as the OP experienced. I would much prefer to make a reference to the long filenames, and add a warning: Beware that if the path exceeds 260 char, then software using old FAT oriented calls to obtain the file path might fail. Trying to keep the solution to the problem secret, because some programmers is not aware of it, is no good way to bring the world forward. In my eyes, that is.

                        Religious freedom is the freedom to say that two plus two make five.

                        D L 2 Replies Last reply
                        0
                        • T trønderen

                          But by keeping that old myth alive (stating unconditionally that "The max length of a filepath is 260 characters", with no reservation, like an absolute truth), you contribute to the problem. Lots of programmers believe that as long as they allocate a 261 char buffer for the file name, they are safe and can handle all the paths there are. But they cannot. Windows software can create longer paths, as the OP experienced. I would much prefer to make a reference to the long filenames, and add a warning: Beware that if the path exceeds 260 char, then software using old FAT oriented calls to obtain the file path might fail. Trying to keep the solution to the problem secret, because some programmers is not aware of it, is no good way to bring the world forward. In my eyes, that is.

                          Religious freedom is the freedom to say that two plus two make five.

                          D Offline
                          D Offline
                          Dave Kreskowiak
                          wrote on last edited by
                          #12

                          No, I don't. Developers who refuse to update their code contribute to the problem, and yes, I still see those problems today. I mention the limit for compatibility reasons.

                          Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles. Dave Kreskowiak

                          1 Reply Last reply
                          0
                          • T trønderen

                            But by keeping that old myth alive (stating unconditionally that "The max length of a filepath is 260 characters", with no reservation, like an absolute truth), you contribute to the problem. Lots of programmers believe that as long as they allocate a 261 char buffer for the file name, they are safe and can handle all the paths there are. But they cannot. Windows software can create longer paths, as the OP experienced. I would much prefer to make a reference to the long filenames, and add a warning: Beware that if the path exceeds 260 char, then software using old FAT oriented calls to obtain the file path might fail. Trying to keep the solution to the problem secret, because some programmers is not aware of it, is no good way to bring the world forward. In my eyes, that is.

                            Religious freedom is the freedom to say that two plus two make five.

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #13

                            The problem is not due to Dave's comments, but rather the developers' failure (or is that refusal) to make use of official documentation. We see plenty of questions where the OP says they cannot find something via Google. And yet when we repeat the search it takes us straight to the MSDN page in question.

                            T 1 Reply Last reply
                            0
                            • L Lost User

                              The problem is not due to Dave's comments, but rather the developers' failure (or is that refusal) to make use of official documentation. We see plenty of questions where the OP says they cannot find something via Google. And yet when we repeat the search it takes us straight to the MSDN page in question.

                              T Offline
                              T Offline
                              trønderen
                              wrote on last edited by
                              #14

                              Richard MacCutchan wrote:

                              The problem is not due to Dave's comments, but rather the developers' failure (or is that refusal) to make use of official documentation.

                              Or, the problem is that when some experienced programmer states "The limit IS 260 characters!" (and that is just a fact), the inexperienced programmer sees no need to go to the official documentation to learn that the experienced programmer had given him incorrect information 'just to be on the safe side'. I willingly admit that when a mate tells me how to do something, or how I can not do it (e.g. using longer paths), I frequently take that as a valid piece of information. I do not always verify against the official documentation every piece of information or every advise I receive. Maybe I should, but that would take a lot of time. I allow myself to learn from others.

                              Religious freedom is the freedom to say that two plus two make five.

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups