Doug Maurer

Forum Replies Created

Viewing 15 posts - 1 through 15 (of 480 total)
  • Author
    Posts
  • in reply to: coding problems with Powershell script #247510
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    Are you trying to actually update the file? In it’s current form, it will only edit that line in memory. The previous answer should help you get the modified line in the variable. Here are two examples of how you can modify the line and update the file. For the sake of other readers I have provided a test text file.

    $file = "C:\temp\textfile.txt"
    
    @'
    some text
    Home-NR.:
    more text
    '@ | Out-File $file -Encoding utf8
    
    $insert = Get-Content -path $file -Encoding utf8
    
    $insert = $insert | Foreach {
        $_ -replace 'Home-Nr.:', “MainStreet Home-Nr.: 83”
    }
    
    $insert | Out-File $file -Encoding utf8
    $file = "C:\temp\textfile.txt"
    
    @'
    some text
    Home-NR.:
    more text
    '@ | Out-File $file -Encoding utf8
    
    $insert = Get-Content -path $file -Encoding utf8
    
    $insert -replace 'Home-Nr.:', “MainStreet Home-Nr.: 83” | Out-File $file -Encoding utf8
    in reply to: Get-NetIPConfiguration on Powershell V2 #247005
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    How can I delete this?

    in reply to: Help with my PowerShell Form #246894
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    So you’re trying to start the entire script with different credentials and then a third set of creds for the scripts the buttons invoke? May be a bit much for a forum. It seems like you’re on the right track so keep at it and come back if you hit another snag.

    Your syntax works fine. You should be able to start this script as you specified and then pass more credentials along. One correction, if it’s saved to $env:temp under the one user then it may not be accessible to the second user. Be sure to move it to a location that the users have access to. My apologies for overlooking that.

    in reply to: Get-WindowsFeature but with Powershell Version 2 #246804
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    Like @Olaf said, efforts should be spent on newer versions of powershell. If you are looking for alternatives, DISM can also enable features starting with Windows 8/2012.

    https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/enable-or-disable-windows-features-using-dism

    in reply to: Help with my PowerShell Form #246762
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    Hello Ogheneotsuko,

    First, you don’t want to run a form in a background job. The UI is the main thread intended for user interaction. This is likely why you are not seeing it in regular powershell. Powershell_ise.exe does some magic so always be sure to test in the real console.

    Second, if you are intending to use the credential on the start-process command, you’ll simply add the creds there. I’ve updated your script to remove the background job, create a small powershell script in $env:temp, and set Start-Process to run powershell.exe with the created script as an argument.

    Put in different valid credentials than the ones calling so you can see the output show you the credentials are passed along and being used.

    @'
    whoami
    pause
    '@ | Out-File $env:temp\hello.ps1 -Encoding ascii -Force
    
    $cred = Get-Credential
    
    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing
    $form = New-Object System.Windows.Forms.Form
    $form.Text = 'CNR Tools’
    $form.Size = New-Object System.Drawing.Size(900,600)
    $form.StartPosition = 'CenterScreen'
    $form.AutoSize = $true
    $form.MaximizeBox = $false
    $form.FormBorderStyle = 'FixedSingle'
    
    $img = [System.Drawing.Image]::Fromfile("c:\users\$env:username\Pictures\logo.png")
    $pictureBox = New-Object Windows.Forms.PictureBox
    $pictureBox.Width = $img.Size.Width
    $pictureBox.Height = $img.Size.Height
    $pictureBox.Location = New-Object System.Drawing.Size(600,465)
    $pictureBox.Image = $img
    $form.controls.add($pictureBox) 
    
    $ADUCButton = New-Object System.Windows.Forms.Button
    $ADUCButton.Location = New-Object System.Drawing.Point(10,25)
    $ADUCButton.Size = New-Object System.Drawing.Size(300,100)
    $ADUCButton.Font = New-Object System.Drawing.Font(“Times New Roman”,14, [System.Drawing.Fontstyle]::Bold) 
    $ADUCButton.Text = ' Active Directory Users and Computers '
    $ADUCButton.Add_Click({Start-Process -filepath "powershell.exe" -WindowStyle maximized -Credential $cred -ArgumentList $env:temp\hello.ps1})
    $ADUCButton.FlatAppearance.BorderColor = [System.Drawing.Color]::DarkBlue
    $ADUCButton.BackColor = [System.Drawing.Color]::CornflowerBlue
    $form.Controls.Add($ADUCButton)
    
    $label = New-Object System.Windows.Forms.Label
    $label.location = New-Object System.Drawing.Point(100,500)
    $label.Size = New-Object System.Drawing.Size(280,70)
    $label.Font = New-Object System.Drawing.Font("Lucida Console",8, 
    [System.Drawing.FontStyle]::Italic)
    $label.Text = 'Created by a PowerShell Novice'
    $form.Controls.Add($label)
    
    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Point(850,300)
    $CancelButton.Size = New-Object System.Drawing.Size(75,23)
    $CancelButton.Text = 'Close'
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $form.CancelButton = $CancelButton
    $form.Controls.Add($CancelButton)
    
    $result = $form.ShowDialog()
    
    if ($result -eq [System.Windows.Forms.DialogResult]::OK)
    {
    $x = $listBox.SelectedItems
    $x
    }
    
    in reply to: Get-Acl – Separate output columns #246582
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    Access is made up of several properties. Format-Table is showing you a friendly view of a few of those properties. If you run this, you can see all of them.
    Get-Acl -Path C:\path | select -ExpandProperty Access
    Output

    $acl.Access
    
    FileSystemRights  : FullControl
    AccessControlType : Allow
    IdentityReference : BUILTIN\Administrators
    IsInherited       : True
    InheritanceFlags  : None
    PropagationFlags  : None
    
    FileSystemRights  : FullControl
    AccessControlType : Allow
    IdentityReference : NT AUTHORITY\SYSTEM
    IsInherited       : True
    InheritanceFlags  : None
    PropagationFlags  : None
    
    FileSystemRights  : ReadAndExecute, Synchronize
    AccessControlType : Allow
    IdentityReference : BUILTIN\Users
    IsInherited       : True
    InheritanceFlags  : None
    PropagationFlags  : None
    
    FileSystemRights  : Modify, Synchronize
    AccessControlType : Allow
    IdentityReference : NT AUTHORITY\Authenticated Users
    IsInherited       : True
    InheritanceFlags  : None
    PropagationFlags  : None

    By default, powershell displays objects with 5 or more members as a list like shown. If you want to coerce it to show table, just select the columns you want to see. Four or less will be a table.

    Get-Acl C:\Path | Select -ExpandProperty Access | Select IdentityReference,FileSystemRights,AccessControlType
    Output

    IdentityReference                           FileSystemRights AccessControlType
    -----------------                           ---------------- -----------------
    BUILTIN\Administrators                           FullControl             Allow
    NT AUTHORITY\SYSTEM                              FullControl             Allow
    BUILTIN\Users                    ReadAndExecute, Synchronize             Allow
    NT AUTHORITY\Authenticated Users         Modify, Synchronize             Allow

    You may also consider using calculated properties to show friendlier columns

    Get-Acl .\aabc.ics | select -ExpandProperty Access | Select @{N="Target Identity";E={$_.IdentityReference}},@{N="Filesystem Rights";E={$_.FileSystemRights}},AccessControlType

    By the way, Format-Table is fine if you’re just viewing the information in an interactive session and it’s the last command in the pipeline. You can’t use the output from the Format-* cmdlets, such as Sort, Group, or Select. Also, if you try to Format-Table on the Access property, it’s also not pleasing to the eyes.

    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    Well at least he shared his solution from his cross posting. I was able to edit his formatting there. Oh well here is just another way in case someone needs it. I’m going to guess it’s much faster than the select-object method on very large datasets.

    Please note the phrase BACKTICKGOESHERE – replace it with the backtick character. I’m not sure how to escape it in this forum.

    $jobfile    = "ps_job.dat"
    $metafile   = "ps_job_metdata.dat"
    $outputfile = "some_file.csv"
    
    $meta = ((Get-Content $metafile -First 1 -Encoding UTF8) -split '\|').Trim('"')
    
    Class ColumnSelector : System.Collections.Specialized.OrderedDictionary {
    
        Select($line,$meta)
        {
            $meta | foreach{$this.add("$_",(iex "BACKTICKGOESHERE$line.$_"))}
        }
        ColumnSelector($line,$meta)
        {
            $this.select($line,$meta)
        }
    }
    
    import-csv $jobfile -Delimiter '|' | 
        foreach{[pscustomobject]([columnselector]::new($_,$meta))} | 
            Export-CSV $outputfile -Encoding UTF8 -NoTypeInformation -Delimiter '|'
    

    Output

    Get-Content $outputfile
    "empid"|"name"|"zipcode"|"salary"
    "1"|"Tom"|"11111"|"1000"
    "2"|"Ann"|"22222"|"2000"

    There has to be a simpler solution.

    • This reply was modified 6 days, 5 hours ago by Doug Maurer.
    • This reply was modified 6 days, 5 hours ago by Doug Maurer.
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    You may collect all the errors using the -ErrorVariable parameter.
    $folders = get-childitem $dir -Directory -Force -Recurse -ErrorVariable Errors
    In the end $Errors will contain all the gci errors.

    in reply to: Dynamic Variables and Runspaces #246231
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    I see your variable turned into a string,

    my mistake. 🙂

    It seems the ideas have helped nonetheless.

    Glad you got it working!

    in reply to: Nested Foreach in PowerShell #246207
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    I’m not sure your code is doing anything other than combining all VMs with all clusters. Maybe this is what you’re looking for?

    
    foreach($vm in (get-vm))
    {
        get-vmhost -vm $vm | foreach{
            [pscustomobject][Ordered]@{
                VM      = $vm.name
                Host    = $_.name
                Cluster = $_.parent
            }
        }
    }
    
    in reply to: Dynamic Variables and Runspaces #246177
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    You need to provide a string to New-Variable, not a variable, so remove the dollar sign. Here’s an example of how to create, capture, and manipulate dynamic variables.

    
    # Create variables, capturing them in another variable to easily reference
    $variables = 1..6 | foreach {
        New-Variable -Name UniqueName$_ -Value @{Number=$_;Date=Get-Date;Script="Write-Host $_ -foreground cyan"} -PassThru
    }
    
    # Use the variables
    $variables | foreach {
        "This variable is named {0} and its number is {1}" -f $_.name,$_.value.number
    }
    
    # Use one like a normal variable
    $UniqueName1
    
    # Get the variables if not already captured
    $variables = 1..6 | foreach {Get-Variable -Name UniqueName$_}
    
    # Get all the values of the variables
    1..6 | foreach {Get-Variable -Name UniqueName$_ -ValueOnly}
    
    # Use the properties
    $variables.value | foreach {& $([scriptblock]::create($_.script))}
    
    # Remove the variables
    $variables | Remove-Variable
    
    # or 
    1..6 | foreach {
        Remove-Variable -Name "UniqueName$_"
    }
    

    Hope it helps

    in reply to: remove element from xml file #246156
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    It does work in my tests, except it gets rid of the first entry. Your data has spaces in it so try this.

    
    Compare-Object -IncludeEqual -ReferenceObject $oldArray -DifferenceObject $newarray | Where-Object -FilterScript {
    
    #if($_.SideIndicator -eq "=>"){Write-Host "New Object - " $_.InputObject}
    if($_.SideIndicator -eq "<="){
    $w=$_.InputObject
    $file_data.SelectSingleNode("//genre[text()='$w']") | foreach {[void]$_.parentnode.removechild($_)}
    #Write-Host "Remove Object - $w"
    }
    
    }
    $file_data.genre
    in reply to: Posts are Broken #245985
    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    I was just coming to make the same complaint. I can’t see all the text on the posts. It’s been like that on mobile for a long while, and as Rob said just the last few days everywhere else. The site has been offline off and on as well as slow, which I assume you guys are already aware of.

    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    Giggle. Henceforth, Krzy Doug shall be addressed as Dough

    All my life.. by mistake and on purpose…

    Participant
    Topics: 4
    Replies: 480
    Points: 1,754
    Helping Hand
    Rank: Community Hero

    Hi Krish,

    I apologize for not being clear enough. What I’m saying is, show us your attempts. You have addressed the forum as Team, asking for help achieving your goal.. but haven’t showed us what you’ve tried. I, at least personally, will assume that you haven’t tried anything based on your request. I’m simply asking you to put in at least the same amount of effort in figuring this out yourself that many of us are willing to put in helping you. What have you tried? Where is it going wrong?

    Hopefully this conveys the meaning of my words better.

Viewing 15 posts - 1 through 15 (of 480 total)