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

Add Security Groups to Printer Server 2008 R2

$
0
0

Hello,

I'm looking for a solution to copy or add security groups to 50 printers resides on a print server running Windows Server 2008 R2.

I tried any Get/Set-Printer -PermissionSDDL etc. it is not supported by this operation system even from remote client running win10.

I tried Get-wmiobject win32_printer and i couldn't solve that issue.

Please help.


Accessing a web service using certificate authentication

$
0
0

I have a web service that requires certificate authentication, and I would like to call it using PowerShell.

If I export my certificate to a pfx file, I can access the service with this code:

$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 "C:\tmp\cert.pfx", "ThePassword"
$proxy = New-WebServiceProxy "https://xxx/service.asmx"
$proxy.ClientCertificates.Add($certificate)
$proxy.SomeMethod()

However, to do this, I must also allow access to the service with anonymous authentication, and verify in the actual calls if the user is authenticated.

Since Get-Credential allows me to select a certificate, I hoped I could do something like this:

$proxy = New-WebServiceProxy "https://xxx/service.asmx" -Credential $(Get-Credential)
$proxy.SomeMethod()

But this does not seem to work, and it behaves like the proxy is not using any credentials.

Is it possible to use a certificate in a call to New-WebServiceProxy?


Paolo Tedesco - http://cern.ch/idm

Powershell: Get-AdUser - connect multiple parameters in -filter property

$
0
0

Hello,

I have a small problem in powershell and I don't know how to solve it.

I want to write a script that gets all User Objects from active directory and exports them to a csv file.

I want to get all objects in AD that have the objectclass "User" and do not have "not-delete" in the notes-field.

So while this works perfectly fine and gives me all user objects:

$ADUsers = get-aduser -filter 'ObjectClass -eq "user"' -properties *


this does not work:

$ADUsers = get-aduser -filter 'ObjectClass -eq "user" -and info -ne "not-delete"'  -properties *

Does anybody know how to connect statements in the -filter property?

Thanks for reading and regards

Martin


Pull All User Attributes with PowerShell

$
0
0

Okay, when I go into ADUC and open up the Attribute Editor for a User I see something like 300 attributes. Many are blank or unused, that's fine. I need to pull that full list with Powershell. I don't care whether they are blank or null or whatever, I want a list of every attribute available in my directory. I've tried several different queries with different tools. Get-ADUser is the most comprehensive at 100 attributes returned.

Get-ADUser username -Properties * | Select *
This isn't all of them. For example the "Audio" Attribute doesn't show up. But as soon as I put a value in Audio it does show up. So I know that the CMDLET has access to the attributes it just isn't showing them to me. Is there a flag/switch I'm missing that will show everything? Is there a different CMDLET I should be using?

Thanks much for the help in advance.

How to invoke ISE, using my existing environment

$
0
0

Hi all,

    I'm sitting in PowerShell. I have all my functions, variables, modules and remote sessions established. I'd like to invoke ISE, WITH this entire environment. Is this possible? If so, how would I go about doing this?

Thanks.

Trimming a string

$
0
0
I'm having a hard time trimming the following string

2015-11-26T06:00:00.000Z

I've tried

$expired="2015-11-26T06:00:00.000Z"

$expires=("$expired"-split'.')[1]

$expires

but it gives me no results. I just want the .000Z removed from the variable. any suggestions?

Strange extra empty table when building a report with ConvertTo-HTML

$
0
0

I'm building a new script to delete old user accounts from one of our domains and then email me a report with the results of the script, but I've run into some strange output while building the report.  It's not a deal breaker and the data I'm getting out of the report looks good, but when I email the report to myself I get an extra blank table at the bottom of the HTML that I was hoping to get rid of.  I might just be missing something when I'm assembling the fragments, but when I look in the raw HTML I see the extra blank table at the bottom of the report as well.  Any thoughts on why this might be happening?  Here's my script and the extra output at the bottom of the HTML report:

</td></tr> </table>
<table>
</table>
</body></html>

