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

Force PowerShell version on remote session

$
0
0

Hi, as the title suggest, I want to explicitly use PowerShell 2.0 to execute scripts and commands, why? Because SharePoint 2010 only supports PowerShell 2.0. So my problem:

I have SharePoint 2010 installed on a Windows Server 2012 (with PowerShell 4.0 as default). When I execute a SharePoint PowerShell command on the server, it only works when I go to a PowerShell 2.0 console (powershell.exe -v 2). But when I am on another server and start a PowerShell 2.0 console, the remote session I create with e.g. Enter-PSSession is always PowerShell 4.0, the version of the host. This will prevent me from executing SharePoint commands remotely

So my question is, is it possible in some way to force a specific version of PowerShell with a remote session?


OS check for Unix or Linux

$
0
0

where I work they use Generic Server names that do not differentiate between OS.  On occasion I get a problem ticket for a server that is not in the documentation library. Is there a quick test I can use to determine if it is Unix or Linux?  It's easy enough to figure out if it is Windows, but sometimes the windows checks fail if the server is pinging but non-responsive, but a quick test to see if it may be Unix or Linux would help.

Thank you,

Bryan

Add more than 1 item to 1 cell in a CSV file with add-member

$
0
0

Hi everyone so I'm pulling some computer info and storing it into a CSV file. It's all working fine but the problem is if I pull something with more than 1 item (2 Nics) it writes it as an object array to my CSV file. Is there a way to put all the items in that array into 1 cell?

Here's a snippet of what I have now.

$NIC = Get-WmiObject win32_networkadapterconfiguration -ComputerName $computer

$output | Add-Member NoteProperty MACAddress ($NIC.MACAddress)

$outarray += $output

$outarray | Export-CSV file_location

Thanks for any help!

Help needed with powershell datasets - recursing.

$
0
0

I was trying to filter the dataset that i got from SQL server database. Here is the scenario...

I'm getting servername,dbname columns from one of the database servers and returning the result set as return ,$dataSet.Tables[0]. I'm getting the results correctly in a table format. (SUCCESS)

But now i got all the server names to a variable from this dataset as below, (SUCCESS)

$servers=$dataSet_1.servername | select  -unique

Now, i'm trying to loop through each server and get the database list associated to each server as follows, but looks like this is not a right approach as it is getting me all the severs and their database names is every iteration (FAILURE)


foreach($server IN $servers) { write-host $server $dataSet_1 | Where-Object {$dataSet_1.servername -eq $server} | select $_.dbname }

Could someone help me the right approach are a way to do this.

Code:

function sqlconnection($server, $db, $sqlcmd)
{

    $connString = "Server="+$server+";Database="+$db+";Integrated Security=sspi"
    $connString
    $sqlConnect = New-Object System.Data.SqlClient.SqlConnection $connString
    $sqlConnect.Open()

    $sqlCommand = $sqlConnect.CreateCommand()
    $sqlCommand.CommandText = $sqlcmd

    $dataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $sqlcommand
    $dataSet = New-Object System.Data.DataSet

    $dataAdapter.Fill($dataSet) | out-null
    $sqlConnect.Close()

    return ,$dataSet.Tables[0]

}


$sqlcmd = "SELECT servername,dbname FROM database_servers WITH (NOLOCK) "

$dataSet_1=sqlconnection 'SQL_Instance' 'database_name' $sqlcmd
$servers=$dataSet_1.servername | select  -unique

foreach($server IN $servers)
{

    write-host "Below are list of databases on "+$server

     $dataSet_1 | where {$_.servername -eq $server}  | select dbname

}

Thanks



PowerShell string comparison (-eq) returns unexpected result

$
0
0

Hello,

I'm scratching my head trying to figure out why this is not working.

So I have a variable called $availableGroups whose type is Object[]. It basically contains a collection of string.

The first element of the collection gives me...

>$availableGroups[0]
[TEAM FOUNDATION]\Team Foundation Anonymous Users

When I try to run the following comparison, it returns False instead of True. 

>$availableGroups[0] -eq "[TEAM FOUNDATION]\Team Foundation Anonymous Users"
False

