Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

All PS scripts in windows scheduler suddenly don't work anymore

$
0
0

I have four PS scripts executed daily by windows scheduler and suddenly two weeks ago all stopped working. I checked also if windows (7 home premium) installed new updates, but there was only windows essential updates. All the scripts work if executed manually, but now any PS script executed through windows scheduler fails always, I can't find any error anywhere, just the result of the task is 0x1 without a message.

I have created also a test script:

write-host (get-date) "This is a test"

and the "action" of the task is:

Program/script: powershell.exe
Add arguments: -c .\test.ps1

And it fails too, but two weeks ago they were all working. I'm quite sure about the day that they stopped working because I save the script output in a log file with the following technique:

Program/script: powershell.exe
Add arguments: -c "powershell -c .\test.ps1 2>&1 >> .\test.log"

And the last entry in the log files is dated 05/17/2016, so since then all the scripts fail and I can't find the reason, I looked also in the event viewer and activated the task history, but nothing, no errors. I can't find anywhere an error, a clue that can point me in the right direction. At this point I would appreciate some help because I am out of ideas.

Thanks in advance.


PowerShell 3.0 - Conditional operator wrong behaviour!??

$
0
0

Hi there! I am a VS C# programmer. Now I am learning PowerShell 3.0

During learning, I tried to make a block of codes for identifying input number's type. The code is:

#Starting of block

cls
$a = Read-Host 'Ínput'
if ($a -gt 0) {
Write-Host 'The input is positive'}
elseif ($a -eq 0) {
Write-Host 'The input is zero'}
else {
Write-Host 'The input is negative'}

#Ending of block

Unfortunately, the output is:

-----------------------------------

Ínput: 5
The input is positive

-----------------------------------

Ínput: 0
The input is zero

-----------------------------------

Ínput: -2
The input is positive

PS C:\Users\Admin> $a
-2

-----------------------------------

Ínput: .8
The input is negative

PS C:\Users\Razib> $a
.8

-----------------------------------

I am totally confused! I understand that I am missing some conditional operator's behavior pattern knowledge.

Can someone please help me out about it?

Regards.

need help with powershell command

$
0
0

hello .

i want to add to a multiple ad groups a multiple ad users with powershell command.

how can i do this in the esaly way?

i try this but itsn't works

$groups=Import-Csv C:\groups.csv
$users= Get-Content C:\Users.txt


foreach ($grp in $groups)
{

(Get-ADGroup -Identity $grp -members $users) 
}

10x for the help!


PS beginner Help

$
0
0

I have been tasked with something that most of you can probably do in 2 minutes.

Here is what it is, I have a monitoring softaware that will run .bat or powershell scripts 

I have to create one or the other that will go out to a xxx.conf file on a diff windows server ... drill down into it looking for a specific line in a specific place. and if it finds it .. TRUE if not FALSE ... 

basically looking to see if a certain word turns up in a certain place in a file.

I know that probably very easy, but like i said I am 100% new to this.

Get-LocalGroupMembership - Script/Module Help

$
0
0

Sorry, I don't have access to pastebin at work (blocked) but I need some help with a module.  This is the closest that I have found to do what I need, but it is way more complicated than I have skill in powershell.

https://learn-powershell.net/2013/08/11/get-all-members-of-a-local-group-using-powershell/

The problem I am having is the module is not enumerating groups out side of the domain the servers it is being run against exist on.

For example:

Servera.sitea.com has two security groups, both with nested security groups and members.

When run I will get:

siteA/Group1

--siteA/Member1

--siteB/Member2

----siteA/Group2

------SiteA/Member3

------SiteA/Member4

SiteB/Group1

.

.

.

.

Nothing will be populated under the second domain's group.  I do have access, if i run a get-adgroupmember against the SiteB/Group1 it does return members.

The problem I believe is in the script.  There is a section where it strips the full name from the groups.  What I am thinking is that it strips the domain suffix before doing the lookup.  Then when it does a lookup of that security group on the default domain (SiteA) it can't resolve the (SiteB) group.  

That, or it is something similar to when you do a "Get-ADGroupMember" lookup.  If you are searching for an account on another domain you have to specify the -server switch and specify the other domain controller.  Would this need to be passed through some how for groups not found on the same domain?  Can it be specified manually?

Is there any way to correct this?  I am trying to run an audit on a hundred or so servers for who has administrator access.  I need to know who is in the base group, and who is inheriting admin access through sub/nested groups (while showing in the output which group they belong to).