<#
 .SYNOPSIS
    Removes accounts in the Contoso domain that have been disabled for over 180 days.
 .DESCRIPTION
    This script searches the Contoso domain for user accounts that have been disabled for over 180 days
    and deletes them.  By default the script searches in the "Staff" OU, but can be adjusted
    to another LDAP searchbase if necessary.  Accounts can be whitelisted by putting the term "WHITELIST" in
    the account description field.
 .NOTES
    Author  : Nick
    Requires: PowerShell Version 2.0, Active Directory module
 .EXAMPLE
    .\Remove-DisabledUsers.ps1
#>

##Check for and import modules as needed
If ( (Get-Module ActiveDirectory -ErrorAction SilentlyContinue) -eq $null )
    {Import-Module ActiveDirectory -ErrorAction SilentlyContinue -Verbose:$False}

$DeletionDate = [DateTime]::Today.AddDays(-180)
$DeletedUsers = @()
$WhitelistUsers = @()

$DisabledUsers = Get-AdUser -Filter {enabled -eq $False} -SearchBase "OU=Staff,DC=Contoso,DC=local" -Properties DisplayName,mail,description,whenchanged

ForEach ($line in $DisabledUsers) {
    #If user has term WHITELIST in description, do nothing and add to whitelist array
    If ($line.description -like "*WHITELIST*") {
        $WhitelistUsers = $WhitelistUsers + $line
    }
    #If user has been disabled for over 180 days, delete and add to deletion array
    Elseif ($line.whenchanged -lt $DeletionDate) {
        #Remove-ADObject -id $line.ObjectGUID -Recursive -Confirm:$false
        $DeletedUsers = $DeletedUsers + $line
    }
}

##Process the results and create HTML for report
$WhitelistCount = ($WhitelistUsers).Count
$DeletedCount = ($DeletedUsers).Count
$ReportHeader = "The cleanup script has completed successfully. $DeletedCount accounts were deleted and $WhitelistCount are whitelisted."
$DeletedTable = $DeletedUsers | Select-Object DisplayName,mail,Description | ConvertTo-Html -Fragment
$WhiteListTable = $WhitelistUsers | Select-Object DisplayName,mail,Description | ConvertTo-Html -Fragment

##Clear any existing report data and set style formatting
$ReportPath = "c:\powershell\DeletedUser_Report.htm"
Clear-Content $ReportPath -Verbose:$False

$CSS = @"<style type="text/css">
    table {
    	font-family: Verdana;
    	border: 1px solid black;
    	padding: 5px;
    	background-color: white;
    	table-layout: auto;
    	text-align: center;
    	font-size: 8pt;
    }
    table th {
    	border: 1px solid black;
        background-color: lightblue;
        font: bold
    }
    table td {
    	border: 1px solid black;
    }
    .style1 {
        font-family: Courier New, Courier, monospace;
        font-weight:bold;
        font-size:small;
    }</style>"@

ConvertTo-Html -Body "$CSS $ReportHeader $DeletedTable $WhiteListTable" -Title "Contoso Disabled Account Cleanup" | Out-File $ReportPath


scripting new-mailboximportrequest

$
0
0

New-mailboximportrequest needs a couple of parameters including a mailbox, and the path to a PST

I created an array like this

$upn = get-aduser -filter {UserPrincipalName -like "*@teststeve.com"} | foreach-object {$_.name}

Then created an array like this

$arr = get-childitem -path "\\2-exchcas1\c$\psts\" | where-object {$_.extension -eq ".pst"} | foreach-object {$_.name} |sort-object {$_.name}

These both work fine.

Id like to export the two to a csv file so I get

user1, user1.pst
user2, user2.pst
user3, User3.pst

then I can spot check the upns and psts match up correctly.

After I manipulate the file so everything is correct, Id like to read it back in and run

New-mailboximportRequest –mailbox $upn –filepath $path

Any suggestions? Ive been trying to work with hash tables and 2d arrays but, Im sure Im making it harder than it has to be.

