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

I want to impersonate user when I access Microsoft SQL Server from powershell

$
0
0

Hi,

Actually I have to perform some SQL operation on my MSSQL server database. but problems is that I have given all credentials (windows fix login/password which can access database) in connection string. but when I execute the script then it is always using my windows login and password and then giving error that not able to connect with it.

My personal windows credentials does not have access to my enterprise database that is why I am using service ID.

I came to know that I have to do user impersonation of user when i access database but how to do that?? can you guys give me the syntax for that as i have to perform all sql operation using impersonation.

Please reply me as soon as possible as i stuck since long


Vipul Mistry Sr. Embedded Engineer www.eInfochips.com


Remove users from all distribution groups in Microsoft 365

$
0
0

Hello

I would like to know if there is a way I can remove a user from all distribution groups in Microsoft 365. I have a rather large list of users that this would need to be applied to though.

Any help would be greatly appreciated.

John

GPO & Printer redirection configuration for Remote Desktop Services 2012 r2

$
0
0

Hello,

I need to have RDS collection users print using following logic :

Do not use Easy print first (search for printer driver on server first)
  1/ if client's printer driver found on server - use it to print and set it as default
  2/ if client's printer driver not found on server - then use Easy print printer driver to print
      (of course set it as default for the user)

Actually configuring the settings using GPO & collection level settings.

Collection Settings :
  

GPO Settings :  
    


It worked for a while but now the "default printer" side of the configuration has unexpected behaviour

Should this default printer side of settings be better handled via scripts ?
Am I missing something ?
 
any help ?

I'm flushing all configured printer drivers & printers from the test server so I can redo tests from scratch.
Thanks


MCTS Windows Server Virtualization, Configuration


Create a dynamic group by email address (not includes 2nd email address)

$
0
0

I've created a dynamic group from powershell as below,  but it also shows the user who's the 2nd email address is @abc.com.

So how can exclude the user has 2nd email address from the group?

New-DynamicDistributionGroup -Name "ACB All Users Dynamic Group" -OrganizationalUnit xyz.lftltd.net/HKG/Groups -RecipientContainer lftltd.net -PrimarySmtpAddressABCAllUsersDynamicGroup@lftltd.net -RecipientFilter {(EmailAddresses -like'*@abc.com') -and (RecipientType -eq 'UserMailbox') -and (CustomAttribute9 -ne 'Resigned') -and (Title -ne 'System Mailbox')}

Many thanks.

Admin Viewing of Documents in Onedrive

Export variables to html

$
0
0

What I'm trying to do is export my custom variables from PowerShell script to html via "ConvertTo-Html"

# This example works
Get-Process | Select-Object Name, ID | ConvertTo-Html

#What I'm trying to do is same as above, but using my own variables. This ofcourse doesn't work :)

$Var1 ='Value1'
$Var2= 'Value2'
$Var3= 'Value3'
$Var4= 'Value4'

Select-Object $Var1, $Var2, $Var3, $Var4 | ConvertTo-Html



Import-CSV Commandlet and Renaming a duplicate value found in a column

$
0
0

I'm fairly new to Power Shell and I need a bit of help manipulating some data after I import it via the "IMPORT-CSV" commandlet.

Source text example could look something like this:

CSV File Name for below text is: Mybooks.csv and I declare a variable with $mybooks = Import-CSV c:\docs\mybooks.csv

Author, Title, Year Published

John Smith, My Book On Life, 1986

Larry John, My Book on Life, 1967

Jimmy Edwards, My Own Book Created, 1956

After the import I would like to search through all the TITLES and if a duplicate Title is detected I'd like to add a "1" to it or some other value.

I've tried Compare-Object, Select-Object, and Get-Unique using various foreach loops and IF statements. I cannot figure this out, please help!!

I thought it would be as simple and doing some compare on $mybooks.title or something.

I'm looking for the easiest method possible and prefer to using the commandlets if possible, or a REGEX if you think that will work. Thanks!

