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

Get-ADGroupMember by different criteria

$
0
0

I've got the following code working to list AD group members by specific group and retrieve their properties. I need to create a report though and seperate it into three seperate sections - accounts logged in within 30 days, accounts not logged in within 30 days, and disabled accounts.

Get-ADGroupMember My_Group | GetADUser -Properties samaccountname, emailaddress, description, lastlogondate | Select samaccountname, emailaddress, description, lastlogondate

When I've ran it off as well I plan to convert the output to HTML and email the report. Emailing it is straightforward and converting it to HTML seems so as well using the -fragment switch and a bit of CSS.

What's the best way to go about seperating the listed members into three categories while keeping the existing working code? For example, adding a 'where account disabled' to the end of that line. Or 'where last logged on' meets a certain criteria? I could run the command three times or perform an operation on just the one. It'd run once a month overnight against less than 100 users so no massive performance hit.

Thanks in advance


NetAdapter InterfaceDescription

$
0
0

Okay, I give up. I'm trying to change the "InterfaceDescription" value for my NICs using PowerShell, and cannot for the life of me figure out how. I can change the "Name" no problem. Anyone that can tell me the magic formula I would greatly appreciate it. See screenshot below for the value I'm referring to:


Shaun

XML-RPC with PowerShell?

$
0
0

I use PowerShell to create new users and accounts for our onboarding process and for Exchange accounts for Office 365 (which we recently migrated to), I need to create the accounts locally and then move them (if they meet certain criteria) a couple hours later after dirsync has finished completely.

But to move them, I need to store accounts and passwords for the local farm and for O365 access. We use Manage Engine PMP for password storage and it has an API using XML-RPC to get the passwords but I'm not sure how to call it from Powershell (not being familiar at all with XML-RPC).

Anyone done that before? Here's the help page on it.

how to capture results and send email

$
0
0

 How can I capture the output of the write-host to a variable then send that info to an email for someone

$year = get-date -f "yyyy"
$month = get-date -f "MM"
$day = get-date -f "dd"


Get-Childitem -Path 'c:\' | foreach-object {
     if(!$_.PSIsContainer -and $_.length -eq 0) {
         write-host (“{0} -> {1}” -f $_.FullName, $_.Length) 
         }
 }

 I want to include the date stuff in the Subject of the Email...

 SubJect: Zero Byte files found on $Year -- $Month -- $Day

 Thanks.

 

powershell to pass yes or no response

$
0
0

I am using Brocade switch to run this command

 

Step 1. Log in to Brocade switch with root user name

 

Step 2.Run the below command

 

Brocade:root> cfgsave

 

Step 3. After this cmd is executed i will get below message

 

"You are about to save the Defined zoning configuration. This

action will only save the changes on Defined configuration.

Do you want to save the Defined zoning configuration only?  (yes, y, no, n): [no]" y_

 

Step 4. I need to select "yes" option.

 

I wrote  powershell script to run this cmd from my computer with SSH-Session module.

 

$d1 ="10.226.232.137"

$u1 ="test"

$p1 ="password"

$c1 = "cfgsave"

New-SshSession $d1 -Username $u1 -Password "$p1"

$Results = Invoke-Sshcommand -InvokeOnAll -Command $c1

 

It simply hangs there to get yes or no response.

 

How to pass yes or no response in powershell for above issue?

Identify elevated process for non-admin

$
0
0

Although it is unusual, unpriviledged users can run elevated under their normal credentials (not with admin creds).  This most commonly occurs with logon scripts run from GPO. 

Running elevated messes some things up (particularly drive mapping).  Thus, I'm looking for a way for a script to identify if it is running elevated.  I know how to find elevated status for administrators:

$identity  = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal( $identity )
$admin = [System.Security.Principal.WindowsBuiltInRole]::Administrator

if ($principal.IsInRole( $admin )) {
    # script is running as an admin
}
But this doesn't work (obviously) for non-admins.

This articleis helpful for testing for elevated processes, but it doesn't work if run elevated itself.

Anyone have any suggestions? 

Thanks.

Short PowerShell script for finding 1st available drive letter?