Thanks.


how can I stop "Select-Object -Property" from truncating the output?

$
0
0

I am trying to list files of a certain type recursively with their full name and last write date

Get-ChildItem -File -Recurse -Filter "*.dtsx" | Select-Object -Property DirectoryName, Name, LastWriteTime

The DirectoryName gets truncated with "..." if too long.

How can I force the output to return more characters?


Eric Mamet _ MCDBA, SQL Server 2005 MCTS, MCAD .Net

Wrote a script to move file based on file name, but will move existing folders into others.

$
0
0

I've just started using powershell and am not completely familiar with it. With some help I made this code:

PS C:\Users\Clyde2409\Desktop\Test>

$Pattern = "(?<Dept>.*)_(?<Name>.*)_(?<Year>.*).pdf"
$list = Get-ChildItem
Set-Location C:\Users\Clyde2409\Desktop\Test

# Foreach-Object loop based on the list of files
foreach ($file in $list) {
    # send $true/$false results from -matches operation to $null
    $File.Name -match $Pattern 2> $Null
    $Destination = Join-Path $matches.Dept $matches.Name

    # Create the destination if it does not exist
    if (!(Test-Path $Destination) ) {
        New-Item -ItemType Directory -Path $Destination
    }

    # Moves the file
    Move-Item $file "$Destination\$($file.Name)"
}

The script will move files based on file name (all files will follow the same pattern). The destination of the file is based off of the first 2 parts of the name, in this case Dept is one folder, and name is a subfolder within the first folder. In the case that the folder/sub folder doesn't exist, it will be created. The problem is that if a folder already exists within Desktop\Test, it will be moved into another folder. This is a big problem the 2nd time through as all of the folders created will be moved into another one. Can anyone help me fix/understand this problem?

Thanks!


cURL Bash to Powershell

$
0
0

Hello,  I am not an experienced powershell user, and could use some help,     in github there is a bash script that downloads Salesforce eventlogs,  located here:  https://github.com/atorman/elfBash/blob/master/elfCURL_win.sh.  (the bash script is also shown below)  

We noticed that the Bash uses cURL, and we prefer not use cURL,  It appears Powershell's (v3.0) equivalent to cURL is Invoke-RestMethod \ Invoke-WebRequest.   It also appears that it pipes out the Json call. 

We want to convert the Bash into Powershell.  Does this seem reasonable ?  or by chance has any one else converted this script to PS?  

Thank you for your help !

BASH:

read -p "Please enter username (and press ENTER): " username
read -s -p "Please enter password (and press ENTER): " password
echo 
read -p "Please enter instance (e.g. emea) for the loginURL (and press ENTER): " instance
read -p "Please enter logdate (e.g. Yesterday, Last_Week, Last_n_Days:5) (and press ENTER): " day

#change client_id and client_secret to your own connected app - bit.ly/sfdcConnApp
access_token=`curl https://${instance}.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=3MVG99OxTyEMCQ3ilfR5dFvVjgTrCbM3xX8HCLLS4GN72CCY6q86tRzvtjzY.0.p5UIoXHN1R4Go3SjVPs0mx" -d "client_secret=7899378653052916471" -d "username=${username}" -d "password=${password}" -H "X-PrettyPrint:1" | jq -r '.access_token'`

#set elfs to the result of ELF query
elfs=`curl https://${instance}.salesforce.com/services/data/v32.0/query?q=Select+Id+,+EventType+,+LogDate+From+EventLogFile+Where+LogDate+=+${day} -H 'Authorization: Bearer {AccessToken}' -H "X-PrettyPrint:1"`

#set the three variables to the array of Ids, EventTypes, and LogDates which will be used when downloading the files into your directory
ids=( $(echo ${elfs} | ./jq -r ".records[].Id" | sed 's/[ \t]*$//') )
eventTypes=( $(echo ${elfs} | ./jq -r ".records[].EventType" | sed 's/[ \t]*$//') )
logDates=( $(echo ${elfs} | ./jq -r ".records[].LogDate" | sed 's/'T.*'//' | sed 's/[ \t]*$//') )

