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

Behavior with " -executionpolicy bypass" and signed code

$
0
0

So, I understand that adding  -executionpolicy bypass to the shortcut launching a script will allow the script to execute no matter what ExecutionPolicy is set to, but does this also just ignore signed code? Or, if I sign the code, and it gets changed, will it refuse to run. In other words, while  -executionpolicy bypass in the shortcut trumps ExecutionPolicy, does code changed since it was signed trump  -executionpolicy bypass and refuse to run?

Thanks for any insights, prior to my buying a code signing certificate. ;)
Gordon


Set local password with secure startup script

$
0
0

Since CPassword has been deprecated by MSFT, I need a secure method to set the password of the local administrator on all workstations. The workaround script that MSFT provided inthe kb article won't work because I have no control over when a computer is on or off. Hence my desire to use a startup script. I logon script would be fine too, but I suspect that wouldn't work since the end users don't have access to set these passwords.

I can set the password with these commands:

$objUser = [ADSI]"WinNT://./LocalAdmin"
$objUser.SetPassword("NewPassword")

but that exposes the password in the script in plain text, which is worse than the CPassword problem that MSFT "fixed."

So, how can I do this same thing and use a predetermined password without putting it into a logon/startup script in plain text?

Thanks in advance!


Blog / Facebook / Twitter

Get-ADUser and Get-Mailbox

$
0
0

Environment: AD running on Windows 2008R2 and Email on Office 365 (cloud only - not on premise)

I am trying to initially find all mailboxes where LitigationHoldEnabled is set to true in a particular OU and then set those mailboxes to false but I'm running into different errors depending on how I write the commands.  I know this is a syntax error because of my limited knowledge of PowerShell so I'm hoping someone can help.

Scenario 1 with error (I did connect to online session before running these commands):

$quarantineOU = get-mailbox -OrganizationalUnit "OU=Quarantine,DC=domain,DC=corp"

error:

Couldn't find organizational unit "Quarantine". Make sure you have typed the name correctly.

    + CategoryInfo          : NotSpecified: (:) [], ManagementObjectNotFoundException

    + FullyQualifiedErrorId : [Server=BLUPR06MB195,RequestId=89e992ba-ad64-4392-887a-626217e46278,TimeStamp=5/14/2014 4:17:41 PM] [FailureCate

   gory=Cmdlet-ManagementObjectNotFoundException] BD65057B

    + PSComputerName        : pod51043psh.outlook.com

Scenario 2 with error:

$qu = get-aduser -filter * -searchbase "OU=Quarantine, DC=domain, DC=corp"
$qu | ForEach-Object (Get-Mailbox $_.userprincipalname -ResultSize unlimited | where {$_.LitigationHoldEnabled -eq $true})

Error:

ForEach-Object : Parameter set cannot be resolved using the specified named parameters.

At line:2 char:7