Here is the section **I THINK** that the problem is stemming from.

----------------------------------------------------------------------------------------------------------------------------------

Function Get-DomainGroupMember {
                [cmdletbinding()]
                Param (
                    [parameter()]
                    $DomainGroup, 
                    [parameter()]
                    [string]$NTName, 
                    [parameter()]
                    [string]$blnNT
                )
                Try {
                    If ($blnNT -eq $True) {
                        # Convert NetBIOS domain name of group to Distinguished Name.
                        $objNT.InvokeMember("Set", "InvokeMethod", $Null, $Translate, (3, ("{0}{1}" -f $NetBIOSDomain.Trim(),$NTName)))
                        $DN = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $Translate, 1)
                        $ADGroup = [ADSI]"LDAP://$DN"
                    } Else {
                        $DN = $DomainGroup.distinguishedName
                        $ADGroup = $DomainGroup
                    }         
                    $Counter++   
                    ForEach ($MemberDN In $ADGroup.Member) {
                        $MemberGroup = [ADSI]("LDAP://{0}" -f ($MemberDN -replace '/','\/'))
                        New-Object PSObject -Property @{
                            Computername = $Computer
                            Name = $MemberGroup.name[0]
                            Type = 'Domain'
                            ParentGroup = $NTName
                            isGroup = ($MemberGroup.Class -eq "group")
                            Depth = $Counter
                        }
                        # Check if this member is a group.
                        If ($MemberGroup.Class -eq "group") {              
                            If ($Counter -lt $Depth) {
                                If ($Groups[$MemberGroup.name[0]] -notcontains 'Domain') {
                                    Write-Verbose ("{0}: Getting domain group members" -f $MemberGroup.name[0])
                                    $Groups[$MemberGroup.name[0]] += ,'Domain'
                                    # Enumerate members of domain group.
                                    Get-DomainGroupMember $MemberGroup $MemberGroup.Name[0] $False


----------------------------------------------------------------------------------------------------------------------------------

Here is the entire module:

----------------------------------------------------------------------------------------------------------------------------------
Function Get-LocalGroupMembership {
    <#
        .SYNOPSIS
            Recursively list all members of a specified Local group.

        .DESCRIPTION
            Recursively list all members of a specified Local group. This can be run against a local or
            remote system or systems. Recursion is unlimited unless specified by the -Depth parameter.

            Alias: glgm

        .PARAMETER Computername
            Local or remote computer/s to perform the query against.

            Default value is the local system.

        .PARAMETER Group
            Name of the group to query on a system for all members.

            Default value is 'Administrators'

        .PARAMETER Depth
            Limit the recursive depth of a query. 

            Default value is 2147483647.

        .PARAMETER Throttle
            Number of concurrently running jobs to run at a time

            Default value is 10

        .NOTES
            Author: Boe Prox
            Created: 8 AUG 2013
            Version 1.0 (8 AUG 2013):
                -Initial creation

        .EXAMPLE
            Get-LocalGroupMembership

            Name              ParentGroup       isGroup Type   Computername Depth
            ----              -----------       ------- ----   ------------ -----
            Administrator     Administrators      False Domain DC1              1
            boe               Administrators      False Domain DC1              1
            testuser          Administrators      False Domain DC1              1
            bob               Administrators      False Domain DC1              1
            proxb             Administrators      False Domain DC1              1
            Enterprise Admins Administrators       True Domain DC1              1
            Sysops Admins     Enterprise Admins    True Domain DC1              2
            Domain Admins     Enterprise Admins    True Domain DC1              2
            Administrator     Enterprise Admins   False Domain DC1              2
            Domain Admins     Administrators       True Domain DC1              1
            proxb             Domain Admins       False Domain DC1              2
            Administrator     Domain Admins       False Domain DC1              2
            Sysops Admins     Administrators       True Domain DC1              1
            Org Admins        Sysops Admins        True Domain DC1              2
            Enterprise Admins Sysops Admins        True Domain DC1              2       

            Description
            -----------
            Gets all of the members of the 'Administrators' group on the local system.        

        .EXAMPLE
            Get-LocalGroupMembership -Group 'Administrators' -Depth 1

            Name              ParentGroup    isGroup Type   Computername Depth
            ----              -----------    ------- ----   ------------ -----
            Administrator     Administrators   False Domain DC1              1
            boe               Administrators   False Domain DC1              1
            testuser          Administrators   False Domain DC1              1
            bob               Administrators   False Domain DC1              1
            proxb             Administrators   False Domain DC1              1
            Enterprise Admins Administrators    True Domain DC1              1
            Domain Admins     Administrators    True Domain DC1              1
            Sysops Admins     Administrators    True Domain DC1              1   

            Description
            -----------
            Gets the members of 'Administrators' with only 1 level of recursion.         

    #>
    [cmdletbinding()]
    Param (
        [parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [Alias('CN','__Server','Computer','IPAddress')]
        [string[]]$Computername = $env:COMPUTERNAME,
        [parameter()]
        [string]$Group = "Administrators",
        [parameter()]
        [int]$Depth = ([int]::MaxValue),
        [parameter()]
        [Alias("MaxJobs")]
        [int]$Throttle = 10
    )
    Begin {
        $PSBoundParameters.GetEnumerator() | ForEach {
            Write-Verbose $_
        }
        #region Extra Configurations
        Write-Verbose ("Depth: {0}" -f $Depth)
        #endregion Extra Configurations
        #Define hash table for Get-RunspaceData function
        $runspacehash = @{}
        #Function to perform runspace job cleanup
        Function Get-RunspaceData {
            [cmdletbinding()]
            param(
                [switch]$Wait
            )
            Do {
                $more = $false         
                Foreach($runspace in $runspaces) {
                    If ($runspace.Runspace.isCompleted) {
                        $runspace.powershell.EndInvoke($runspace.Runspace)
                        $runspace.powershell.dispose()
                        $runspace.Runspace = $null
                        $runspace.powershell = $null                 
                    } ElseIf ($runspace.Runspace -ne $null) {
                        $more = $true
                    }
                }
                If ($more -AND $PSBoundParameters['Wait']) {
                    Start-Sleep -Milliseconds 100
                }   
                #Clean out unused runspace jobs
                $temphash = $runspaces.clone()
                $temphash | Where {
                    $_.runspace -eq $Null
                } | ForEach {
                    Write-Verbose ("Removing {0}" -f $_.computer)
                    $Runspaces.remove($_)
                }             
            } while ($more -AND $PSBoundParameters['Wait'])
        }

        #region ScriptBlock
            $scriptBlock = {
            Param ($Computer,$Group,$Depth,$NetBIOSDomain,$ObjNT,$Translate)            
            $Script:Depth = $Depth
            $Script:ObjNT = $ObjNT
            $Script:Translate = $Translate
            $Script:NetBIOSDomain = $NetBIOSDomain
            Function Get-LocalGroupMember {
                [cmdletbinding()]
                Param (
                    [parameter()]
                    [System.DirectoryServices.DirectoryEntry]$LocalGroup
                )
                # Invoke the Members method and convert to an array of member objects.
                $Members= @($LocalGroup.psbase.Invoke("Members"))
                $Counter++
                ForEach ($Member In $Members) {                
                    Try {
                        $Name = $Member.GetType().InvokeMember("Name", 'GetProperty', $Null, $Member, $Null)
                        $Path = $Member.GetType().InvokeMember("ADsPath", 'GetProperty', $Null, $Member, $Null)
                        # Check if this member is a group.
                        $isGroup = ($Member.GetType().InvokeMember("Class", 'GetProperty', $Null, $Member, $Null) -eq "group")
                        If (($Path -like "*/$Computer/*")) {
                            $Type = 'Local'
                        } Else {$Type = 'Domain'}
                        New-Object PSObject -Property @{
                            Computername = $Computer
                            Name = $Name
                            Type = $Type
                            ParentGroup = $LocalGroup.Name[0]
                            isGroup = $isGroup
                            Depth = $Counter
                        }
                        If ($isGroup) {
                            # Check if this group is local or domain.
                            #$host.ui.WriteVerboseLine("(RS)Checking if Counter: {0} is less than Depth: {1}" -f $Counter, $Depth)
                            If ($Counter -lt $Depth) {
                                If ($Type -eq 'Local') {
                                    If ($Groups[$Name] -notcontains 'Local') {
                                        $host.ui.WriteVerboseLine(("{0}: Getting local group members" -f $Name))
                                        $Groups[$Name] += ,'Local'
                                        # Enumerate members of local group.
                                        Get-LocalGroupMember $Member
                                    }
                                } Else {
                                    If ($Groups[$Name] -notcontains 'Domain') {
                                        $host.ui.WriteVerboseLine(("{0}: Getting domain group members" -f $Name))
                                        $Groups[$Name] += ,'Domain'
                                        # Enumerate members of domain group.
                                        Get-DomainGroupMember $Member $Name $True
                                    }
                                }
                            }
                        }
                    } Catch {
                        $host.ui.WriteWarningLine(("GLGM{0}" -f $_.Exception.Message))
                    }
                }
            }

            Function Get-DomainGroupMember {
                [cmdletbinding()]
                Param (
                    [parameter()]
                    $DomainGroup, 
                    [parameter()]
                    [string]$NTName, 
                    [parameter()]
                    [string]$blnNT
                )
                Try {
                    If ($blnNT -eq $True) {
                        # Convert NetBIOS domain name of group to Distinguished Name.
                        $objNT.InvokeMember("Set", "InvokeMethod", $Null, $Translate, (3, ("{0}{1}" -f $NetBIOSDomain.Trim(),$NTName)))
                        $DN = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $Translate, 1)
                        $ADGroup = [ADSI]"LDAP://$DN"
                    } Else {
                        $DN = $DomainGroup.distinguishedName
                        $ADGroup = $DomainGroup
                    }         
                    $Counter++   
                    ForEach ($MemberDN In $ADGroup.Member) {
                        $MemberGroup = [ADSI]("LDAP://{0}" -f ($MemberDN -replace '/','\/'))
                        New-Object PSObject -Property @{
                            Computername = $Computer
                            Name = $MemberGroup.name[0]
                            Type = 'Domain'
                            ParentGroup = $NTName
                            isGroup = ($MemberGroup.Class -eq "group")
                            Depth = $Counter
                        }
                        # Check if this member is a group.
                        If ($MemberGroup.Class -eq "group") {              
                            If ($Counter -lt $Depth) {
                                If ($Groups[$MemberGroup.name[0]] -notcontains 'Domain') {
                                    Write-Verbose ("{0}: Getting domain group members" -f $MemberGroup.name[0])
                                    $Groups[$MemberGroup.name[0]] += ,'Domain'
                                    # Enumerate members of domain group.
                                    Get-DomainGroupMember $MemberGroup $MemberGroup.Name[0] $False
                                }                                               
                            }
                        }
                    }
                } Catch {
                    $host.ui.WriteWarningLine(("GDGM{0}" -f $_.Exception.Message))
                }
            }
            #region Get Local Group Members
            $Script:Groups = @{}
            $Script:Counter=0
            # Bind to the group object with the WinNT provider.
            $ADSIGroup = [ADSI]"WinNT://$Computer/$Group,group"
            Write-Verbose ("Checking {0} membership for {1}" -f $Group,$Computer)
            $Groups[$Group] += ,'Local'
            Get-LocalGroupMember -LocalGroup $ADSIGroup
            #endregion Get Local Group Members
        }
        #endregion ScriptBlock
        Write-Verbose ("Checking to see if connected to a domain")
        Try {
            $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
            $Root = $Domain.GetDirectoryEntry()
            $Base = ($Root.distinguishedName)

            # Use the NameTranslate object.
            $Script:Translate = New-Object -comObject "NameTranslate"
            $Script:objNT = $Translate.GetType()

            # Initialize NameTranslate by locating the Global Catalog.
            $objNT.InvokeMember("Init", "InvokeMethod", $Null, $Translate, (3, $Null))

            # Retrieve NetBIOS name of the current domain.
            $objNT.InvokeMember("Set", "InvokeMethod", $Null, $Translate, (1, "$Base"))
            [string]$Script:NetBIOSDomain =$objNT.InvokeMember("Get", "InvokeMethod", $Null, $Translate, 3)  
        } Catch {Write-Warning ("{0}" -f $_.Exception.Message)}         

        #region Runspace Creation
        Write-Verbose ("Creating runspace pool and session states")
        $sessionstate = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
        $runspacepool = [runspacefactory]::CreateRunspacePool(1, $Throttle, $sessionstate, $Host)
        $runspacepool.Open()  

        Write-Verbose ("Creating empty collection to hold runspace jobs")
        $Script:runspaces = New-Object System.Collections.ArrayList        
        #endregion Runspace Creation
    }

    Process {
        ForEach ($Computer in $Computername) {
            #Create the powershell instance and supply the scriptblock with the other parameters 
            $powershell = [powershell]::Create().AddScript($scriptBlock).AddArgument($computer).AddArgument($Group).AddArgument($Depth).AddArgument($NetBIOSDomain).AddArgument($ObjNT).AddArgument($Translate)

            #Add the runspace into the powershell instance
            $powershell.RunspacePool = $runspacepool

            #Create a temporary collection for each runspace
            $temp = "" | Select-Object PowerShell,Runspace,Computer
            $Temp.Computer = $Computer
            $temp.PowerShell = $powershell

            #Save the handle output when calling BeginInvoke() that will be used later to end the runspace
            $temp.Runspace = $powershell.BeginInvoke()
            Write-Verbose ("Adding {0} collection" -f $temp.Computer)
            $runspaces.Add($temp) | Out-Null

            Write-Verbose ("Checking status of runspace jobs")
            Get-RunspaceData @runspacehash   
        }
    }
    End {
        Write-Verbose ("Finish processing the remaining runspace jobs: {0}" -f (@(($runspaces | Where {$_.Runspace -ne $Null}).Count)))
        $runspacehash.Wait = $true
        Get-RunspaceData @runspacehash

        #region Cleanup Runspace
        Write-Verbose ("Closing the runspace pool")
        $runspacepool.close()  
        $runspacepool.Dispose() 
        #endregion Cleanup Runspace    
    }
}

Set-Alias -Name glgm -Value Get-LocalGroupMembership

----------------------------------------------------------------------------------------------------------------------------------

Thank you for any help.

--Sieran

                                                                                                                                                              

Custom provider Get-Item() : How do I format output in a custom provider

$
0
0

I'm starting to write my first custom provider. All the examples I found use WriteItemObject() to display data to user.  The output appears to display all public property names : Value e.g.

PSPath : <blah>

PSDrive: <blah>

..

MyProperty: MyPropertyContents

Question:  How do I format this output into something more friendly, for example I don't want to see the PSDrive.

MyPropertyLabel    

------------------

MyPropertyValue

Thanks,

Call function with parameters invoke -command powershell

$
0
0
                  
You cannot vote on your own post

hey Guys,

Need help in invoking function remotely I get error invalid function. let me know what is missing

error message

nvoke-Command : Cannot validate argument on parameter 'ScriptBlock'. The
argument is null. Provide a valid value for the argument, and then try running
the command again.
At line:1 char:91
+ ...   -ScriptBlock ${function:EnableADBA } -ArgumentList $adbakey
+                    ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Invoke-Command], ParameterBind
   ingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power
   Shell.Commands.InvokeCommandCommand


$LocalAdminCredentialToUse = Get-Credential
 function EnableADBA
{
    param($Key)
    # Need to check the OS version to see if Active Directory is enabled.
    $OSVersion = [System.Environment]::OSVersion.Version
    if ($OSVersion.Major -gt 6 -or (($OSVersion.Major -eq 6) -and ($OSVersion.Minor -ge 2)))
    {
       write-host "Enabling ADBA"
        slmgr.vbs /ad-activation-online  $Key "WinVLK"
       write-host "Enabled ADBA"
    }
    else
    {
       write-host "ADBA could not be enabled, as we are not running on Windows Server  2012 or greater."

    }
}

$fqdn = Get-ADDomain -Server "pods975105007.test.net" |select -ExpandProperty PDCEmulator
$adbakey = "abcde-wxyz-rzsd-4b26"
Invoke-Command -ComputerName $fqdn -Credential  $LocalAdminCredentialToUse   -ScriptBlock ${function:EnableADBA  } -ArgumentList $adbakey

Setting System Time with PowerShell

$
0
0

How can we modify or change system time (not date) using windows powershell? I was trying to change system time by below command:-

set-date -adjust "Monday, October 17, 2011 5:35:25 PM"

But it throws error saying Cannot convert value "Monday, October 17, 2011 5:35:25 PM" to type System.TimeSpan.

I googled a lot but can't find a way to set the SystemTime using powerShell to a given time. I am baically trying to develop a script that accepts time in hours, minutes, seconds ( like "5:35:25 PM") and then sets the system time to "5:35:25 PM" some thing like below.

function Set-Time( [DateTime]$Time)
{
set-date -adjust $Time
}

Set-Time  "Monday, October 17, 2011 5:35:25 PM"



Export list of Virtual Machines in Azure

$
0
0

Hi all,

I'm trying to find a way to export to CSV a list of all VM's against my Azure subscription.<o:p></o:p>

I seem to be going around in circles - some scripts look promising, some just fail miserably.<o:p></o:p>

Can anyone help me out?
I need to see:
Computer name
Resource group
Machine specs such as CPU, RAM, Disks mounted
Private IP address
Location

All machines in Azure are 2012 R2.

Cheers!
Hunt

Can see values from parsed JSON object, but they present as null on PSv2

$
0
0

Code:

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") | out-null
$web_client = new-object system.net.webclient
$npi="randomNPInumberfromNPPES"
$jsondownload = "https://npiregistry.cms.hhs.gov/api/?number=" + $npi
$build_info=$web_client.DownloadString($jsondownload)
$ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$obj = $ser.DeserializeObject($build_info)
#$obj.results.basic.name
Write-Host "Taxonomies for" $npi
$obj.results.taxonomies.code

(of course, it needs a real NPI number, but that's it)

When I am on my Windows 10 workstation at home with PS5, I can access and call all the elements of the deserialized JSON. When I am on my Windows 7 workstation at work with PS2, I cansee them, but nothing returns when I call them directly.

$obj.results

                                                                                          

Key                Value                                                                                                   
---                -----                                                                                                   
taxonomies         {System.Collections.Generic.Dictionary`2[System.String,System.Object]}                                   
addresses          {System.Collections.Generic.Dictionary`2[System.String,System.Object], System.Collections.Generic.Dict...
created_epoch      1196294400                                                                                              
identifiers        {}                                                                                                      
other_names        {}                                                                                                      
number             randomNPInumberfromNPPES                                                                                              
last_updated_epoch 1387411200                                                                                              
basic              {[status, A], [credential, ANP], [first_name, FakeFirstName], [last_name, FakeLastName]...}                             
enumeration_type   NPI-1        

On my Windows 10 PSv5, I can call $obj.results.created_epoch and 1196294400 returns. I do the exact same thing on the W7 PSv2 desktop, andwhile I can still see it (see above paste) when I do $obj.results, when I do $obj.results.created_epoch, no value returns.

I'm losing my mind - I was so happy when I figured out that my PSv2 could use System.Web.Extensions so I could parse JSON, but now I'm really lost. It's maddening because I can see the results on both installations, but can only access the actual values in v5. I've searched everywhere and I can't find a solution - I'm sure it's something ridiculous.

Please help :(

How to enable Cred SSP on DC?

$
0
0

Hi,

I want to enable basic (HTTP) cred ssp between 2 servers.

How can I add SPN on the client machine, which command.

and which exact CMD should I run on server.

Sorry completely new to this.

Thanks in advance

To update(Add or remove user)in "Lock pages in memory"

$
0
0

Dear Experts.... 

Can some guide with a powershell script to add or remove a user in the Lock pages in memory.

GPEDIT-> Computer Configuration -> Windows Setting->Security Setting-> Local Policy-> user rights assignment-> Lock pages in memory


Possible to run advertised programs with Powershell

$
0
0

Hi all so where I work we re-image the machines about every 6 months typically we log into them, go to control panel and select from 2 images (advertisements x64 or x86). My question is could I automate this somehow? Is there an object or a way to call advertised programs and then slect one of them.

Thanks for any help!

How do you get account that powershell session is being run under?

$
0
0
Anybody know a trick to do this?  The $env:profile returns the profile that is being used to logon to Windows.  I want to return the account that is being used to run the session when I do a "runas".  It would be nice to also get the domain that user is in too.  Why?  I run powershell command in multiple domains from my laptop and want to build a way to put the "runas" user name and domain in the window frame so that if I have multiple windows open for powershell I can see what domain I am in by looking at the frame title. 

Import-CSV is blank and empty

$
0
0

My CSV looks like this

Name,Address
Dave,Dave@dave.com
Dave,Dave2@dave.com
Dave,Dave3@dave.com

I've stored this on my C:drive, called it 'alias.csv' and ran this command:

PS C:\>Import-CSV "alias.csv" | ForEach {Set-Mailbox $_.Name -EmailAddresses @{add=$_.Address}}

It goes straight to a flashing cursor.

But then I addresses are not listing.

I can add them individually with no problem at all.

Set-Mailbox dave -EmailAddresses @{add="dvealias@dave.com"}

This works fine so I'm thinking there must be something wrong with the CSV.  I try this command:

Get-ChildItem 'alias.csv' | ForEach {

    $check = Import-Csv $_

    If ($check) { Write-Host "$($_.Name) contains data" }

    Else { Write-Host "$($_.Name) does not contain data" }

}

And it comes back with

does not contain data

Every time....it's not reading the CSV at all.  But If I do this:

PS C:\> Get-Content alias.csv

It lists the contents of the CSV!!

Why is import not working? 

It worked yesterday LOL

Thanks!

* Just tried on another PC and it's working.  Must be something to do with powershell.

Delete files older than 24 hours

$
0
0

Hi guys,

with your help I created this script that delete from a folder all the files older than 14 days and keep just 1 for day from today to 14 days ago.

I need that ALL the files in the last 24 hours are not going to be deleted.

So, I need to have a folder with ALL the files in the last 24 hours, just 1 file from 24 hours ago to 14 days ago, and all the others deleted.

I attach you the script. Can you help me?

Thank you very much everyone

function remove-oldfiles
{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[ValidateScript({
if ((Test-Path "$_") -eq $true) { $true }
else { Throw "folder cannot be located" }
})]
[string]$FolderPath
)
dir -Path "$FolderPath" | where { $_.LastWriteTime -lt ((Get-Date).AddDays(-14)) } | Remove-Item -Force -Confirm:$false
$remaingfiles = dir -Path "$FolderPath" | select *, @{ n = 'DayofFile'; e = { $_.lastwritetime.toshortdatestring() } }
$groups = $remaingfiles | Group-Object dayoffile | where { $_.count -gt 1 }
if ($groups)
{
foreach ($group in $groups)
{
($group).group | sort lastwritetime -Descending | select -Skip 1 | Remove-Item -Force -Confirm:$false
}
}
}

Optimal way to read big log files

$
0
0

Hey There,

I have multiple servers with 2+ GB log files. I need to search certain string from each logs files and pipe result to another file. For the search I use the following commands:

$script=[ScriptBlock]::Create("Get-Content -Path `"C:\Data\2GBFile.log`" | Select-String -Pattern `" 200 `" -NotMatch | Add-content -Path C:\Temp\Non.200Codes.txt")

Invoke-Command -Computer NameLogServer01 -ScriptBlock $script -AsJob

But this ends to the error message: Exception of type 'System.OutOfMemoryException' was thrown.

Is there anything what can be done?

I miss so much of the pure "find.exe".


Petri

How to Execute Batch and Jar File Remotely

$
0
0

Hello,

I need to execute a batch file (.bat) remotely. The bat file is used to start a jar file. I've tried several scripts:

invoke-command -scriptblock {start-process xxx.bat} -computername RemoteComputer

invoke-command -scriptblock {cmd.exe /c xxx.bat} -computername RemoteComputer

invoke-command -scriptblock {& "xxx.bat"} -computername RemoteComputer

The first script works well, and .jar is started by batch file. However, java.exe runs in background and I can't see any output when I use Remote Desktop to remote computer. More seriously, the jar file will call webdriver and run Chrome.exe, but the chrome.exe also runs in background and some bugs then occur. How can I run batch file or jar file remotely not in background?

The second and third command will be stuck because jar file consistently output results in prompt. Also these command start java.exe in background.

How can I execute files just like double clicking them?

Thanks in advance

Powershell Split file at a word

$
0
0

Hello


I am trying to split a file

Everytime it finds the Word SPLIT

The below did not work



$Path = "C:\Users\PLW\Desktop\a\"


$InputFile = (Join-Path $Path "File.txt")

$Reader = New-Object System.IO.StreamReader($InputFile)

While (($Line = $Reader.ReadLine()) -ne $null) {
    If ($Line -match "SPLIT") {
        $OutputFile = $matches[1] + ".txt"
    }

    Add-Content (Join-Path $Path $OutputFile) $Line
}

http://superuser.com/questions/466363/how-to-split-a-text-file-into-multiple-text-files

I don't know what the problem is :(

thank you for your help

Bulk email domain change

$
0
0

I am trying to find the PS script to update multiple users to a new domain in office 365, leaving existing domains as the alias. I have used a command in the past successfully:

Import-CSV "C:\temp\Users.csv" | ForEach {Set-Mailbox $_.UserID -EmailAddresses $_.NewEmailAddress,$_.UserID,$_.Proxy1,$_.Proxy2}

Now it will not work. can anyone tell me what is now wrong with it?

Viewing all 21975 articles
Browse latest View live




Latest Images