Choping up a string in powershell

I have a variable called $office
$Office = (get-aduser -Identity $Name -Properties * |select physicalDeliveryOfficeName).physicalDeliveryOfficeName
It produces results like this
01A;514;295;632;428;485;442;277;800;175
Of course it could be shorter or longer depending on how many locations the user is in.
Each location code will ALWAYS be separated by a semicolon.
Is there a way to break that up and use each code between the semicolons as a string that I could then use a foreach statement?
Thanks
Lishron

I had just found this article 
http://blogs.technet.com/b/heyscriptingguy/archive/2014/06/11/powertip-split-string-with-powershell.aspx
Like it was written for me but you beat me to the bunch.
Thanks so so much!
Lishron

Similar Messages

  • Remove the prefix string in powershell

    I am getting the users connected to Webservers count with this query
    $wf = Get-Counter -ComputerName "WebServerName" -Counter "\web service(_total)\Current Connections"
    I am getting the out put as..
    webservername\\web service(_total)\current connections : 5
    But i want to get out put only Webservername : 5
    Please help us ..
    Regards,
    Phani

    Hi,
    It seems you have got the answer in the thread which you asked in the Windows PowerShell forum as the link below.
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/88a4d5e3-3591-43ac-b20f-ecc915ee004e/remove-the-prefix-string-in-powershell?forum=winserverpowershell#72b8da5c-ee85-483e-a6c4-fefcb44f78f4
    Thanks.
    Tracy Cai
    TechNet Community Support

  • How can I seperate one string into multiple strings using PowerShell?

    New to PowerShell...how can I read/separate parts of a file name? For instance if I have a file name like "part1_part2_part3_part4.xls", how to separate this file name to four different parts? So I basically want to go from that file name,
    to four different strings like part1, part2, part3, and part4...as four separate strings. How can I get this done in PowerShell?
    Thanks

    You can try something like this
    PS> (Get-ChildItem part1_part2_part3_part4.xls).BaseName.Split('_')

  • Parsing a string in powershell

    I've looked around a bit and can't quite find an answer to this.    I've got a script going that looks at a configuration file, and I need to find the values that is inside of quotes.   
    config file:
    Version = "3.2"
    currently in my script I simply have
    $Versionvalue = get-content $ConfigFile | select-string "Version"
    However this returns the whole string and I need just the number that is in quotes, in Unix I would do this with some cut commands, but I haven't quite found the equivalent in my searches. 
    Thanks in advance

    You need to use parenthesis to do capturing. You can do numbered captures, or named captures. This looks like a fairly simple regular expression, so numbered is fine.
    Here are two examples using both numbered and named captures with Select-String. This assumes your version is always 'Major.Minor'. If you have revision or build numbers in there (even if they're optional), you'll need to modify the regex. (I don't use select-string
    very much, so there might be a better way to do this):
    # Numbered
    Get-Item $ConfigFile | Select-String -pattern 'Version = "(\d+\.\d+)"' | select -exp matches | % { $_.groups[1].Value }
    # Named
    Get-Item $ConfigFile | Select-String -pattern 'Version = "(?<version>\d+\.\d+)"' | select -exp matches | % { $_.groups["version"].Value }
    Here's how I would do it using the -match comparison operator (which doesn't mean it's the best way). For more info on the -match operator, see the about_Comparison_Operators help topic:
    # Numbered:
    Get-Content $ConfigFile | foreach { if ($_ -match 'Version = "(\d+\.\d+)"') { $matches[1] } }
    # Named:
    Get-Content $ConfigFile | foreach { if ($_ -match 'Version = "(?<version>\d+\.\d+)"') { $matches.version } }
    Note that if your config file has more than one 'Version = "x.x"' line in it, you'll get more than one result back.

  • How to user PowerShell -replace to remove the dreaded em dash from a file name?

    I have a bunch of .msg files in a directory and want to zip them up (to send them to our spam filtering company), but I keep getting errors on file names that contain the em dash (—).  I believe it's (char)0x2014.
    [edited]... the correct syntax is [char]0x2014.
    I wish to eliminate the em dash in the file name but I can't seem to find anything on the web about replacing em dashes.  When I paste '—', PowerShell replaces it with a '-'.
    I found this neat function that does a great job replacing multiple characters within a string.
    http://powershell.com/cs/blogs/tobias/archive/2011/04/28/multiple-text-replacement-challenge.aspx
    I am using the below code for my string replacement.
    Thank you for your help.
    function Replace-Text {
    param(
    [Parameter(Mandatory=$true)]
    $text,
    $replacementlist = "(-,,',,%,,$,,@,,#,,&,,’,"
    Invoke-Expression ('$text' + -join $(
    foreach($e in $replacementlist.Split(',')) {
    '.Replace("{0}","{1}")' -f $e, $(
    [void]$foreach.MoveNext()
    $foreach.Current)
    $path = '<path>'
    Get-ChildItem -Path $path | Rename-Item -NewName {(Replace-Text $_.Name).trim()}

    Here is a simple filter that will strip out all nonprintable chanracters.
    $newname=$file.Name -replace '[^a-zA-Z\.]'
    I just tested it on Win 7 which supports has a Unicode filesystem and it successfullstrips the bad characters.
    We also need to do this on files uploaded to SharePoint and OneDrive.
    The ~ and other similar characters are not allowed in may systems.  You should keep a translation log and tag all renamed files with some obvious tag.
    ¯\_(ツ)_/¯

  • How to set ApplicationIntent=ReadOnly in Connection String for SharePoint 2013

    SharePoint 2013 and SQL Server 2012 allows us some additional options to create HA and DR sites through AlwaysOn Availablibity Groups and Listeners.  Problem that I'm having is that I have a DR site that is at a different location.  Microsoft
    recommends not to stretch the farm across different locations, so I've created a separate farm for DR.  I have my content database in an Availability Group so that is Asynchronously commits data changes across the 2 locations.  My DR site
    connects to the content database through a Listener. 
    Since the DR site is connecting to the content database through the Listener, it is connecting the primary replica.  In order to connect to the Read Only secondary replica, I need to add "ApplicationIntent=ReadOnly"
    to the connection string.  How do you do that?

    It supports a secondary being Readable, that is all it is telling you. It does not support, nor implement, Read-Intent. This is expected behavior. You can look at the Conn Strings via PowerShell, of course:
    $db = get-spdatabase | where {$_.TypeName -like "*Config*"}
    $db.DatabaseConnectionString
    Data Source=SPSQL;Initial Catalog=Config;Integrated Security=True;Enlist=False;
    Pooling=True;Min Pool Size=0;Max Pool Size=100;Connect Timeout=15
    Trevor Seward
    Follow or contact me at...
    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • Calling powershell script from a batch file

    Hello All,
    I have a batch script that calls a powershell script. Before calling the script I set the execution policy to unrestricted, but when it gets to the line that calls the batch script i still get the confirmation in the command window: "Do you want to
    perform this operation" I then have to press Y for the PS script to run and then my batch script finishes.
    Does anyone know the setting I need to change in order to suppress the confirmation?
    Note: this is Windows 8, see code below
    set THIS_DIR=%~dp0
    powershell Set-ExecutionPolicy unrestricted
    powershell %THIS_DIR%MyScript.ps1 "param1"

    I may sound like a jerk but you really want to look at PowerShell.exe /?
    PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
        [-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
        [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
        [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
        [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
        [-Command { - | <script-block> [-args <arg-array>]
                      | <string> [<CommandParameters>] } ]
    PowerShell[.exe] -Help | -? | /?
    -PSConsoleFile
        Loads the specified Windows PowerShell console file. To create a console
        file, use Export-Console in Windows PowerShell.
    -Version
        Starts the specified version of Windows PowerShell.
        Enter a version number with the parameter, such as "-version 2.0".
    -NoLogo
        Hides the copyright banner at startup.
    -NoExit
        Does not exit after running startup commands.
    -Sta
        Starts the shell using a single-threaded apartment.
        Single-threaded apartment (STA) is the default.
    -Mta
        Start the shell using a multithreaded apartment.
    -NoProfile
        Does not load the Windows PowerShell profile.
    -NonInteractive
        Does not present an interactive prompt to the user.
    -InputFormat
        Describes the format of data sent to Windows PowerShell. Valid values are
        "Text" (text strings) or "XML" (serialized CLIXML format).
    -OutputFormat
        Determines how output from Windows PowerShell is formatted. Valid values
        are "Text" (text strings) or "XML" (serialized CLIXML format).
    -WindowStyle
        Sets the window style to Normal, Minimized, Maximized or Hidden.
    -EncodedCommand
        Accepts a base-64-encoded string version of a command. Use this parameter
        to submit commands to Windows PowerShell that require complex quotation
        marks or curly braces.
    -File
        Runs the specified script in the local scope ("dot-sourced"), so that the
        functions and variables that the script creates are available in the
        current session. Enter the script file path and any parameters.
        File must be the last parameter in the command, because all characters
        typed after the File parameter name are interpreted
        as the script file path followed by the script parameters.
    -ExecutionPolicy
        Sets the default execution policy for the current session and saves it
        in the $env:PSExecutionPolicyPreference environment variable.
        This parameter does not change the Windows PowerShell execution policy
        that is set in the registry.
    -Command
        Executes the specified commands (and any parameters) as though they were
        typed at the Windows PowerShell command prompt, and then exits, unless
        NoExit is specified. The value of Command can be "-", a string. or a
        script block.
        If the value of Command is "-", the command text is read from standard
        input.
        If the value of Command is a script block, the script block must be enclosed
        in braces ({}). You can specify a script block only when running PowerShell.exe
        in Windows PowerShell. The results of the script block are returned to the
        parent shell as deserialized XML objects, not live objects.
        If the value of Command is a string, Command must be the last parameter
        in the command , because any characters typed after the command are
        interpreted as the command arguments.
        To write a string that runs a Windows PowerShell command, use the format:
            "& {<command>}"
        where the quotation marks indicate a string and the invoke operator (&)
        causes the command to be executed.
    -Help, -?, /?
        Shows this message. If you are typing a PowerShell.exe command in Windows
        PowerShell, prepend the command parameters with a hyphen (-), not a forward
        slash (/). You can use either a hyphen or forward slash in Cmd.exe.
    Hope that helps! Jason

  • PowerShell Script to get Memory\Available MBytes

    I have a SQL Agent job with 3 separate Operating System Command Steps.
    PowerShell.exe Get-Date
    PowerShell.exe Get-Counter "\\mmserver\Memory\Pages/sec" | Format-table -auto
    PowerShell.exe Get-Counter "\\myserver\Memory\Available MBytes" | Format-Table -auto
    The first two steps work fine.  The third fails.  I have tried reformatting the counter name in any number of ways including escaping the backslashes, adding single quotes around various pieces, and I tried creating a string variable for the counter
    name.
    The failure message varies a little depending on what I change but basically it seems to be trying to interpret "MBytes" as a separate parameter.  For example:
    The error information returned by PowerShell is: 'Get-Counter : A positional parameter cannot be found that accepts argument 'MBy  '
    Followed immediately in the log file with a second error on the remainder of the command string.
    The error information returned by PowerShell is: 'tes'.  At line:1 char:12  + Get-Counter <<<< 
    \\myserver\Memory\Available MBytes      + CategoryInfo          : InvalidArgument: (:) [Get-Counter], ParameterBindingException    '
    Other errors indicate the name of the counter is wrong in someway.  For example, I found I had to include the server name even though the script is running locally and it works find from the ISE.
    I appreciate any assistance :)
    Ray

    Here's what worked for me from a command prompt, though I'm not sure why you were seeing that behavior when the value appeared to be quoted properly. Maybe cmd.exe and/or SQL Server was stripping the quotes before sending the string to PowerShell.exe:
    PowerShell.exe "Get-Counter '\\myserver\Memory\Available MBytes' | Format-Table -auto"

  • Interacting with Powershell from Java

    Hi,
    I'm trying to run a Java application which creates a new powershell process on startup and then later on interacts with it multiple times. Calling powershell.exe and have it execute a single command and return the output works fine for me. The problem arises if I don't want the powershell process to immediately finish/exit but to stay open so I can write to its outputStream and receive results back from the inputStream.
    String input = "dir";
    String[] commandList = {"powershell.exe", "-Command", "dir"};
    ProcessBuilder pb = new ProcessBuilder(commandList);
    Process p = pb.start();
    if(input != null) { 
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
    writer.println(input);
    writer.flush();
    writer.close();
    //p.getOutputStream().close();
    Gobbler outGobbler = new Gobbler(p.getInputStream());
    Gobbler errGobbler = new Gobbler(p.getErrorStream());
    Thread outThread = new Thread(outGobbler);
    Thread errThread = new Thread(errGobbler);
    outThread.start();
    errThread.start();
    System.out.println("Waiting for the Gobbler threads to join...");
    outThread.join();
    errThread.join();
    System.out.println("Waiting for the process to exit...");
    int exitVal = p.waitFor();
    System.out.println("\n****************************");
    System.out.println("Command: " + "cmd.exe /c dir");
    System.out.println("Exit Value = " + exitVal);
    List<String> output = outGobbler.getOuput();
    input = "";
    for(String o: output) { 
    input += o;
    System.out.println("Final Output:");
    System.out.println(input);
    This code returns the result of the "dir" command from a powershell - fine. But as you can see, I'm trying to run a second "dir" command using
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
    writer.println(input);
    writer.flush();
    This has no effect whatsoever - no second dir output is shown when I run my code. I've also experimented with a powershell.exe option to open the powershell but not close it immediately:
    String[] commandList = {"powershell.exe", "-NoExit", "-Command", "dir"};
    But then my code hangs, meaning the Gobbler's who consume the process's inputStream don't read anything - strangely enough: they don't even read the first line - there must be at least some output....
    I've also tried to close the process's outputStream after writing the second "dir" command to it - didn't change anything.
    But when I initially call the cmd.exe using the /k (keep open) switch:
    String[] commandList = {"cmd.exe", "/k", "dir"};
    I can then still write to that outputstream and invoke the second "dir" command and get the output of both "dir" commands from the inputstream fo that process.
    Any help is highly appreciated.
    Thanks
    Kurt

    user4491593 wrote:
    BUT: my Gobblers only read the output of all my commands Then why don't change your Gobbler code ? ;)
    Test this, it's ugly and needs improvemens, but by now works fine on linux and windows:
    public class Gobbler implements Runnable {
        private PrintStream out;
        private String message;
        private BufferedReader reader;
        public Gobbler(InputStream inputStream, PrintStream out) {
            this.reader = new BufferedReader(new InputStreamReader(inputStream));
                   this.out = out;
            this.message = ( null != message ) ? message : "";
        public void run() {
            String line;
            try {
                while (null != (line = this.reader.readLine())) {
                    out.println(message + line);
                this.reader.close();
            } catch (IOException e) {
                System.err.println("ERROR: " + e.getMessage());
    public class PowerConsole {
        private ProcessBuilder pb;
        Process p;
        boolean closed = false;
        PrintWriter writer;
        PowerConsole(String[] commandList) {
            pb = new ProcessBuilder(commandList);
            try {
                p = pb.start();
            } catch (IOException ex) {
                throw new RuntimeException("Cannot execute PowerShell.exe", ex);
            writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
            Gobbler outGobbler = new Gobbler(p.getInputStream(), System.out);
            Gobbler errGobbler = new Gobbler(p.getErrorStream(), System.out);
            Thread outThread = new Thread(outGobbler);
            Thread errThread = new Thread(errGobbler);
            outThread.start();
            errThread.start();
        public void execute(String command) {
            if (!closed) {
                writer.println(command);
                writer.flush();
            } else {
                throw new IllegalStateException("Power console has ben closed.");
        public void close() {
            try {
                execute("exit");
                p.waitFor();
            } catch (InterruptedException ex) {
        public static void main(String[] args) throws IOException, InterruptedException {
            /*   PowerConsole pc = new PowerConsole(new String[]{"/bin/bash"});
            PowerConsole pc = new PowerConsole(new String[]{"/bin/bash"});
            pc.execute("pwd");
            pc.execute("ls");
            pc.execute("cd /");
            pc.execute("ls -l");
            pc.execute("cd ~");
            pc.execute("find . -name 'test.*' -print");
            pc.close();
            //      PowerConsole pc = new PowerConsole(new String[]{"cmd.exe"});
            PowerConsole pc = new PowerConsole(new String[]{"powershell.exe", "-NoExit", "-Command", "-"});
            System.out.println("========== Executing dir");
            pc.execute("dir");
            System.out.println("========== Executing cd\\");
            pc.execute("cd \\"); Thread.sleep(2000);
            System.out.println("========== Executing dir");
            pc.execute("dir"); Thread.sleep(2000);
            System.out.println("========== Executing cd \\temp");
            pc.execute("cd \\temp"); Thread.sleep(2000);
            System.out.println("========== Executing dir");
            pc.execute("dir"); Thread.sleep(2000);
            System.out.println("========== Executing cd \\bubba");
            pc.execute("cd \\bubba"); Thread.sleep(2000);
            System.out.println("========== Exiting .... bye.");
            pc.close();
    }I tested this and there is still a little problem -look at the test below.
    It seems that when thecommand
    executed in the powershell prints only a one ot two lines,
    powershell doesn't flush the output stream
    .... but this rather problem of powershell, not the java code
    I have not a clue how to force powershell to flush
    it's output stream after each command.
    C:\temp>java -jar PowerShell.jar
    ========== Executing dir
        Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp
    Mode                LastWriteTime     Length Name
    -a---        2012-01-09     01:16       5290 PowerShell.jar
    ========== Executing cd\
    ========== Executing dir
        Directory: Microsoft.PowerShell.Core\FileSystem::C:\
    Mode                LastWriteTime     Length Name
    d----        2012-01-08     02:56            61587b977687a6e22fbe
    d----        2011-12-14     03:19            Documents and Settings
    d----        2011-12-15     00:05            oraclexe
    d-r--        2012-01-08     03:44            Program Files
    d----        2012-01-05     19:59            sqldeveloper
    d----        2012-01-09     01:15            temp
    d----        2012-01-09     01:13            WINDOWS
    -a---        2011-12-14     03:12          0 AUTOEXEC.BAT
    -a---        2011-12-14     03:12          0 CONFIG.SYS
    ========== Executing cd \temp
    ========== Executing dir
        Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp
    Mode                LastWriteTime     Length Name
    -a---        2012-01-09     01:16       5290 PowerShell.jar
    ========== Executing cd \bubba
    Set-Location : Cannot find path 'C:\bubba' because it does not exist.
    At line:1 char:3
    + cd  <<<< \bubba
    ========== Exiting .... bye.
    C:\temp>

  • How to recognize string in txt file and set it as variable

    Hi, 
    I have txt file and somwhere in it string starting with:
    data directory....:
    How (using batch file) find it in the text, read and set the value as a variable? I mean the string is:
    data directory....: c:\datadir
    where what I mean value is  in this case "c:\datadir". So I want batch file to read the txt file, find string starting with "data directory....:" and then set "c:\datadir" as a variable. 
    Best, mac

    It's not very intuitive to do this sort of thing in a batch file. If you have the option to use PowerShell instead, I'd highly recommend it. It's the new way for performing command-line tasks in Windows, and there's no need to struggle with the old command
    prompt anymore.
    Here are PowerShell and batch examples of doing this type of string parsing:
    # PowerShell:
    $dataDirectory = Get-Content .\test.txt |
    ForEach-Object {
    if ($_ -match '^\s*data directory\.*:\s*(.+?)\s*$')
    $matches[1]
    break
    $dataDirectory
    # Batch file:
    @echo off
    setlocal EnableDelayedExpansion
    set DATA_DIRECTORY=
    for /F "tokens=1,* delims=:" %%a in (test.txt) do (
    set PROPERTY=%%a
    set PROPERTY=!PROPERTY:~0,14!
    if /I "!PROPERTY!" equ "data directory" (
    set DATA_DIRECTORY=%%b
    :RemovingSpaces
    if "%DATA_DIRECTORY:~0,1%" neq " " goto :SpacesRemoved
    set DATA_DIRECTORY=%DATA_DIRECTORY:~1%
    goto :RemovingSpaces
    :SpacesRemoved
    echo %DATA_DIRECTORY%
    endlocal

  • PowerShell Test-connection and Active Directory Input

    I am just learning powershell, and I"m working to write a script that pulls computer names from AD and puts them into a Test-connection cmdlet to determine if its valid.
    clear-host
    import-module activedirectory
    $workstations = Get-ADComputer -Filter '*' -SearchBase "OU=CMSD,OU=Windows XP,OU=Workstations,DC=TECH,DC=LOCAL" | FT Name
    Foreach($w in $workstations)
    Test-Connection -ComputerName $w -Count 1
    when i run the script, i receive the following error for all entries:
    Test-Connection : Testing connection to computer 'Microsoft.PowerShell.Commands.Internal.Format.GroupEndData' failed: The requested name is valid, but no data of the requested type was found
    At line:6 char:24
    + Test-Connection <<<< -computername $w -Count 1
    + CategoryInfo : ResourceUnavailable: (Microsoft.Power...at.GroupEndData:String) [Test-Connection], PingException
    + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand
    I'm thinking that when the array is going into the Test-connection cmdlet, its adding string characters such as "name=computer" and not just the computer name.  I don't know how to edit strings in powershell.  
    any help is appreciated, thank you.

    When you return a computer you get multiple properties - DN, Name, SID, etc. You need to indicate what property you want using dotted notation.
    Test-Connection -ComputerName $w.Name -Count 1
    You can also only return the Name when you do your Get-ADComputer by piping it to Select-Object. If you do this option, your variable would not need the dotted notation (.Name). $w is all you would need, since it would only contain the Name property.
    Get-ADComputer -Filter * -SearchBase ... | select Name
    Oh my, I just realized you are piping this to Format-Table - get rid of that! Do one of the two options above and you should have this figured out. Doing a select may be the best option since you will be returning a smaller set of information.

  • Powershell search for a word and use the next word

    Here is the skinny.  I am trying to easily part through a event log of print jobs.  I export it to a CSV, grab only the events that pertain to what I need but I am stuck there.  Here is a sample of what I need help with.
    Microsoft Word - Test Print owned by user1 on computer1 was printed on printer1 through port
    Obviously document name, user1, computer1 and printer1 will be different in almost every case.  How do I parse through this and grab the username, computer and printer.  I was thinking search for "owned by", but how do I grab the name?
    Thanks for the help.

    ok now I am running into another issue.  Apparently the nuances of splitting by word seems to be los on me.
    when I do
    foreach ($job in $printjob) {        $test = $job.split("owned by")        echo $test}
    It will then split the line by each and ever "o", "w", "n", "e", "d", etc.....  I even tried $test = $job.split("'owned by'").  Any ideas?
    I feel like I should explain why this is happening.
    When you call $job.Split(), you're calling the .NET Split() method of the object System.String.
    If you look at the overloads of split (i.e., all the different ways you can call String.Split) - link here https://msdn.microsoft.com/en-us/library/system.string.split%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 -,
    you'll notice that the only way of calling String.Split() with a single parameter is if you pass a char[], an array of characters.
    Now, if you were coding in C# or VB.NET and you did... String.Split("owned by"), you'd get an error saying that it's expecting a char[] but you gave it a string.
    Powershell however is a bit 'smarter' and it tries to accommodate... It knows that the method expects a char[] and it knows you gave it a string, but it also knows how to convert it to a char[], so it does that, and that's what the method String.Split()
    receives.
    And what happens when the method String.Split() receives a char[]? It splits on every single character in that char[], as you've seen :)
    How to fix it? Well, there are two overloads that accept a string[], so you can use those. Now here's an interesting fact...
    In the same way that PowerShell converted a string to a char[] to accommodate the needs of the method you were calling, it can also convert a string into a string[], so you could do this:
    $job.Split("owned by", [System.StringSplitOptions]::None)
    You're passing it a string... and a [StringSplitOptions] object, so you expect it to call the third overload from the page I provided earlier.
    But if you run it... you still get the same stuff as before! What gives?
    Well, seeing as in this particular case there is an overload that receives char[] and another that receives string[] and you passed a string, which means PowerShell will always have to convert it into something anyway... You have no control
    over what PowerShell will decide to convert the string to. It could convert to char[] or to string[]. In this case, because the definition of the char[] method appears before the string[], that gets picked.
    So, finally... how to force PowerShell to pick the string[] overload? Well, don't give it a choice!
    $job.Split([string[]] "owned by", [System.StringSplitOptions]::None)
    So here I'm casting the string into a string[] before it gets passed to the method, so PowerShell does not need to perform any conversion itself and everything is right with the world.
    Hope this helps :)

  • Run PowerShell Script from a Event Receiver

     Hi,
    Just looking around on the net for some documentation for running a PowerShell script via an Event Receiver. We want to be able to make changes to the script and not change anything in the ER.
    Sadly using a workflow isn't an option here.
    Looking for websites that give some examples really, or if anyone has done this.
    Regards
    If this is helpful please mark it so. Also if this solved your problem mark as answer.

    Hi TemPart:
    string cmdArg = “C:\\Scripts\\test.ps1″;
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(cmdArg);
    Collection [PSObject] results = pipeline.Invoke(); // please Update [] bracket with less then and greater then bracket
    runspace.Close();
    Had to modify this slightly:
    string cmdArg = “Powershell.exe -file C:\\Scripts\\test.ps1″;
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(cmdArg);
    Collection [PSObject] results = pipeline.Invoke(); // please Update [] bracket with less then and greater then bracket
    runspace.Close();
    If this is helpful please mark it so. Also if this solved your problem mark as answer.

  • Hot to run "Deploy WSP" file through sharepoint Powershell from C# win Application

    HI All,
         I have create one web part (wsp) and also i have created one window application for deploy wsp file through powershell commands but i am stuck in executing the commands from powershell from c# win app .please let me know any have idea about
    this  ?
    Software developer

    Hi,
    The following code snippet for your reference:
    public string RunPowershell(string powershellText, SPWeb web, string param1, string param2)
    // Powershell ~= RunspaceFactory - i.e. Create a powershell context
    var runspace = RunspaceFactory.CreateRunspace();
    var resultString = new StringBuilder();
    try
    // load the SharePoint snapin - Note: you cannot do this in the script itself (i.e. add-pssnapin etc does not work)
    PSSnapInException snapInError;
    runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out snapInError);
    runspace.Open();
    // set a web variable.
    runspace.SessionStateProxy.SetVariable("webContext", web);
    // and some user defined parameters
    runspace.SessionStateProxy.SetVariable("param1", param1);
    runspace.SessionStateProxy.SetVariable("param2", param2);
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(powershellText);
    //add a "return" variable
    pipeline.Commands.Add("Out-String");
    var results = pipeline.Invoke();
    //convert the script result into a single string
    foreach (PSObject obj in results)
    resultString.AppendLine(obj.ToString());
    finally
    // close the runspace
    runspace.Close();
    // consider logging the result. Or something.
    return resultString.ToString();
    More information:
    Running Powershell from within SharePoint
    http://geekswithblogs.net/Norgean/archive/2012/09/19/running-powershell-from-within-sharepoint.aspx
    Best Regards
    Dennis Guo
    TechNet Community Support

  • Read a CSV file and dynamically generate the insert

    I have a requirement where there are multiple csv's which needs to be exported to a sql table. So far, I am able to read the csv file and generate the insert statement dynamically for selected columns however, the insert statement when passed as a parameter
    to the $cmd.CommandText
    does not evaluate the values
    How to evaluate the string in powershell
    Import-Csv -Path $FileName.FullName | % {
    # Insert statement.
    $insert = "INSERT INTO $Tablename ($ReqColumns) Values ('"
    $valCols='';
    $DataCols='';
    $lists = $ReqColumns.split(",");
    foreach($l in $lists)
    $valCols= $valCols + '$($_.'+$l+')'','''
    #Generate the values statement
    $DataCols=($DataCols+$valCols+')').replace(",')","");
    $insertStr =@("INSERT INTO $Tablename ($ReqColumns) Values ('$($DataCols))")
    #The above statement generate the following insert statement
    #INSERT INTO TMP_APPLE_EXPORT (PRODUCT_ID,QTY_SOLD,QTY_AVAILABLE) Values (' $($_.PRODUCT_ID)','$($_.QTY_SOLD)','$($_.QTY_AVAILABLE)' )
    $cmd.CommandText = $insertStr #does not evaluate the values
    #If the same statement is passed as below then it execute successfully
    #$cmd.CommandText = "INSERT INTO TMP_APL_EXPORT (PRODUCT_ID,QTY_SOLD,QTY_AVAILABLE) Values (' $($_.PRODUCT_ID)','$($_.QTY_SOLD)','$($_.QTY_AVAILABLE)' )"
    #Execute Query
    $cmd.ExecuteNonQuery() | Out-Null
    jyeragi

    Hi Jyeragi,
    To convert the data to the SQL table format, please try this function out-sql:
    out-sql Powershell function - export pipeline contents to a new SQL Server table
    If I have any misunderstanding, please let me know.
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna
    TechNet Community Support

Maybe you are looking for

  • How do you change the connection of an existing report?

    I have a series of reports that I have to change the database connection. We had a database go down and I recovered onto our development database and am pointing the production servers to that database. I need to change our custom reports which are b

  • Remove decimal from Line Chart

    I am using custom XML for line chart to control thresholds. On X axis , I want to specify % instead of decimal value. How can I achieve it? I changed the below : <format><![CDATA[{%Name}{enabled:True} - {%Value}{numDecimals:0}%]]></format> But it doe

  • Getting error [Program Terminated] while doing GR postings

    Dear All, Please help me out from this error. I get this error when I am going to do GR postings. Error Message is " Message_Type_X " short dump has not been completely stored. How I solve this error. Please help me. Thanks & Regards Prateek

  • Windows Server 2008 R2 - Trial Version Activation Error

    I downloaded a trial of Windows Server 2008 R2 a few months ago.  I may have loaded the ISO onto another PC for testing, but the testing is no longer active.  However,  I am testing a new environment where I need to load Server 2008 R2 onto 2 differe

  • Printing PDF files in batch to user default printer.

    Hi, My recuirement is something like this: I had to print 'n' number of PDF files sotred in Database. Problem is that I had to print all of these files to default printer attached to my website's user desktop. The printing should happen without openi