WSUS Maintenance Script Problem

$
0
0

I have a PowerShell script to run routine maintenance on my WSUS server and it is exhibiting odd behavior that I have been unable to resolve. The script is scheduled to run every day. It performs the clean-up tasks every day and runs the database maintenance script on Sunday. The database maintenance part of the script works every time. The clean-up part will frequently report no data. If I log into the server under the account the task runs under and manually run the script it works. If I log into the server as myself and execute the task it works. If I remotely trigger the task I get the periodic lack of data. Here's my script:

$LogFile = "c:\Scripts\WSUSCleanup.log"
$LogFile2 = "c:\Scripts\WSUSDbMaint.log"
$MaxLines = 10000
$nl = [Char]13 + [Char]10

If (Test-Path $LogFile) { $LogFileData = Get-Content $LogFile -Tail $MaxLines }
Else { $LogFileData = "" }
$LogFileData += "-----------------------------------------------" + $nl + "Beginning cleanup at " + (Get-Date -Format "yyyy/MM/dd HH:mm:ss zzz") + $nl
Import-Module UpdateServices
$out = Get-WsusServer -Name wsus.domain.com -PortNumber 8531 -UseSsl | Invoke-WsusServerCleanup -CleanupObsoleteComputers -CleanupObsoleteUpdates -CleanupUnneededContentFiles -CompressUpdates -DeclineExpiredUpdates -DeclineSupersededUpdates
$LogFileData += $out
$LogFileData += $nl + "Finished cleanup at " + (Get-Date -Format "yyyy/MM/dd HH:mm:ss zzz")
Out-File -FilePath $LogFile -Encoding ascii -InputObject $LogFileData

If ((Get-Date -Format "ddd") -eq "Sun")
    {
    If (Test-Path $LogFile2) { $LogFileData = Get-Content $LogFile2 -Tail $MaxLines }
    Else { $LogFileData = "" }
    $LogFileData += "------------------------------------------------------------" + $nl + "Beginning database maintenance at " + (Get-Date -Format "yyyy/MM/dd HH:mm:ss zzz") + $nl
    cd 'C:\Program Files\Microsoft SQL Server\110\Tools\Binn'
    $out = SQLCMD.EXE -E -S np:\\.\pipe\MICROSOFT##WID\tsql\query -i c:\scripts\WSUSDbMaintenance.sql
    $LogFileData += $out
    $LogFileData += $nl + "Finished database maintenance at " + (Get-Date -Format "yyyy/MM/dd HH:mm:ss zzz")
    Out-File -FilePath $LogFile2 -Encoding ascii -InputObject $LogFileData
    }

Here is a except from the Clean-Up log:

Beginning cleanup at 2014/10/20 10:54:34 -07:00



Finished cleanup at 2014/10/20 10:57:12 -07:00
-----------------------------------------------
Beginning cleanup at 2014/10/21 10:54:05 -07:00

Obsolete Updates Deleted:0
Expired Updates Declined: 0
Obsolete Updates Deleted:0
Updates Compressed:1304
Obsolete Computers Deleted:5
Diskspace Freed:3139221020

Finished cleanup at 2014/10/21 10:57:27 -07:00
-----------------------------------------------
Beginning cleanup at 2014/10/22 10:54:01 -07:00

Obsolete Updates Deleted:0
Expired Updates Declined: 0
Obsolete Updates Deleted:0
Updates Compressed:200
Obsolete Computers Deleted:0
Diskspace Freed:582233144

Finished cleanup at 2014/10/22 10:54:52 -07:00
-----------------------------------------------
Beginning cleanup at 2014/10/23 10:54:03 -07:00

Obsolete Updates Deleted:0
Expired Updates Declined: 0
Obsolete Updates Deleted:0
Updates Compressed:154
Obsolete Computers Deleted:0
Diskspace Freed:482770256