$
0
0

I only found old and long scripts (mostly non PS).

Any suggestion?

unpersistent drive mapping question

$
0
0

We have a large (200+) set of shares to map to various users based on group membership via PowerShell login script.  I am very familiar with the arguments for using GPP with item level targeting as a modern method of mapping shares, and we do that for some other shares, but that just isn't a viable option in this case (for reasons I won't go into). 

The script works fine with the

(new-Object-ComWScript.Network).MapNetworkDrive($drive,$path, $true)

method of mapping, but I would like to remove the persistent flag (as it is best practice to not script persistent drives).  If I manually run that command without the $true on the end (non-persistent), the drive appears and works in the Windows GUI and is not persistent across log off/on.  However, in the login script, while the command is successful (based on error checking), the drive is not available in the GUI. 

Does anyone have any suggestions why that would be?

We have a number of XP system still, so we are limited to PowerShell v2 although I am curious if it is possible using the improved "New-PSDrive" in PoSh v3 to thread that middle-ground between mapping the share so that it is available outside the PoSh session and also doesn't remain persistent after log off. 

Thanks.


Bug? Invoke-RestMethod and UTF-8 data

$
0
0

Using PowerShell 3.0 I have a RESTful get service I'm calling that returns UTF-8 data and it appears I've found a bug, but I'm hoping someone has a work-around. The service returns a person's first name, and in one instance the name is Paulé.

Among other settings in the headers I have indicatedAccept-Charset = 'UTF-8' however when the data is returned like this:

$data = Invoke-RestMethod -Uri $url -Headers $header -Method Get -ContentType 'application/json; charset=utf-8'

the name appears like this in the variable: Paulé

However, if I change the invoke call to save the data to a file, the name comes back correctly:

Invoke-RestMethod -Uri $url -Headers $header -Method Get -ContentType 'application/json;charset=utf-8' -OutFile "C:\temp\response.txt"
$data = (gc c:\Temp\response.txt -Encoding UTF8) | ConvertFrom-Json
Now when I inspect the name in the $data variable, it appears correct: Paulé

This appears to be a bug me, and I'd really like to avoid writing the output to a file and then reading it back in. Does anyone have any suggestions on how to get Invoke-RestMethod to work correctly saving the results to a variable?  Short of abandoning Invoke-RestMethod and writing my own function, is there anyway to avoid writing to disk?

Thanks for you help!


PowerShell 2.0 - When to use SqlServer Snap-In

$
0
0

Hello there,