#loop through the array of results and download each file with the following naming convention: EventType-LogDate.csv
for i in "${!ids[@]}"; do
    
    #uncomment the next three lines if you want to see the array of Ids, EventTypes, and LogDates
    echo "${i}: ${ids[$i]}"
    echo "${i}: ${eventTypes[$i]}"
    echo "${i}: ${logDates[$i]}"

    #make directory to store the files by date
    mkdir "${logDates[$i]}"

    #download files into the logDate directory
    curl --compressed "https://na1.salesforce.com/services/data/v32.0/sobjects/EventLogFile/${ids[$i]}/LogFile" -H 'Authorization: Bearer {AccessToken}' -H "X-PrettyPrint:1" -o "${logDates[$i]}/${eventTypes[$i]}.csv"

Exporting all Windows Features to file for import in new systems as a templated setup

$
0
0

Is there a simple way to export all the windows features from one system to use as a template for setting up others?

Previously you could use ServerManagerCmd.exe -inputPath Install.xml to achieve this but on the Powershell provider from what I can tell you need to explicitly script each feature install using Install-WindowsFeature

Install-WindowsFeature -Name Web-Server -IncludeAllSubFeature
Other than piping Get-WindowsFeature to a text file and re-importing is there a simpler way of achieving this?


Nikolai Blackie Adaptiv Integration

Starting a Service on Multiple Servers in an Array

$
0
0

Hello, having some trouble getting a service to start on multiple servers. I can get the script to work using the stop command but fore some reason my start script will only start the service on the first server in the array. What is also puzzling is that the command to set the service to auto start changes from manual to auto per the script on both servers. 

Powershell info:

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

Working stop script:  (Stops the service on both servers in the array)

Clear-Host

Write-Host ""

Write-Host ""

Write-Host "==================================================================="

Write-Host ">>> Capture 2 Citrix Servers"

Write-Host "==================================================================="

# Array of target servers

[array]$Servers = "Testserver1","Testserver2" 

# Array of services for actions

[array]$Services = "IMAService"

# Array of processes associated with services

[array]$Processes = "ImaSrv"

# Create the Powershell session(s) for each server
$Session = New-PSSession -ComputerName $Servers

# Set the services to Manual so they don't auto restart

Write-Host ""

Write-Host "==> Setting the startup type of services to 'Manual'..."

foreach ($Service in $Services) 

{

    Set-Service -Name $Service -ComputerName $Servers -Verbose -PassThru -ErrorAction Continue -StartupType Manual

}

# Stop each service

Write-Host ""

Write-Host "==> Stopping services..."

foreach ($Service in $Services) 

{

    $svc = Get-Service -Name $Service -ComputerName $Servers  -Verbose -ErrorAction Continue

Stop-Service -InputObject $svc -force -Verbose -PassThru -ErrorAction Continue
    

}

# Try to kill any processes still running

Write-Host ""

Write-Host "==> Trying to stop the associated processes..."

foreach ($Process in $Processes) 

{

    $wmi = Get-WmiObject -Class Win32_Process -ComputerName $Servers -Filter "Name = '$Process.exe'" -ErrorAction Continue

    if ($wmi) { Try { $wmi.Terminate() } Catch { Write-Host "ERROR: Unable to terminate '$wmi.Name'" } }

}

# Close the remote sessions
Remove-PSSession -ComputerName $Servers

Write-Host "==> Done for $Servers"

 

Write-Host ""

Write-Host ""


Non working start service script  (Only starts the service on the first server in the array but sets the service to auto start on both servers)

Clear-Host

Write-Host ""

Write-Host ""

Write-Host "==================================================================="

Write-Host ">>> Capture Start Citrix Servers"

Write-Host "==================================================================="

# Array of target servers
[array]$Servers = "Testserver1","Testserver2"