+ $qu | ForEach-Object (Get-Mailbox $_.userprincipalname -ResultSize unlimited | w ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : MetadataError: (:) [ForEach-Object], ParameterBindingException

    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.ForEachObjectCommand

Pass password to Rename-computer

$
0
0

Hey all as the title says I need help to pass my AD credentials to rename-computer. The problem is when I put it in a loop it asks for them on every machine. How could I store it in a variable and then pass that to rename-computer. I don't think rename-computer had a password switch.

Here's what I have now

$psr = $PSScriptRoot
$oldcomputers = Get-Content C:\Users\cody\Desktop\list.txt
$newcomputers = Get-Content C:\Users\cody\Desktop\newlist.txt


for($i=0;$i -lt $oldcomputers.Length ;$i++){
    if(Test-Connection -ComputerName $oldcomputers[$i] -BufferSize 16 -Count 1 -ea 0 -quiet){
        Write-Host $oldcomputers[$i]
        Rename-computer –computername $oldcomputers[$i] –newname $newcomputers[$i] -DomainCredential doamin\cody\ -Force -restart
    }else{
        Write-Host $oldcomputers[$i] -ForegroundColor Red
    }
}
Thanks!

New to Scripting. Getting error "cannot index into a null array"

$
0
0

I'm trying to build a script that will stop a process when it's hung at 45% CPU usage or more.  I'm getting the error mentioned in the title.  Could someone please review my script and tell me what I'm doing wrong?  Again, I'm very new to powershell scripting so please be patient with me.  Here is the script:

$ProcessName = "dfileman"

foreach ($proc in (Get-WmiObject  Win32_Processor)){
    if($proc.numberofcores -eq $null){
        $cores++
    }else{
        $cores = $cores + $proc.numberofcores
    }

$cpuusage = [Math]::round(((((Get-Counter "\Process($ProcessName)\% Processor Time" -MaxSamples 2).Countersamples) [0].CookedValue)/$cores),2)

if ($cpuusage -gt 45){stop-process ($ProcessName)}


Get-Acl where username has access to folders and SubFolders

$
0
0

Hi, I have a script that works only on the path that is defined, but in my environment I have this path with plenty of subfolders underneath this path. How do I get the ACL permission of the user in the SubfolderS?

$Path = Get-Acl -filter * -path  \\ServerName\Shared\
$Path.Access | where {$_.IdentityReference -like "DomainName\UserName"} | Select-Object FileSystemRights, AccessControlType, IdentityReference, IsInherited | ft -auto

Thanks,

Running CMD command in PS

$
0
0
In PS2, I always use cmd.exe /C to run DOS commands.

However, I ran into this scenario:



The first try, using cmd.exe /C, failed with the above error.

The second try, running the command directly, was successful.

Anyone can explain why?


Thanks.

what is the easiest way to get a list of an Object[] methods and properties?

$
0
0

What is the easiest way to get a list of an Object[] methods and properties?

I'm using this now, and I'm not sure why it actually works.

% -inputobject [[]]$_ {$_|gm;$_|gm -static}






List of Domains and Child Domains

Recursively changing permissions on folders with long path names

$
0
0

I've gotten a request to change permissions on specific folders for every branch office my organization has - 260+. I'm ok getting the folders, but I'm not sure the output/variable will be ok to pass it into the next command.

$folders = gci -Recurse -path q:\ -include *"Long Foldername Search"* | select name

Will the output from that be suitable to pass to a command to change permissions assuming I can work with foldernames over 248 characters? I'm thinking I'll need a foreach statement, but I've never changed folder permissions in PowerShell before.


zarberg@gmail.com

manipulate powershell output

$
0
0

Hello

i am asking if someone can help joining the below powerShell outputs

10381_PHYEDU_6_016100_SD_2013*

10381_PHYEDU_6_016100_SC_2012*

10381_PHYEDU_6_016100_SC_2014*

to be this way

[10381_PHYEDU_6_016100_SD_2013*],[10381_PHYEDU_6_016100_SC_2012* ],[10381_PHYEDU_6_016100_SC_2014*]

A big, a very big and a huge 'big' number - THE GOOD, THE BAD AND THE UGLY

$
0
0
function f{begin{&$s}process{&$s}end{&$s}}
$s,$v={$script:v*=$v},2
$(1..2|f),$v,$($v=2)
$(1..2|%{f}),$v,$($v=2)
$(1..3|%{f}),$v

• <-


I have no time to waste.


Add multi-value Registery entries

$
0
0

Hello All,

I am trying to use the below script to add multi-value registry key

the script is working fine except he is writting only the last value of the variable

any help please

Add-PSSnapin Quest.ActiveRoles.ADManagement
$data= get-QADUser $env:USERNAME -IncludedProperties MemberOf
$1= $data.memberof  -split(",OU") -split "CN=" | Select-String -AllMatches "_Teachers" 
$2 = $1 -creplace "_Teachers", "*"
Foreach($item in $2){
$item 
REG add "HKCU\Volatile Environment" /v Impero_PopulateMyPersonalGroupWithUsers /t REG_MULTI_SZ  /s "," /d "[$item]" /f}


Query remote XP machine for list of mapped network drives of current logged on user

$
0
0

Hi everyone,

I have searched high and low for this script but nothing.  Is it possible to do this if the XP machine does not have PS installed?  Thanks.

Trouble getting a ps1 file to execute

$
0
0

I am having trouble getting a ps1 file to execute.

All the powershell.exe does is go to the next prompt without executing anything.

powershell.exe -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -file C:\Users\Administrator\Documents\Powershell\Excel.ps1' -verb RunAs}"

Excel.ps1

$strPath="c:\path.xlfile.xls"
$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=$true
$Workbook=$objExcel.Workbooks.Add()
$Workbook=$objExcel.Workbook.Add()
$sheet=$Workbook.worksheet.item(1)
$sheet.Cells.item(1,1)=("Title")
$sheet.Cells.item(3,1)=("col1Title")
$sheet.Cells.item(3,2)=("col2Title")
$sheet.Cells.item(3,3)=("col3Title")
$x=100
$y=200
$z=300
$sheet.Cells.item(3,1)=($x)
$sheet.Cells.item(3,1)=($y")
$sheet.Cells.item(3,1)=($z)6
$range=$sheet.UsedRange
$range.EntireColumn.AutoFit()
IF(Test-Path $strPath)
    {
     Remove-Item $strPath
     $objExcel.ActiveWorkbook.SaveAs($strPath)
     }
ELSE
     {
       $objExcel.ActiveWorkbook.SaveAs($strPath)
     }


Merge XML

$
0
0

I have split up what is going to be a very large amount of XML data into multiple files for long term maintenance reasons. However, I need to combine all this information into a single XML object for use by my code. I tried the expediant of a foreach loop, reading each XML file into a temp variable and using

$global:ResourceXml += $TempResourceXml.InnerXml

However, this produces an XML object that no longer works, and I am trying to determine if I can't merge this way, or I need to access the merged data differently, or... At the memento I am not even sure exactly what is wrong, as I can't get a clean XML to the screen, and my code dumps into an endless loop now, erring on a SelectSingleNode attempt on the newly merged data. Gack.

Any thoughts greatly appreciated.
Gordon

Path tool long when using arrays

$
0
0

Hey Powershell people. I'm running into an array issue in powershell where the error "Copy-Item : The specified path, file name, or both are too long" is thrown back at me. However, the odd thing is if I type the copy path in manually the script it works fine, so the error only occurs when the script directly references the item in the array by its numbered location. Eventually, I want to create a for loop for this that will reference each file name in the array, so i'm hoping I can directly reference the array pointer.

$DTS = get-date -format "dd-MM-yyy_hh-mm-ss"
New-Item c:\$DTS -type directory
$get = Get-Content C:\array.txt
Start-Sleep -s 1 
$testdata=@"
$get            
"@
($testdata | Select-String -Pattern '(?<=t.s.\\.).+?(?=\. u s p)' -AllMatches).Matches | %{$_.Value} | Out-File c:\test.txt
Start-Sleep -s 1
$get2 = Get-Content C:\test.txt
$get2 = $get2 -replace " ", "" | Out-File c:\test.txt
$get = Get-Content C:\test.txt

Copy-Item "\\server\C$\Program Files\Projects\$get[0].usp" \\server2\C$\$DTS

Note, if I do something like $get4 = $get[0] the script will properly reference $get[0] if $get4 is inserted into the copy path . 


Long file names with [System.IO.Directory]

$
0
0

Hello,

I understand the 260 character limitation in certain Windows components and a 32k limitation in NTFS. Unfortunately, some of our users have outdone themselves in creating long paths, but I need to still work with these folders. I was using get-childitem, but was pointed in the direction of [System.IO.Directory] from .NET.

I have tried the following code:

$destinationpath = '\\?\UNC\server1\APPS\'

$Searchstring = "*"
$SearchOption = "AllDirectories"
#$folders=[System.IO.Directory]::GetDirectories($destinationpath,$SearchString,$SearchOption)
$folders=[System.IO.Directory]::GetDirectories($destinationpath)

Unfortunately, it fails with:

Exception calling "GetDirectories" with "1" argument(s): "Illegal characters in path."

At C:\Users\heywoodg\Dropbox\Powershell\Scripts\temp.ps1:6 char:47
+ $folders=[System.IO.Directory]::GetDirectories <<<< ($destinationpath)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
 

The other code I tried was 

$destinationpath = '\\server1\APPS\'

$Searchstring = "*"
$SearchOption = "AllDirectories"
$folders=[System.IO.Directory]::GetDirectories($destinationpath,$SearchString,$SearchOption)
#$folders=[System.IO.Directory]::GetDirectories($destinationpath)

This fails with:

Exception calling "GetDirectories" with "3" argument(s): "Could not find a part of the path '\\server1\apps\DEP-Administration\SECRETARIAT\Subsidiary Companies UK\Copmany UK Branch Global Developments Limited\OVERSEAS BRANCHES\Company UK Global Developments Limited - (Pakistan Branch)\Loan Agreements (not part of a project)'."


At C:\Users\heywoodg\Dropbox\Powershell\Scripts\temp.ps1:5 char:47
+ $folders=[System.IO.Directory]::GetDirectories <<<< ($destinationpath,$SearchString,$SearchOption)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
 

So, I have two questions.

1) What is the correct way to pass the UNC to [System.IO.Directory] (a normal UNC still seems affected by the long path issue)?

2) Is the code to search sub-folders correct?

Thanks

finding long unc paths (254 characters)

$
0
0

Some users are using very long filenames and folder names which creates long unc paths altogether.

I want to locate this long UNC path's, is there way to do this with powershell, i am just a beginner with powershell so bare with me.

 

regards,

 

Francis

Any way to convert the Exchange PowerShell sets to EXE file?

$
0
0
Any way to convert the Exchange PowerShell sets to EXE file?
Viewing all 21975 articles
Browse latest View live


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