Finished cleanup at 2014/10/23 10:54:56 -07:00
-----------------------------------------------
Beginning cleanup at 2014/10/24 10:54:03 -07:00



Finished cleanup at 2014/10/24 10:58:33 -07:00
-----------------------------------------------
Beginning cleanup at 2014/10/25 10:54:03 -07:00



Finished cleanup at 2014/10/25 10:55:39 -07:00
-----------------------------------------------
Beginning cleanup at 2014/10/26 10:54:03 -07:00



Finished cleanup at 2014/10/26 10:55:26 -07:00
-----------------------------------------------
Beginning cleanup at 2014/10/27 09:33:21 -07:00



Finished cleanup at 2014/10/27 09:35:16 -07:00



Service created with New-Service does not start

$
0
0

Hello,

I am trying to create a working service using the New-Service cmdlet. I tried a bunch of different examples, I found on the internet like this one from technet:

new-service -name TestService -binaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"-dependson NetLogon -displayName "Test Service"-StartupType Manual -Description "This is a test service."

The service gets created and is listed in services.msc and Get-Service but I cannot start it. Ever. The state changes to "Starting" but that's all.

I tried it on different machines with different Windows- and PowerShell versions using elevated PS-consoles.

Thanks,

Manuel



Powershell $lastexitcode return works on non-zero return but keeps hanging otherwise

$
0
0

So I have performed some major customization on SQLSPADE thats available on CodePlex

sqlspade.codeplex.com

Here is where I am stuck. I have 2 functions in play. When the first functions executes, It calls the second function called Install-SQLSERVER. The code Snippet for the first function is provided below.

Function Fn_Install()
{
$Global:ResultTextBox.AppendText(" Installaling $Global:Version $Global:edition Edition on $env:computername .Please Wait....`n ")
Install-SQLSERVER -Parameters $ht -TemplateOverrides $overrides -Verbose -DontCopyLocal -InstallOnly
Return
}

As you can see, it writes data to a text box and calls the function Install-SQLSERVER. Within that function, it runs the setup.exe to run a silent SQL Server installation.The code snippet for the second function is provided below