I copied and pasted the string value from the console and there is no way it's a typo issue. Can anyone help me how I can get it to return True?

How to pause Windows Media Player Video every 20 seconds (what ever time interval) using Powershell

PowerShell Workflow : Write-Error ignores -ErrorAction?

$
0
0

Greetings All,

I've seen some very curious behaviors around $ErrorActionPreference and -ErrorAction in PowerShell workflow.  

#1: Consider the three examples pasted below.  wtfFunction and wtfInlineScript behave as expected, and wtfNative shouldnot cause the catch to trigger, since -ErrorAction Continue is specified, but it does.  No value for -ErrorAction seems to be observed by the workflow engine.  This seems a defect since nothing in the literature says -ErrorAction is ignored or unsupported by PowerShell workflow.

#2: Same three functions, but this time, set your shell's $ErrorActionPreference to "Stop" before executing the examples.  Even though this shouldn't change anything, since the workflow's first line is to set the preference to stop anyway, it does.  Now, wtfFunction and wtfInlineScript continue to avoid the catch, but code halts execution anyway - never reaching the Write-Output statement.

Are these defects?  Did I miss something in the literature about -ErrorAction not being observed under some conditions?

workflow wtfFunction
{
    Write-Output "Workflow Start: My ErrorActionPreference is $ErrorActionPreference"
    $ErrorActionPreference = "Stop"

    #Write-Error with ErrorAction: Continue as function activity
    function myFunction {
        Write-Output "Function Start: My ErrorActionPreference is $ErrorActionPreference"
        try
        {
            Write-Error -Message "This message should not trigger the catch" -ErrorAction Continue
        }
        catch
        {
            Write-Warning "Oops!  Got Caught!!"
        }
    }
    #But this call will cause an error.
    myFunction

    Write-Output "Reached the end!"
}
wtfFunction

workflow wtfInlineScript
{
    Write-Output "Workflow Start: My ErrorActionPreference is $ErrorActionPreference"
    $ErrorActionPreference = "Stop"

    #Write-Error with ErrorAction: Continue as InlineScript {} activity
    try
    {
        InlineScript{Write-Error -Message "This should also not get caught!" -ErrorAction Continue}
    }
    catch
    {
        Write-Warning "Oops!  Got Caught!  How?!"
    }

    Write-Output "Reached the end!"
}
wtfInlineScript

workflow wtfNative
{
    Write-Output "Workflow Start: My ErrorActionPreference is $ErrorActionPreference"
    $ErrorActionPreference = "Stop"

    #Write-Error with ErrorAction: Continue as native workflow activity
    try
    {
        Write-Error -Message "This, however, seems to catch the error!" -ErrorAction Continue
    }
    catch
    {
        Write-Warning "Yup - Caught it!"
    }

    Write-Output "Reached the end!"
}
wtfNative


Profile Signature?

powershell code,script Split - for each - how to?

$
0
0

Hello Good people,

case:

I've got an variabele ($post) wich can contain the next information (its posted with a form) and looks like :

A       B       C       D

anna   1       2       3

John

Roy

Sam



Values in A are sperated  a ;

Information can be different on each user post. Now I want to export for each A an csv file wich contains A B C D like:

A       B       C       D

Anna  1       2       3

A       B       C       D

John   1       2       3      etc.

The next lines are working fine for one A:

$export = "c:\CSV\" + $post."A" + "-" + $date + ".csv"

$post | Select "a","B","C","D" | export-csv $export -notype - delimiter ","

I want a unique file fo each A, so each file must contain their own A with the common BCD (labels) and their value. any ideas?

I'm a newbie in powershell and not a native English speaking so I hope my question is clear?

thx



Can't access remote powershell

$
0
0

Hi,

Remote powershell was working well until the port 5985 was blocked by my antivirus provider. After that I've configured my PC (I'm administrator on the domain) on the standard http ports, it works well from my pc to the domain controller. Unfortunatly it is not working from the domain controller to the user's PC's. I got an access denied. the command Test-WSMan "computer" -port 80 is working fon both ways. I've configured the User's GPO to enable Powershell script's launching. I've also set the authorized profiles to execute with:

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell -Force

Thanks for Help, Olivier.