Just started learning about sending Sql Server command through PowerShell.
I understand that we can use .Net objects like SQLConnection, SqlCommand (just like we do in C#) to send the CRUD request to Sql Server database (as $sqlcmd = New-Object System.Data.SqlClient.SqlCommand...)

However, I was reading about Provider and SnapIns and have two doubts. Below is the snippet from my PS v2.0 window:

PS C:\> Get-PSSnapin -Registered
returns:---------------------------------------------------------------------
Name        : SqlServerCmdletSnapin100
Name        : SqlServerProviderSnapin100

#If I see what commands are available in above SnapIns, I get following:
PS C:\> get-command -module SqlServerProviderSnapin100
#returns:---------------------------------------------------------------------
CommandType     Name                                           Definition
-----------                 ----                                                   ----------
Cmdlet          Convert-UrnToPath                              Convert-UrnToPath [-Urn] <String> [-Verbose.
Cmdlet          Decode-SqlName                                 Decode-SqlName [-SqlName] <String> [-Verbos.
Cmdlet          Encode-SqlName                                 Encode-SqlName [-SqlName] <String> [-Verbos.

PS C:\> get-command -module SqlServerCmdletSnapin100
#returns:---------------------------------------------------------------------
CommandType     Name                                           Definition
-----------                 ----                                               ----------
Cmdlet          Invoke-PolicyEvaluation                        Invoke-PolicyEvaluation [-Policy] <PSObject.
Cmdlet          Invoke-Sqlcmd                                  Invoke-Sqlcmd [[-Query] <String>] [-ServerI.

Two questions:
1. Do I need to Add-PSSnapin only when I need to run above commands?
    So, I don't need to import any snap-ins if I want my PowerShell to use .net framework objects to communicate with SQL Server.
2. I can send any CRUD request to database using SqlServerCmdletSnapin100 command 'Invoke-Sqlcmd'.
Which one is preferred method of sending CRUD requests - 'Invoke-Sqlcmd' or .Net Framework objects?

Can anyone please clarify.

Thank you!

The operation returned because the timeout limit was exceeded

$
0
0

I have the following script,  I've ran it for about a year now.  with no issues.   It searches through all the AD servers,  looking for the Last user logon date.    Today, I noticed I am getting a timeout limit was exceeded error.   And the script is very slow.    Does anyone know what this error means ?  thank you for your help


Error:

Get-ADUser : The operation returned because the timeout limit was exceeded.
At C:\Scripts\Sharepoint\LastUserLogon\LastUserLogon.ps1:38 char:10
+                 $u = Get-ADUser $sam -Server $hostname -Properties * | Select-Object Display ...



Script:

Import-Module ActiveDirectory 

$date = (get-date).ToString('yyyy-MM-dd')
$Path = "E:\_CSV-IN\" + $date + "\"

If (-not (test-path $Path))
{
New-Item $Path -type directory 
}

$LastUserLogon = $Path + $date + "-" + "LastUserLogon.csv"

$csvHead = @"
"SamAccountName","DistinguishedName","Enabled","LastLogonTimeStamp","Host"
"@
$csvHead >> $LastUserLogon

$users = Get-ADUser -Filter * -Properties * | Select-Object SAMAccountName,DistinguishedName,enabled,@{label="LastLogon";Expression={if($_.LastLogon){[datetime]::FromFileTime([Int64]$_.LastLogon)}}}| sort-object lastLogon

$dcs = Get-ADDomainController -Filter {Name -like "*"}
  
Foreach($user in $users)
{
$sam = $user.SamAccountName
$time = 0  

foreach($dc in $dcs)
 { 
   $hostname = $dc.HostName
   $u = Get-ADUser $sam -Server $hostname -Properties * | Select-Object Displayname,DistinguishedName,enabled,@{label="LastLogon";Expression={if($_.LastLogon){[datetime]::FromFileTime([Int64]$_.LastLogon)}}}| sort-object lastLogon

   if($u.LastLogon -gt $time) 
     {
    $time = $u.LastLogon
$DCHost = $hostname 
    }
    }
  
 $dt = $time
$Dn = $u.DistinguishedName
$Name = $u.DisplayName
$Enabled = $u.Enabled

If($dt -eq 0)
{
$dt = "Never"
}

  
$csv = @"
"$Name","$Dn","$Enabled","$dt","$DChost"
"@

$csv >> $LastUserLogon

Write-Host $Name "last logged on at:" $dt
}

Get-PrinterProperty question

$
0
0
From my 2012 R2 server how can I get the properties on a printer from a 2008R2 server using Power shell, Thanks.

MSB

How to type Korean Characters in command prompt of Korean win2k3/XP

$
0
0

We are not able to type the Korean multi-bytes in command prompt of Korean-Win2k3/XP. But we able to copy paste the Korean characters command prompt successfully. Here we are using “MS-IME2002” as keyboard type

In case of Korean-Win2k8, able to type through both command prompt by selecting “MS-IME2002” as keyboard type.

Can any one give the solution... its urgent...

Functions from Module Scoping Question

$
0
0
Hello,

I have the following case:

I`m using module that contains several functions, some of them are executing commends in remote sessions. These functions are used from Powershell Script.
The issue is that when function refers to variable from the local computer using the “$Using:var” syntax, it does not tries to access the variables that is defined in Script scope.
The exception is:
“Invoke-Command : The value of the using variable ‘$using:var’ cannot be retrieved because it has not been set in the local session.”

This behavior is not reproduced when the functions are defined in the Script. I`m aware that Modules have their own “Scope”(or Context or whatever…), so I suppose the behavior is by design :)

I`m able to workaround it in two ways:
Using the “$Using:global:var” syntax in the script block or dot source the script.

However it`s not so appropriate for my purpose.

My Question is:
Can I force the Functions that comes from Module to behave the same way as if they are defined in the Script.
Any other suggestions are welcome.

Some examples:

Module content:
————————————————————————————–
function Main
{

param
(
$sb2
)

$ses = New-PSSession -ComputerName sof-srv01

Execute -ses $ses -sb $sb2

}

function Execute
{

param (
$sb,
$ses
)

Invoke-Command -Session $ses -ScriptBlock $sb

}

Export-ModuleMember Execute,Main
————————————————————————————–

Script content:
————————————————————————————–
$var = ‘winrm’
$scr = {Get-Service $using:var}

Main -sb2 $scr
————————————————————————————–

Powershell script to reset TPMLockout

$
0
0

We have Windows 7 Enterprise laptops with TPM chips. We have deployed Bitlocker to these laptops. What I'm trying to accomplish is to write a PowerShell script to look up the msTPM-OwnerInformation value for a specific computer in AD. I want it to then take that value and reset the TPMLockout.

Right now we have to go into the TPM console and click reset and specify the XML file that contains that value.

I have started on a script, but it's not doing what I want it to do as I'm very new to PowerShell.


DataGridView: Get data from rows

$
0
0

Hi, i'm fresching with powershelle and i want to know if there is an option of DataGridView, that allow to get data from rows without select it. i will more clear... i do a grafical inteface where user insert data on many rows. When he finish to insert data  clicking on ok button and all data will be saved in a txt file or csv.

Thanks for the helpfulness

Cristian

Different Results Depending On Execution Area

$
0
0

Hello,

I am trying to write some simple testing to be completed after patching/outages and wanted to automate it. Everything was going great until I tried to package it all together so that each test was a function that returned some results objects so that I could aggregate and report easily.

When I run the Execute-SQLQuery function by itself (outside of the Test-SQLClusterNodesAreUp function) I get a dataset back as expected and I can access the dataset result. When I run the Test-SQLClusterNodesAreUp I get back a dataset result but there is no data in it. I setup breakpoints and can see that there is a tablecollection with 1 table and the table has 1 row but when I try to access it I get an index out of bounds error. When I tried to foreach it, I also get an index error... I'm not sure why.

I also know that this is pretty sloppy for Powershell but any hints or posts for betters ways of writing this I am all open for. Just getting started working with this, be gentle.

Scripts:

function Create-UnitTestReportObject
{
    $ReportObject = New-Object Object | 
                    Add-Member NoteProperty TestName "TestName" -PassThru |
                    Add-Member NoteProperty Description "Simple Description" -PassThru |
                    Add-Member NoteProperty Passed $false -PassThru |
                    Add-Member NoteProperty FailureDescription "Info about failures" -PassThru |
                    Add-Member ScriptMethod WriteResultsToConsole {
                                    Write-Host $this.TestName : $this.Passed
                                } -Passthru|
                    Add-Member ScriptMethod WriteResultsToHTMLString {
                                $HTMLData = "<tr><td>" + $this.TestName + "</td><td>" + $this.Passed + "</td>"
                                return $HTMLData
                                } -PassThru
    return $ReportObject
}

function Create-SQLConnectionObject
{
	param   (
		[string] $SqlServerName,
		[string] $DatabaseName = "master",
		[string] $ExtraConnectionInfo = ""
		)
	$ConnectionString = "Server=$SqlServerName;Integrated Security=True;Database=$DatabaseName;$ExtraConnectionInfo"

	$ConnectionObject = new-object system.data.SqlClient.SQLConnection($ConnectionString) -ErrorAction Stop

	return $ConnectionObject
}

function Create-SQLCommandObject
{
	param   (
		[string] $SQLCommandText,
		[System.Data.SqlClient.SqlConnection] $ConnectionObject
		)
	
	$CmdObj = new-object system.data.SqlClient.SqlCommand($SQLCommandText, $ConnectionObject) -ErrorAction Stop

	return $CmdObj
}

function Execute-SQLQuery
{
	param   (
		[string] $ServerName,
		[string] $DatabaseName,
		[string] $OtherConnectionInfo,
		[string] $QueryText
		)

	try
	{
		$Connection = Create-SQLConnectionObject -SQLServerName $ServerName -DatabaseName $DatabaseName -ExtraConnectionInfo $OtherConnectionInfo
		$Connection.Open()
	
		$QueryObj = Create-SQLCommandObject -SQLCommandText $QueryText -ConnectionObject $Connection
		
		$SqlAdapter = new-object system.data.SqlClient.SqlDataAdapter $QueryObj
		
		$DataSet = new-object system.data.DataSet
		$SqlAdapter.Fill($DataSet) | Out-Null

		$Connection.Close()

    	return $DataSet
	}
	catch
	{
        return $Error[0]
	}
	finally
	{
        $Connection.Dispose()
        $QueryObj.Dispose()
        $SqlAdapter.Dispose()
	}
}

function Test-SQLClusterNodesAreUp
{
	param   (
		[string] $ServerName,
        [string] $OtherConnectionInfo
		)

	try
	{
        $Query = "SELECT COUNT(*) AS DownNodes FROM sys.dm_os_cluster_nodes WHERE status != 0"

        $UnitTestReport = Create-UnitTestReportObject
        $UnitTestReport.TestName = "SQL Cluster Nodes Up"
        $UnitTestReport.Description = "Checks to see if any cluster nodes are down from the perspective of SQL Server."
		$SQLQueryResults = Execute-SQLQuery -ServerName $ServerName -DatabaseName "master" -OtherConnectionInfo $OtherConnectionInfo -QueryText $Query

        if($SQLQueryResults.count -eq 1)
        {
                if($SQLQueryResults.Tables[0].Row[0]["DownNodes"] -eq 0)
                {
                    $UnitTestReport.Passed = $true
                }
                else
                {
                    $UnitTestReport.Passed = $false
                    $UnitTestReport.FailureDescription = "There were nodes down according to SQL Server. Please Investigate!"
                }
            }
            if($SQLQueryResults.GetType() -eq "ErrorRecord")
            {
                $UnitTestReport.Passed = $false
                $UnitTestReport.FailureDescription = $SQLQueryResults[0].Exception.Message
            }
	}
	catch
	{
        $UnitTestReport.Passed = $false
        $UnitTestReport.FailureDescription = $Error[0].Exception.Message
	}
    return $UnitTestReport
}


Sean Gallardy | Blog | Twitter

change a cell value in excel using powershell

$
0
0

HI All,

I am using powershell to manipulate an excel spreadsheet.

I am using a vlookup to get data from another sheet and compare it.

I want to delete all rows where the vlookup comes back with #N/A but I am struggling to get it to work.

I tried using this code that I found on a website

for ($i = 1; $i -le $rows; $i++) {
     If ($ws.Item($i,5) = "#N/A") {
         $Range = $ws.Cells.Item($i, 1).EntireRow
         $Range.Delete()
         $i = $i - 1
     }
 }

But that goes through and deletes every row.

does anyone have any ideas?

My code so far is:-

 # Show Excel
 $xl.visible = $true
 $xl.DisplayAlerts = $False
 # Create a workbook
 $wb = $xl.Workbooks.open("x:\messaging\pstfilestest.csv")
 $wb1 = $xl.Workbooks.open("x:\messaging\Batch14a\BAtch14a.csv")
 # Get sheets
 $ws = $wb.WorkSheets.item(1)
 $ws.activate()
 Start-Sleep 1
 $ws.cells.item(1,3).value() = "Alias"
 $ws.Cells.Item(1,4).value() = "UserPrincipalName"
 $ws.Cells.Item(1,5).value() = "DisplayName"
 $ws.Cells.Item(1,6).value() = "Batch"
  $ws.cells.item(2,3).value() = "=LEFT(RC[-1],FIND(""@"",RC[-1])-1)"
 $ws.Cells.Item(2,4).value() = "=LEFT(RC[-2],FIND("".uk"",RC[-2])+2)" 
 $ws.Cells.Item(2,5).value() = "=VLOOKUP(RC[-1],BAtch14a.csv!R1:R1048576,2,FALSE)"
 $ws.Cells.Item(2,6).value() = "Batch14a_001"
  $rows = $ws.range("c2").currentregion.rows.count
 $ws.range("c2:e$rows").formula = $ws.range("c2:e2").formula
 [void]$ws.Cells.Item(1,1).select()
 [void] $ws.cells.EntireColumn.Autofit()
 $Range = $ws.UsedRange
 $R2 = $ws.Range("E1")
 [void] $Range.Sort($R2)

 $Range = $ws.Range("A1:F1").entirecolumn
 $Range.Copy()|Out-Null
 $Range = $ws.Range("A1")
 $Range.PasteSpecial(-4163)

Bottom 4 lines is to paste the values rather than the formula as I thought this might be the issue so I can remove them if needed

TIA

Andy

failed files check, keeping track issue

$
0
0

Hey guys, we have a failed print queue folder and we want to run a script that checks this folder for say 10+ failed jobs then email us and notify that is the case, easy enough? But... i dont want it to email us every 10 seconds about same jobs i want it to email us on anything new and 10+(the jobs are kept there for 7 days then they expire), so i need a log setup that should keep track of jobs it emailed us about then maybe compare this list with the jobs that are out there, for some reason i am having the hardest time with this.

#job count to look for or more than
$jobcount = "10"
#set servers
$servers = "ghsepsw3k3"#,"ghsepsw3k6","ghsepsw3k7"
#set people to email
[string[]]$emailTo = "email"
#setup E-mail settings
$emailFrom = "EPSFailCheck@g.edu"
$smtpServer = "GEXHUB2W8K1V.g.edu"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg = new-object Net.Mail.MailMessage  
$msg.From = $emailFrom 
$msg.IsBodyHTML = $true
$msg.To.Add($emailto)
while(1){
sleep -Seconds 1
$d = Get-Date
#check for 4:30 pm or 7:30 am
#if($d.Hour -eq 16 -and $d.Minute -ge 30 -or $d.Hour -eq 12 -and $d.Minute -ge 30){
#dc10 logs
$dc10="\\ctx65dcepc010\c$\PsScripts\test\EPSFailed\Logs"
#create logs
if (!(test-path "$($dc10)\FailedEPS.log")){
new-item -type file "$($dc10)\FailedEPS.log"}else{}
$logEps = "$($dc10)\FailedEPS.log"
if (!(test-path "$($dc10)\Eps3FailedJobs.log")){
new-item -type file "$($dc10)\Eps3FailedJobs.log"}else{}
$logEps3 = "$($dc10)\Eps3FailedJobs.log"
foreach($server in $servers){
if($server -like "*w3k3"){$log = $logeps3}
$files = dir "\\$($server)\c$\Epic\Jobs\Failed\7.8.4\Epic Print Service" -Recurse | ? { !$_.PSIsContainer}
if($files.Count -ge $jobcount){
if($files){
$failedlist = gc $logEps
foreach($file in $files){
#check if all eps log empty or doesnt have that failed file name
if((!$failedlist) -or !($failedlist).Contains($file.Name)){
#add file name to all eps log
$file.Name >> $logEps
}
else{
}
}
}
    #sending E-mail 
    #$msg.Subject = "EPS Failed Jobs high count"
    #$msg.Body = "$Date, Found failed jobs: `"$($files.count)`" on $($server) server"
    #$smtp.Send($msg)
    }
}#if time
}#while loop


Add YYYYMMDD_xyz_ftp in front of the file name using PowerShell

$
0
0

Hi All,

I am working on a PowerShell script to generate a dat file. I need to change the format of this file as follows:

Original File Name: eagle.dat

Required File Name: YYYYMMDD_CA_eagle.dat

I know that we can do this very easily from Windows Cmd like below. I have written this massive PowerShell script which I do not want to be wasted just because of this last step.

rename eagle.dat %date:~-4,4%%date:~-10,2%%date:~-7,2%_CA_eagle.dat

Thank you in advance for your reply.

Ben

Viewing all 21975 articles
Browse latest View live


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