# Array of services for actions
[array]$Services = "IMAService"

# Create the Powershell session(s) for each server
$Session = New-PSSession -ComputerName $Servers

# Set the services to Automatic

Write-Host ""

Write-Host "==> Setting the startup type of services to 'Automatic'..."

foreach ($Service in $Services) 

{

    Set-Service -Name $Service -ComputerName $Servers -Verbose -PassThru -ErrorAction Continue -StartupType Automatic

}

# Start each service

Write-Host ""

Write-Host "==> Starting services..."

foreach ($Service in $Services) 

{

    $svc = Get-Service -Name $Service -ComputerName $Servers -Verbose -ErrorAction Continue

    Start-Service -InputObject $svc -Verbose -PassThru -ErrorAction Continue

}

# Close the remote sessions
Remove-PSSession -ComputerName $Servers

Write-Host "==> Done for $Servers"

Write-Host ""

Write-Host ""

Thanks for any and all suggestions! 


PowerShell v3 ISE suddenly won't start

$
0
0

It has been running on Windows 7 x64 for months now. And I can still start the console version, but not the ISE or ISE (x86). Event Log says:


Application: PowerShell_ISE.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
Stack:
   at Microsoft.Windows.PowerShell.GuiExe.Internal.GPowerShell.Main(System.String[])

and

Faulting application name: PowerShell_ISE.exe, version: 6.2.9200.16398, time stamp: 0x50333c54
Faulting module name: KERNELBASE.dll, version: 6.1.7601.18015, time stamp: 0x50b8479b
Exception code: 0xe0434352
Fault offset: 0x0000000000009e5d
Faulting process id: 0x1848
Faulting application start time: 0x01ce465096915587
Faulting application path: C:\Windows\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe
Faulting module path: C:\Windows\system32\KERNELBASE.dll
Report Id: d44d4d75-b243-11e2-86dc-001b10002aec

To try to fix the problem I attempted moving away everything from C:\Program Files\Common Files\Modules, C:\Windows\System32\WindowsPowerShell\v1.0\Modules, my profile and other modules (C:\Users\XXXX\Documents\WindowsPowerShell). ISE would still give the same error.

I had a look in Add/Remove Programs for recently added programs or updates and didn't find anything. I tried re-running the WMF 3.0 installer but it says it is already installed. There is no entry in Add/Remove Programs for WMF so I can't see how you could possibly re-install it or do a recovery.

Export Shares to CSV from Known File Servers

$
0
0

I'd like to be able to remotely run a PowerShell script in order to document all network shares (non admin shares) in a network.  I'd like to add the servers into a "FileServers.CSV" file, and then import that into the PowerShell script.  It should give me another "NetworkShares.CSV" output file with this information.

I have the following:

$Data = Import-CSV "D:\Scripts\FileServers.csv"

ForEach ($Line in $Data)
 {
  $FileServer = ($Line.FileServer)

  Write-Host -ForeGroundColor 'green' "Process " $FileServer ;
  Get-WMIObject -ComputerName $FileServer -Query "SELECT * FROM Win32_Share Where Type=0" |
  Select-Object Name,Path,Description | Export-CSV "D:\Scripts\NetworkShares.csv"

 }

Write-Host -ForeGroundColor 'green' ":)"   Completed!  ":)"

I get the following error message:

Get-WMIObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At D:\\Scripts\DocumentShares.ps1:9 char:3
+         Get-WMIObject -ComputerName $FileServer -Query "SELECT * FROM Win32_Share Wher ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

It's probably something obvious, but I'm not very familiar with PowerShell :) 



How to Change Default location to run powershell script for Task scheduler to run on?

$
0
0

Hi

I have have to manupulate Triggers for windows Task via powershell script.

By default powershell commandlets are only looking at \Microsoft\Windows\PowerShell\ScheduledJobs 

I want to be able to manupulate triggers for Task on different location e.g. \SCOM-SCCM

is there any way setting up default location at start of the script and exit the location at the end?