Remotely enable PSRemoting

$
0
0

Hi guys,

So, the scripting world is new to me but I’m trying to get a handle on it, and hope that you can help me.

I’m working in a mixed environment; our domain contains XP clients and 2008R2 servers. All client computers have PS 2.0 installed.

I want to be able to work with PSRemoting on other client computers. Of course I have Admin privileges and I ran the commands as admin.

My problem is that I can't enable remoting through Group Policy. Our organization is really big and changing GPO will take forever because of IT policies and different approvals.

Right now we have a few jobs we really need to execute and can’t wait till GPO changes are done.

So actually, I’m looking for a way to enable remoting on remote machines in our domain. When I logon interactively to a machine and enable PSReomting, I’m able to work remotly on this machine after that. But I can't find a way to remotely enable PSReomting.

I’ve tried to enable thewinrm service through cmd, and then with PS, like this:

SC\\server start winrm

Then, from PS:

foreach ($i in 'Computer') { Enable-PSRemoting -Force }

Then I ranwinrm quickconfig, and the result was:

WinRM already is set up to receive requests on this machine

WinRM already is set up for remote management on this machine

After performing these steps, I tried remoting and got this error:

"Connecting to remote server failed with the following error message: access is denied. for more info...."

I went through every step in About_Remote_Troubleshooting but found nothing.

After googling for hours I found nothing.

Also, does anyone know if PS Active Directory module is available for XP? After some searching it looks like XP doesn’t support this module, but just to make sure.

Thank youJ

read an xml file from a filesystem and process

$
0
0

hi,

  would like to know how to read a xml file in power shell.

assume i have a xml fiel called sites.xml

<sites><site name="project1"><siteurl>http://srvrname:2020/sites/project1 </siteurl><siteowner>in\sa.pp</siteowner></site></sites>

I am keeping this file in D:\ drive and want to read in power shell script process it.

help is appreciated!




Case Statement?

$
0
0

Hello,

I have a script which is going to tell the user when their password expires. we basically provide E-Mail to companies so they are not on the domain so we are automating the process of sending them an E-Mail to remind them and let them know when the password expires. This part I have done and the script works well. We have generated the E-Mails and tested them and its all working the only part is that I need to check against the dates for 14 dates till expiry and then 7,6,5,4,3,2,1 days till expiry and then send an E-Mail.

I am just unsure how to go about this:

$Date1 = (Get-Date).AddDays(+1).ToString('dd MMMM yyyy')
$Date2 = (Get-Date).AddDays(+2).ToString('dd MMMM yyyy')
$Date3 = (Get-Date).AddDays(+3).ToString('dd MMMM yyyy')
$Date4 = (Get-Date).AddDays(+4).ToString('dd MMMM yyyy')
$Date5 = (Get-Date).AddDays(+5).ToString('dd MMMM yyyy')
$Date6 = (Get-Date).AddDays(+6).ToString('dd MMMM yyyy')
$Date7 = (Get-Date).AddDays(+7).ToString('dd MMMM yyyy')

I currently have the following:

If($_.PasswordStatus -eq "Expires at: $Date7")
 {

$smtp = "Server.co.uk"

$to = $Mail

$from = PasswordExpiry@domain.co.uk

$subject = "Password Expiry"

$body = "<font size=3 face=arial> Dear $First </font> <br><br>"

$body += "<font size=3 face=arial> Your password is about to expire, please click <a href=https://link.com>here</a> to update your password.</font> <br><br> "

$body += "<font size=3 face=arial> Your password $PasswordStatus </font> <br><br> "

$body += "<font size=3 face=arial> Regards, </font> <br><br> "

$body += "<font size=3 face=arial> These nice people in IT </font> <br><br> "

$body += "<b> <font size=4 face=arial color=red> Please do not reply to this E-Mail as this mailbox is not monitored. </font> </b> <br><br>"

#### Now send the email using \> Send-MailMessage

Send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Priority high

 }
}

So I would need this 7 times unless there is an easier way of doing this. The first idea I had was to change this:

If($_.PasswordStatus -eq "Expires at: $Date7")

to

If($_.PasswordStatus -le "Expires at: $Date7")