if (($InstallOnly -eq $true -or $Full -eq $true) -and $Global:CriticalError -eq $false)
		{
			Write-Log -level "Section" -message "Starting SQL Server Install"


				#Call the queit install process  - because it writes to the console we don't have to force the code to wait
				if ($pscmdlet.ShouldProcess("Start SQL Installer Package", "Install SQL")) #if (!$Global:Simulation)
				{

                    Invoke-Expression $command
                   [int] $Global:exitCode = $Lastexitcode


				}


                 if ($Global:exitCode -eq 0)
                {
                $Global:ResultTextBox.AppendText(" Installation Completed Successfully `n ")
                $Global:ButtonPostInstall.enabled = $True
		$Global:CriticalError = $false

                }

                else

                {
                Write-Log -level "Error" -message "SQL Server Install failed - please check the console output"
                $Global:ResultTextBox.AppendText(" Installation Failed with error Code: $exitCode `n ")
				$Global:CriticalError = $true

                }

                else
		{
			Write-Log -level "Section" -message "Skipping SQL Server Install"
		}


So I am evaluating the condition based on $lastexitcode. It evaluates the condition and does what its supposed to when the installation fails with a non-zero error code. However, when the installation succeeds, it doesnt evaluate the IF condition at all and just stays stuck on the screen. I have to kill the script from the task manager when that happens. The problem is, I cant evaluate if the $lastexitcode was 0 since I have to kill the entire session. Any idea why this is happening?

Thanks,

Lokesh 



Lokesh Gunjugnur

Create (security)event

$
0
0

Hello,

How can I use PowerShell to create a (security) event?

The structure of the message part of the event should be like the following:

<EventData>
<Data Name="SubjectUserSid">S-1-5-21-1229272821-1801674531-839522115-18652</Data>
<Data Name="SubjectUserName">admindijc</Data>
<Data Name="SubjectDomainName">PGGM-INTRA</Data>
<Data Name="SubjectLogonId">0x21ec6eef</Data>
<Data Name="ObjectType">File</Data>
<Data Name="IpAddress">145.4.61.34</Data>
<Data Name="IpPort">56027</Data>
<Data Name="ShareName">\\*\IPC$</Data>
<Data Name="ShareLocalPath"
/>
<Data Name="AccessMask">0x1</Data>
<Data Name="AccessList">%%4416</Data>
</EventData>

The PowerShell script should be able to create the (xml) eventdata structure with (custom) names for the different parameters. This will enable me to address the individual parts of the avent in OM2012. Without the xml structure SOM2012 would need to search the whole event text which is an expensive operation

Thanks in advance

Regards,

Coen

Regex for computer FQDN

$
0
0

Hi,

Can anyone help me with a RegEX to validate ComputerName to test if it is in FQDN format or not? Also I want to extract NetBIOS Name from FQDN of the computer.


Thanks,

Sitaram Pamarthi

Blog : http://techibee.com

Follow on Twitter

This posting is provided AS IS with no warranties or gurentees,and confers no rights

Get-NetworkStatistics returns all the values set to zero despite having internet traffic

$
0
0

Hi

I'm running Windows Server 2012 R2 and I have a problem with the Get-NetworkStatistics cmdlet: it returns all the parameters with a value of zero eventhough the wireless network adapter is up and running, including having internet access. Furthermore, if I double-click on the wireless network adapter, it displays the correct values for bytes sent / received.

So it seems like the Get-NetworkStatistics cmdlet is unable to read the statistics for the wireless adapter. Any help would be appreciated.

Thanks

Trying to delete a file with Powershell script ran by a service but issues with uac

$
0
0

I'm having issues with a script that will delete a file on the C-Drive of a server. the script looks like this:

param(
[Parameter(Mandatory=$true)][string]$hostname
)

$StrFileName = "C:\Program Files\NSClient++\nsclient.log"
$LogLocal="c:\Nagios\naf_delete_nscp_log_file.log"

$Date = Get-Date -Format "yyyy-MM-dd hh:mm:ss""$date : NSClient logfile deletion requested on $hostname" | Out-File -filepath     $LogLocal -Append

If (Test-Path "$strFileName"){
    Remove-Item $strFileName -Force
$Date = Get-Date -Format "yyyy-MM-dd hh:mm:ss""$date : NSClient logfile deleted on $hostname" | Out-File -filepath $LogLocal -Append
}

The script is initiated from a Nagios quick action which will use nrpe to pass the host as parameter and make the nscp service, which runs as local system, run it. It works perfectly on servers that have no uac enabled, but I can't get it to work on servers with uac. I've tried numerous options, but none seem to work. Any tips or advice to get this working with Powershell v2 code on servers with uac enabled is highly appreciated.

Thanks.

Willem

home folders through csv file (new-aduser) are not actually created

$
0
0

Hi all,

I imported few hundreds users from csv file which include the homedirectory , homedrive.  I run the script and when I check the profile tab of user properties, everything seems to be ok (z:\\dc1\homefolders\marketing\lea zinder) but the actual folders do not exist. If I change one letter just to get the "apply" option, and press apply then the home folder is created. I have to mention that I created the necessary home folders with permissions in advance (it is too complicated for me to set permissions via script).

So my question is how to make the script to actually create the home folders automaticly?

momu


Powershell workflow generating false e-mail alerts

$
0
0

Hi,

I have a powershell script that gathers all of the trusted domains in our environment and then sends each domain name to another script to time the amount of time it takes to receive a response to an unqualified (isolated) name query in AD.

Script 1 code:

#Load the Active Directory Module
Import-module activedirectory

#Search the local schema for all trusted domain objects
$ADDomainTrust = Get-ADObject -Filter {ObjectClass -eq "trustedDomain"} -Properties * | Sort-Object cn

#Define workflow to pass domain names to trustsearch script
workflow Get-domains
{

  param( $trusteddomainlist)
  foreach -parallel ($trusteddomain in $trusteddomainlist)
  {
    $trust = $trusteddomain.name
      InlineScript {C:\trustsearch.ps1 $using:trust}
  }
}

Get-domains -trusteddomainlist $ADDomainTrust

As you can see, I'm using a "foreach -parallel" workflow to query each trusted domain simultaneously. This is done to alert us to a potential problem as quickly as possible, without having to wait for the entire script to finish.

Here's the code for the second (isolated name query) script. It sends me an e-mail if the query takes over 60 seconds. 

Script #2 code:

 $trust=$args[0]
foreach($domain in $trust){

$startDTM = (get-date)
$objUser = New-Object System.Security.Principal.NTAccount("junk")
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value
$endDTM = (get-date)
$totaltime = (($endDTM-$startDTM).TotalSeconds)
$ftotaltime = "{0:N2}" -f $totaltime

Function SendMail
{
#SMTP server name
     $smtpServer = "<SMTP server IP address>"

     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage

     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)

     #Email structure
     $msg.From = "<sender e-mail address>"
     $msg.ReplyTo = "<reply e-mail address>"
     $msg.To.Add("<recipient e-mail address>"
     $msg.subject = "Isolated Name monitor warning"
     $msg.body = @"
     Isolated name queries are running slowly. A script measures how long the NAMCK domain controllers take to resolve an unqualified name query. It usually takes no more than 60 seconds to execute. It is currently taking $ftotaltime seconds. This may indicate a trust issue or a problem with a downstream trusted domain.
"@

#Sending email 
    $smtp.Send($msg)
}

If ($ftotaltime -gt "60.00")
{
 SendMail
}

Unfortunately, I'm getting a lot of false positives....e-mail alerts when query responses are taking only 7 or 8 seconds, not just over 60. It seems to happen most during the first 2 or 3 minutes the script runs. I think it has something to do with it running in parallel, because when I remove the "foreach -parallel" functionality, I don't get any false positives.

Does anyone have suggestions on how to cut down or even eliminate the false positives without removing the "foreach -parallel" functionality?

Thanks.

Powershell runs old version script

$
0
0

Hi all,

I'm having a very strange problem with a powershell which I've created. I will try to explain the situation a bit:

We have a powershell script that looks like this:

Function RunCode
{

some stuff to do here

}

$var1=xx
$var2=xx
...

RunCode($var1, $var2)

##############

$var1=yy
$var2=yy

...

RunCode($var1;)

The script actually calls the "runcode" with different parameters (I will call this SCRIPT1 for now). However, we also have another script that is supposed to run only once (xx for example) (I will call this SCRIPT2 for now). If I start SCRIPT2 on my pc, it works correctly. If I start SCRIPT2 on my virtual machine, it starts running the older script (SCRIPT1). This is a completely different script. However, the function "RunCode" is present in both scripts (and is the same). Although SCRIPT2 only commands powershell to run the code for parameter YY, it will run the code for parameter XX and YY ...

I've tried looking on fora, etc... but I couldn't find any help about this. So I'm hoping someone here knows what the problem could be.

Kind regards

Rename file once it is a specific size

$
0
0
I need to rename a *.log file to *.old once it hits 10MB per the vendor.  I'm not finding a powershell command to do this.  Any ideas?

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


Exception write to event log when user not found in active directory

$
0
0

I'm trying to use a exception to write to a event log to show which user did not get imported from my csv file. Any help to write this exception is appreciated. Thanks

Import-CSV $importfile | ForEach-Object{
     $samaccountname = $_.sAMAccountName.ToLower() #samaccountname on csv file

    Try {
        $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$samaccountname)" #Filter user by samaccountname
        }
    Catch
        {
        write-host "Users did not exist." #user does not exisit
        }


Viewing all 21975 articles
Browse latest View live


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