Thank you in advance.

Need Help with reg expression in powershell

$
0
0

Hello,

I have a string that I want to remove a character from. The problem is that the character exist in two places, so when I try and do a simple replace it removes the character.  If someone could help me with figuring out how to skip the first character, then remove everything else. 

smdpitch_mc-BZX.L2.GE.dat.20151119-050201  <---- I want to remove  "-050201" , but if I do -replace ("-","") that obviously removes all of the "-"  

Let me know if anyone can help

Use a PowerShell script as generic script for failover cluster

$
0
0

Hello,

it is possible to use a VB script as generic script resource in a failover cluster: https://msdn.microsoft.com/en-us/library/aa372846%28v=vs.85%29.aspx

Is it possible to do the same with powershell? And if yes is there a sample somewhere available.

Thanks,

Daniel

listing all files of a particular type recursively but without a sub folder...

$
0
0

I am trying to list of files of type *.xslt within a folder structure but excluding the sub folders called "obj".

The bit I struggle with is excluding this sub folder

I tried this

Get-ChildItem -File -Recurse -Filter "*.dtsx" -exclude "*\obj\*"| sort-object -Property LastWriteTime -Descending | Format-Table -Property FullName, LastWriteTime, CreationTime -AutoSize | Out-String -Width 4096

which does not exclude anything

or that 

Get-ChildItem -File -Recurse -Filter "*.dtsx"  | where {$_.fullname -notcontains "\obj\"} | sort-object -Property LastWriteTime -Descending | Format-Table -Property FullName, LastWriteTime, CreationTime -AutoSize | Out-String -Width 4096

which does not exclude anything either

The result is something like this


Eric Mamet _ MCDBA, SQL Server 2005 MCTS, MCAD .Net

Write output to csv file

$
0
0

I have a script that counts files and sizes of folders which are listed in a csv file.

The first version was asking for source and destination location and exported the results to a csv file.

But I want to have a larger overview of many folders, so I use a CSV file as input.

Although I cannot write the data correct to the csv file.

What I would like to achieve is that the results are written to csv and also the folders should be added to the csv file.

Otherwise I only get values, but don't know where they belong to.

I found some information, which I tried to use in my script, but it doesn't work.

The first script is working, but doesn't show all information in the csv file such as the folders I am counting. the second script doesn't work at all yet.

any suggestions ?

Clear-Host
. ".\Get-FolderItem.ps1" -Local 1
$compare = import-csv .\folders.csv

foreach ($folder in $compare){

$sfiles = Get-FolderItem -Path $folder.source

$sfiles | Measure-Object -Sum -Property Length |
    Select Count,@{L='SizeMB';E={$_.Sum/1MB}} | export-csv .\file_count.csv -Append

$dfiles = Get-FolderItem -Path $folder.destination

$dfiles | Measure-Object -Sum -Property Length |
    Select Count,@{L='SizeMB';E={$_.Sum/1MB}} | export-csv .\file_count.csv -Append
}

Clear-Host
. ".\Get-FolderItem.ps1" -Local 1
$compare = import-csv .\folders.csv

# Set work file
$WorkFile = '.\Workfile.csv'
'"Feed","File","Length"' | Out-File -FilePath $WorkFile -Encoding asci

    foreach ($folder in $compare)
    {
    $sfiles = Get-FolderItem -Path $folder.source

    $sfiles | Measure-Object -Sum -Property Length |
        Select Count,@{L='SizeMB';E={$_.Sum/1MB}}

    $dfiles = Get-FolderItem -Path $folder.destination

    $dfiles | Measure-Object -Sum -Property Length |
        Select Count,@{L='SizeMB';E={$_.Sum/1MB}}

    }

# Write the results and view
$collection | Export-Csv -LiteralPath $WorkFile -NoTypeInformation -Encoding UTF8
Invoke-Item -Path $WorkFile

Write-Host "Done"

Viewing all 21975 articles
Browse latest View live


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