Which doesn't work as its a string so it cant work out what is less than "Expires at:" so I think that would be the ultimate solution but if not then if there is a way of doing this then its fine such as maybe a case statement? I am unsure how this would work though.

I hope this makes some sense.

Any help would be appreciated.

James

Powershell won't run SELECT queries with VIEWS

$
0
0

I created view

CREATEVIEW V_DUPLICATE_ID ASSELECTDISTINCT Computer_Name, IP_Address, COUNT(Computer_ID)AS Num_Computer_IDFROM dbo.ComputersWHERE Computer_Name in(SELECTDISTINCT Computer_NameFROM dbo.ComputersWHERE dbo.Computers.COMPUTER_NAME LIKE'%s001'AND dbo.Computers.IP_Address LIKE'%.100'GROUPBY Computer_Name,IP_AddressHAVING COUNT(DISTINCT Computer_ID)>1)AND dbo.Computers.COMPUTER_NAME LIKE'%s001'AND dbo.Computers.IP_Address LIKE'%.100'GROUPBY Computer_Name, IP_Address

And created an execution string, $SQL10 that goes into ODBC and output goes to EXCEL

$SQL10 ="SELECT * FROM [V_Duplicate_ID]
ORDER BY Num_Computer_ID DESC"...$ws =$wb.Worksheets.Item(10)$ws.name ="GUP Duplicate ID"$qt =$ws.QueryTables.Add("ODBC;DSN=$DSN3;UID=$username;PWD=$password",$ws.Range("A1"),$SQL10)if($qt.Refresh()){$ws.Activate()$ws.Select()$excel.Rows.Item(1).HorizontalAlignment =$xlCenter$excel.Rows.Item(1).VerticalAlignment =$xlTop$excel.Rows.Item("1:1").Font.Name ="Calibri"$excel.Rows.Item("1:1").Font.Size =11$excel.Rows.Item("1:1").Font.Bold =$true}

Problem is, the Powershell script hangs with this statement. How to fix?

Use alternative values in a foreach loop

$
0
0

Hi, i have to modify the values in a set of DHCP scopes, but i don't want those values in the same order, so the same server doesn't overload, so i want to alternate each velue

For example..:

$values = '1.1.1.1','2.2.2.2'

foreach ($scope in $scopes) {

Set-DhcpServerv4OptionValue  -ScopeId $scope.ScopeId  -OptionId 150 -Value $values[0],$values[1]

}


So for the firsrt i want them to be like 

Set-DhcpServerv4OptionValue -ScopeId $scope.ScopeId -OptionId 150 -Value
1.1.1.1,2.2.2.2

And for the second i want them to be set like:

Set-DhcpServerv4OptionValue -ScopeId $scope.ScopeId -OptionId 150 -Value
2.2.2.2,1.1.1.1

And so on....

How can i do this?

Thanks



Get-adcomputer in a specific OU and export to csv with following

$
0
0

Hi all,

need some help With PowerShell command for following requirements:

Export all computer in spesific OU that shows Computername,last boot time,total memory,harddisk type(spin or SSD).

Is it possible?

thanks!


Please mark as helpful if you find my contribution useful or as an answer if it does answer your question. That will encourage me - and others - to take time out to help you. Thank you! Off2work


script to find out if there are Active/Inactive RDP sessoins on windows servers

$
0
0

Hi All

I wanted to use this script to find out if there are any Active or Inactive RDP sessions as my client is escalating everyday about this...My team members do not bother to log off from servers.


param(

    [CmdletBinding()] 
    [Parameter(ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true)]
    [string[]]$ComputerName = 'localhost'
)

process {
    foreach ($Computer in $ComputerName) {
        quser /server:$Computer | Select-Object -Skip 1 | ForEach-Object {
            $CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
            $HashProps = @{
                UserName = $CurrentLine[0]
                ComputerName = $Computer
            }

            # If session is disconnected different fields will be selected
            if ($CurrentLine[2] -eq 'Disc') {
                    $HashProps.SessionName = $null
                    $HashProps.Id = $CurrentLine[1]
                    $HashProps.State = $CurrentLine[2]
                    $HashProps.IdleTime = $CurrentLine[3]
                    $HashProps.LogonTime = $CurrentLine[4..6] -join ' '
            } else {
                    $HashProps.SessionName = $CurrentLine[1]
                    $HashProps.Id = $CurrentLine[2]
                    $HashProps.State = $CurrentLine[3]
                    $HashProps.IdleTime = $CurrentLine[4]
                    $HashProps.LogonTime = $CurrentLine[5..7] -join ' '
            }

            New-Object -TypeName PSCustomObject -Property $HashProps |
            Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime
        }
    }
}

When i run this from my desktop(Win7) it shows me that i am logged in.

But when i give a server list in txt format at the above highlighted line localhost it gives me error (string[]]$ComputerName = c:\serverlist.txt)

Also let me know how to get output in txt or CSV

The term 'test.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the sp
elling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:9
+ test.ps1 <<<<  >> test
    + CategoryInfo          : ObjectNotFound: (test.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


Suggestion [3,General]: The command test.ps1 was not found, but does exist in the current location. Windows PowerShell d
oesn't load commands from the current location by default. If you trust this command, instead type ".\test.ps1". See "ge
t-help about_Command_Precedence" for more details.

Error 0x000006BA enumerating sessionnames
Error [1722]:The RPC server is unavailable.


Thanks in Advance.

Alex


Alex


Locate all possible gateways in network

$
0
0

Using Powershell 4.0. I want to know if there is a way to locate all possible gateway by IP in our network? We have multiple global sites but only interested in locating the gateways....

I'm assuming by querying our DHCP servers we can locate the gateways.....

Thanks!


New-WSManInstance Error

$
0
0

I'm trying to get WinRM to run over HTTPS using GPO configuration.

I'm running AD Server 2012 with Win7 and Win 8.1 clients. I have a Certificate Server running on my domain.

I've got it working fine over HTTP.

This blog post by Eric at “OtherDutiesAsRequired.com” is great, but he glosses over the Certificate construction.

After I asked, Eric referred me to a TechNet Article that covers the auto-enroll certificate and GPO in detail.

Eric has a PowerShell script run from a GPO that creates the HTTPS listener:

$ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
$Hostname = “{0}.{1}” -f $ipProperties.Hostname,$ipProperties.DomainName
$CertThumbprint = Get-ChildItem “Cert:\LocalMachine\My” | Select -First 1
$CertThumbprintValue = $CertThumbprint | foreach-Object {$_.Thumbprint}
New-WSManInstance winrm/config/listener -SelectorSet @{Address=”*”;Transport=”HTTPS”} -ValueSet @{Hostname=$Hostname;CertificateThumbprint=$CertThumbprintValue}

When I run the lines of the script manually (from Admin level PowerShell), on the last line I get the error:

New-WSManInstance : An internal error occurred.+ New-WSManInstance winrm/config/listener -SelectorSet @{Address="*";Transport="HT ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (:) [New-WSManInstance], InvalidOperationException+ FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.NewWSManInstanceCommand


I haven’t seen anything really helpful on this error.

Do any of you PS guru's know how to resolve this?

question on syntax

$
0
0

Can someone kindly tell me how i can fix this syntax issue?

$var = '\\'+$_.name;write-host $var

Works, but is sloppy

Write-host '\\'$_.name
Puts a space that i cant have.


Problems writing to remote file share using a scheduled task using a GMSA.

$
0
0

Hi All,

We have an issue where we are having problems writing to remote DFS file share using a scheduled task (which is running a PowerShell script) running under the security context of a gMSA [Group Managed Service Account] (running under Windows Server 2012). The GMSA has been granted the permissions write to the remote file share location.  The scheduled task runs properly, except its unable to write to the DFS share.  I will note that it can write the file to local file system.

One of the real issues we are having in troubleshooting this issue is finding away to capture the output/errors that the script is experiencing writing to the file share (which is being covered up by running under a scheduled task which is running under GMSA).  We have checked the logs that we are aware of.

I did a some research and I found the following article (see below).  Not sure if that is the issue.  

Scheduled task cannot write to a share? 

  • Summary: Recommends using the "Log on as a batch job", under Local Security Policy\Local Policies\User Rights Assignments\

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>