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

Get-wmiobject Win32_Share does not show Sharing Permissions

$
0
0

To find folders which have Shares open to Everyone, I am using the below. This works well however there is an interesting test we found.

Method 1 - Simple Method - Right click on folder - Share with - specific people. Add everyone and powershell script shows this folder

Method 2 - Old Method used in XP or earlier - If we right click on folder - properties - sharing tab - Enable Share - Advanced permission and then add everyone with full rights - the below does not show up. I mean, the powershell script does not show that folder.

The first method adds the ACL as well when sharing is done.

The second method does not add ACL. It only adds sharing permission.

I cannot use Get-SmbShareAccess because it does not work on Windows 7.

How can I query Share Access as well using powershell?


function Check-Share {Get-WmiObject -Query 'Select * from win32_share where not name like "%$%" and not name like "%users%" and not name like "%driver%"'}


if (Check-Share)  {

Check-Share |

ForEach-Object{
		if(Get-Acl $_.Path|?{
        $_.Access.IdentityReference -match 'Everyone'}){

             $info = "`n$SlNo. $($_.Name) Shared Folder at Path $($_.path)"

             Write-host $info -fore cyan
          }
     } }



Regards, Vik Singh "If this thread answered your question, please click on "Mark as Answer"



Exchange 2010 Delete all mails till a date for all users

$
0
0

Hi , 

I want to delete on my exchange for all users till a date 20/07/2016 .

in all folders , and do not move it to the trash box .

I used this command but this will not work : 

get-mailbox | search-mailbox -SearchQuery "Received:<$(20/07/2016)" -deletecontent

DSC Partial configurations failing when trying to update servers at the same time.

$
0
0

Hi All,

I have tried to configure the partial configurations for the set of servers.

The nodes are configured as following:

ConfigurationRepositoryWeb XXX-DSC-REPOS {
ServerURL = "https://$servername/PSDSCPullServer.svc"
CertificateID = $CertificateID
AllowUnsecureConnection = $False
RegistrationKey = $RegistrationKey
ConfigurationNames = @("xMyconfigMasterHost", "xMyconfig", "xMyconfig_SIT", $ComputerName)

"xMyconfigMasterHost", "xMyconfig", "xMyconfig_SIT" – are the partial configuration names that are merged for the node and contain environment wide settings.
 $ComputerName – Computer specific configuration. Variable is populated from the script input.



PartialConfiguration xMyconfigMasterHost
        {
            Description                     = 'Configuration for the xMyconfigMasterHost'
            ConfigurationSource             = '[ConfigurationRepositoryWeb]XXX-DSC-REPOS'
            RefreshMode                     = 'Pull'
        }
PartialConfiguration xMyconfig
        {
            Description                     = 'Configuration for the xMyconfig'
            ConfigurationSource             = '[ConfigurationRepositoryWeb]XXX-DSC-REPOS'
            DependsOn                       = '[PartialConfiguration]xMyconfigMasterHost'
            RefreshMode                     = 'Pull'
        }
           PartialConfiguration xMyconfig_SIT
        {
            Description                     = 'Configuration for the xMyconfig_SIT'
            ConfigurationSource             = '[ConfigurationRepositoryWeb]XXX-DSC-REPOS'
            DependsOn                       = '[PartialConfiguration]xMyconfig'
            RefreshMode                     = 'Pull'
        }
  PartialConfiguration $ComputerName
        {
            Description                     = "Configuration for the  $ComputerName"
            ConfigurationSource             = '[ConfigurationRepositoryWeb]XXX-DSC-REPOS'
            DependsOn                       = '[PartialConfiguration]xMyconfig_SIT'
            RefreshMode                     = 'Pull'
        }

So all the servers have 2 partials configurations that they share and one specific, that is representing the configuration specific for the server.

I have 2 problems with this config:

1. If the configurations have been pulled to the node and I would like to change  one of the configuration names,  the merge will fail as it will try to include the old partial configuration that will now being replaced, as it still exist on the node. The error will say that I do have a duplicate resource.

2. If  I will try to run "Start-DscConfiguration -UseExisting -ComputerName "Server-01","Server-02" -Verbose -Force -Wait" on multiple nodes - it will fail for all except one. 

The error for the failed nodes would be:

The attempt to get the action from server
http://dsc-001///PSDSCPullServer.svc/Nodes(AgentId='C07CBBB90')/GetDscAction failed
because pullserver is not available or there is no  registered node with AgentId C07CBBB90
on the server.+ CategoryInfo          : ResourceUnavailable: (root/Microsoft/...gurationManager:String) [], CimException+ FullyQualifiedErrorId : WebDownloadManagerGetActionNodeConfigurationNotFound,Microsoft.PowerShell.DesiredStateCo
   nfiguration.Commands.GetDscActionCommand+ PSComputerName        : Server-01

If try to run any amount of nodes in different PowerShell sessions with only one node per command - it will work fine for all nodes.

Any advice?


Silent Install of .net 4.5 in powershell issue

$
0
0

When I am installing .net framework 4.5 through a silent install in Powershell, I am prompted by a GUI Open File - Security Warning. Is there a way to bypass these and completely install the executable file.

I am running Powershell as an administrator. The code I am using is:

 start-process -filepath D:\path\to\dotnetfx45_full_x86_x64.exe -argumentlist '/q /norestart'

Keep getting System.String[] for Gateway using Get-WMIObject

$
0
0

I have been trying to add a function to grab a bunch of Network data from systems in preparation to replace a ton of older machines, but the original script was not one that I created. I've got it to work 99.9% but I need help on the last part. I am able to put the data into an Excel spreadsheet but the Gateway property from win32_networkadapterconfiguration keeps showing up as System.String[] in the Gateway column of the spreadsheet. When I Debug the code, it shows the Gateway address but also has curly braces as well, which is just because it's a String. That's fine with me but it's the only value in the Array and I can't figure out how to remove them and show the actual Gateway IP in the column. I know this may sound convoluted and even though I'm new-ish to Powershell, I still have good luck with using PS to get valuable data from systems. I just need some advice on this last part. I don't get why toString() won't remove the braces. I shouldn't even need it. I have other Properties that are Arrays of Strings, and I can just reference the index of the specific fields I need from within the Array, but I can't figure out what I'm doing wrong with an Array with only one value. Please help.

Brian Embree

Legacy Health System

Portland, OR

new-azurermvm

$
0
0

Hi everyone,

I'm struggling to find instructions I can understand for the proper usage of the new-azurermvm syntax.  My starting point is here:

https://msdn.microsoft.com/en-us/library/mt603754.aspx?f=255&MSPPError=-2147217396

Parameter Set: Default
New-AzureRmVM [-ResourceGroupName] <String> [-Location] <String> [-VM] <PSVirtualMachine> [[-DisableBginfoExtension]] [-LicenseType <System.String> ] [-Tags <Hashtable[]> ] [ <CommonParameters>]

I'm brand new to Azure Powershell and I'm trying to equate it to commands I am more family with like the new-vm command in PowerCLI, for that I would use syntax similar to this:

New-vm -vmhost esxihost1.mydomain.ca -Name newserver01 -Template W2K12_SQL_Build1.2 -Datastore "DatastoreCluster Prod" -OSCustomizationspec "Windows 2012 Build 1.4" -Location Deploy

My preference is to avoid setting 20+ variables like they do in the example and instead just put the minimum requirements in order to deploy the VM and work on adding to it from there.  With that in mind I'm thinking:

Run Login-AzureRmAccount
#Before proceeding verify you are connected to the subscription you intend to deploy to
$VirtualMachine = New-AzureRmVMConfig -VMName PwrShellvm1 -VMSize "Standard_A2"
## Storage
$StorageName = "pwrshelltestacct"
$StorageType = "Premium_LRS"
New-AzureRmVM -ResourceGroupName PwrShellResGrp1 -Location eastus2 -VM $VirtualMachine

I'm getting:

New-AzureRmVM : Unable to cast object of type
'WhereEnumerableIterator`1[Microsoft.Azure.Management.Storage.Models.StorageAccount]' to type
'Microsoft.Azure.Management.Storage.Models.StorageAccountListResponse'.
At line:1 char:1

The example doesn't seem to specify the storage account within the new-azurermvm command, so I don't see how setting it as a variable would help anyway, am I correct in saying that or am I misunderstanding how PowerShell works?

Get-DistributionGroupMember Recursive Functionality.

$
0
0

I’m looking to create a script that can use a list of groups to go through and get me the members of each group.

Example

$group = Get-DistributionGroupMember –identity “Group Name” | Select DisplayName

Now the content of $group will be a list of Distribution Groups, I need to use this as the input to create a CSV file of all the members of each of the groups in $group.

Can someone help me with this?

Ideally if Get-DistributionGroupMember had a recursive function I wouldn’t need to figure out a way to do this. I have seen a couple enumeration scripts around, but I’m not getting exactly the results I need. Any help would be appreciated.

 


Paul Arbogast

Copy text from one file into another at a specific possition using Powershell - Having trouble with Select-String -Pattern

$
0
0

Hello And thank you in advance for any help this community can provide!

I'm trying to create a powershell script that will copy the "excel.officeUI" file from a network drive, to a users local drive into the "C:\Users\%UserID%\AppData\Local\Microsoft\Office"  folder, but If the file already exists, I just want it to copy a specific portion of the file and append it to the local one that already exists

In the File, there is a bunch of headers that are the same, but then it shows <mso:tab id="mso_c2.3ED4DC" label="Macros" insertBeforeQ="mso:TabHome">.... and all the information about the custom ribbon I created in Excel appear all the way to </mso:tab>

So I want to take everything that is between <mso:tab id=".... to </mso:tab> and copy that into the "excel.officeUI" file on their local workstation, and enter it right before the </mso:tabs> (The final tag for the Tabs) so I don't disrupt any custom ribbons they might have already created.

If you are still following me up to here, thank you for your patience :)

So here is the code I'm trying to use but for some reason, it does not find the text I'm looking for and it might have to do with the way I'm entering the "-pattern ..." portion or the fact that the file might have multiple locations where <mso:tab id="... exists:

$copyMacroText = Get-Content $NetExcelFile | Select-String  -Pattern '<mso:tab .*?</mso:tab>' |
               select -expandproperty matches |
               select value


$replaceDestinationText = Get-Content $localExcelFile | Select-String  -Pattern $msoFinal |
               select -expandproperty matches |
               select value

Hopefully this is something very simple that I'm missing!

Thank you!

Alex


How to provide input for prompts ?

$
0
0

Hi Gurus,

I am running an executable that prompts for confirmation when it is invoked,

c:\> commit.exe

Are you sure you want to continue (y/n) ? 

My script needs to call this executable (commit.exe) and then provide input to the prompt either as 'y' or 'n'. How do I take care of this in powershell, such that when I get an expected prompt, I can enter the required input?

Here I would like to enter 'y' or 'n' to the prompt.


-Pranav

Reg Add Command

$
0
0

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AutoAdminLogon /t REG_SZ /d (value 0 or 1)

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultDomainName /t REG_SZ /d (domain or computer name)

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword /t REG_SZ /d (password)

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultUserName /t REG_SZ /d (username)

Hello,

How can I force the script above to prompt for user input? I need it to ask what we would like to change the data fields to. We use this for some of our computers to have them auto login but the data can be different depending where they are located. Any help is appreciated.

Thank you.

Powershell IE current Window name

$
0
0

After I navigate to a new page, LocationName is still displayed as Facebook. What am I doing wrong here?

$ie = New-Object -ComObject InternetExplorer.Application 
$ie.visible=$true
$ie.navigate("https://www.facebook.com") 
while($ie.ReadyState -ne 4) {start-sleep -m 100} 

$ie.Navigate("https://www.google.com")

start-sleep 10

$ie.Refresh()
Write-Output $ie.LocationName

invoke-webrequest : The operation has timed out.

$
0
0

Getting a exception when I try to pull data from this webrequest.

$headers = @{Authorization=$access_token}

$MyURI = "https://apis.accela.com//v4/inspections"

$ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($MyURI)

$result = invoke-webrequest -Method GET -Headers $headers -Uri $MyURI

$ServicePoint.CloseConnectionGroup("")

Add-WindowsFeature, Get-WindowsFeature modules not recognized in powershell.

$
0
0
Hi, I have several Windows Server 2008 R2 servers running in a test lab environment. I have installed the RTM version of 2008 r2. I am building an exchange 2010 lab to test out the new features in it. I was doing some troubleshooting on some of the exchange processes and ran across a page using the Add-WindowsFeature cmdlet in powershell. However when I type in that command in powershell I get a message that says:

The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:19
+ Add-WindowsFeature <<<<
    + CategoryInfo          : ObjectNotFound: (Add-WindowsFeature:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I am also getting the same message with the Get-WindowsFeature command.

What do I need to do on these servers to fix this?

Thanks.

Generating IIS Machine Keys with PowerShell

$
0
0

Hi - I have written a PowerShell script to update machine keys for a suite of web applications. I've used the "Generate-MachineKey" function found here: 

https://support.microsoft.com/en-us/kb/2915218#AppendixA

When I generate an HMACSHA512 validation key with this function I get a 256 character output string. But if I use Microsoft IIS admin utility to generate the same key I get a 128 character output string. 

I also notice both the IIS gui and the PowerShell function generate a 128 character output string for HMACSHA256 (so in PowerShell the output for HMACSHA512 is twice the length of HMACSHA256 but in IIS gui both are 128). 

I tested my apps with the PowerShell generated keys and everything works fine. But can anyone explain to me why the output is different lengths from different MS tools and not matching up with the lengths they say these values should be? I want to make sure this PowerShell function is good before I deploy these keys to production web apps. I have spent hours searching and can find no info about this. Any insight would be much appreciated. 

According to this article the lengths should be as stated below: 

https://msdn.microsoft.com/en-us/library/w8h3skw9(v=vs.100).aspx

  • HMACSHA256 requires a 256-bit key (64 hexadecimal characters).

  • HMACSHA384 requires a 384-bit key (96 hexadecimal characters).

  • HMACSHA512 requires a 512-bit key (128 hexadecimal characters).


Unable to add permissions to a file via set-acl

$
0
0
I see that the local Administrator is the owner of the file

$acl = get-acl -Path $file
$acl.Owner shows BUILTIN\Administrators

When i try to add File permissions to the file, where im a part of builtin\Administrators, im unable to apply permissions

$newacl = new-object System.Security.AccessControl.FileSystemAccessRule("Domain\ADGroup","Modify","Allow")

$acl.SetAccessRule($newacl)

set-acl -path $file -aclobject $acl
By Design, this set-acl is supposed to work, but for some reason, this throws an error

set-acl : Attempted to perform an unauthorized operation.At line:1 char:1+ set-acl -Path '<File Path...>+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : PermissionDenied: (<File Path>:String) [Set-Acl], UnauthorizedAccessException    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetAclCommand0down votefavoriteI see that the local Administrator is the owner of the file$acl = get-acl -Path $file$acl.Owner shows BUILTIN\Administrators
Do suggest on how this can be fixed.

Cheers, Alan.


exchange 2013 powershell script to generate shared mailbox owners list

$
0
0

hi,

exchange 2013 powershell script to generate shared mailbox owners list.

can any one help?  tried with Owner parameter but it does not generate list with all shared mailbox details of owners


MD

"Copy but keep both Files" in any of xcopy, copy, or robocopy

$
0
0

Hello

I am building a batch file to move some files from 1 part of the network to the another. From time to time some files will have the same name, but not necessarily be the same file. I would like to replicate the "Copy but keep both Files" functionality you get when copy and pasting from the GUI, but cannot see it as an option in 'copy', 'xcopy' or 'robocopy'.

Does anyone know if this is possible please?


Paddy

Run ps1 files in a batch file

$
0
0

I try to run a few ps1 files in a batch file.

Powershell.exe -File f1.ps1
Powershell.exe -File f2.ps1
Powershell.exe -File f3.ps1
...
Powershell.exe -File f8.ps1

Is there way to wait to finish one and then start next one automatically? I don't want to use "pause" command after each line

Thanks

trouble looping with do-while

$
0
0

just trying out a simple loop while encountering an "error"

$int = 0
do{
    $int = Read-Host "test"

}while(!($int -ne 1991))

it wokrs well until i enter value of  0/1 then it exits the loop - can anyone enlighten me why? whats behind it?

    Thanks!

Right click and "Run with PowerShell" Evasive Error

$
0
0

Hi, I create scripts for others to use.  They do not know powershell, but can right click and run.  It's hard to support a script if the user can't see the error long enough to read it.  It's also hard for me to support the script because I have also been unable to see or log the error myself, no matter what I try.  I can guess that it's a policy or elevation issue, but I need a way to know for sure. 

I get the error when I right-click and run with powershell.  I thought, no problem.  I'll run it in an ISE or command window to get and see the error.  Problem is, it runs fine no matter how else I run it.  I also added the sendto item as described in the following link.  The script runs without error. 

http://social.technet.microsoft.com/Forums/windowsserver/en-US/cfb64674-240b-4fb7-b9ed-143f408a7e00/run-with-powershell?forum=winserverpowershell

I tried to grab the error message with FullShot, but the timing just does not work.  It's driving me crazy. 

I looked at the eventlogs.  There are events 40961 and 40962 for the console, but nothing obvious to me.  I do notice a CAPI2 event 81 for powershell. 

Log Name:      Microsoft-Windows-CAPI2/Operational
Source:        Microsoft-Windows-CAPI2
Date:          2/11/2014 12:51:46 PM
Event ID:      81
Task Category: Verify Trust
Level:         Error
Keywords:      Trust Verification

<UserData>
    <WinVerifyTrust>
      <ActionID>{00AAC56B-CD44-11D0-8CC2-00C04FC295EE}</ActionID>
      <UIChoice value="2">WTD_UI_NONE</UIChoice>
      <RevocationCheck value="0" />
      <StateAction value="0">WTD_STATEACTION_IGNORE</StateAction>
      <Flags value="80000100" WTD_SAFER_FLAG="true" CPD_USE_NT5_CHAIN_FLAG="true" />
      <FileInfo filePath="C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1" hasFileHandle="true" />
      <DigestInfo digestAlgorithm="" digest="" />
      <RegPolicySetting value="23C00" WTPF_OFFLINEOK_IND="true" WTPF_OFFLINEOK_COM="true" WTPF_OFFLINEOKNBU_IND="true" WTPF_OFFLINEOKNBU_COM="true" WTPF_IGNOREREVOCATIONONTS="true" />
      <StepError stepID="3" stepName="TRUSTERROR_STEP_SIP">
        <Result value="57">The parameter is incorrect.</Result>
      </StepError>
      <StepError stepID="9" stepName="TRUSTERROR_STEP_MSG_SIGNERCOUNT">
        <Result value="57">The parameter is incorrect.</Result>
      </StepError>
      <StepError stepID="32" stepName="TRUSTERROR_STEP_FINAL_OBJPROV">
        <Result value="800B0003">The form specified for the subject is not one supported or known by the specified trust provider.</Result>
      </StepError>
      <StepError stepID="33" stepName="TRUSTERROR_STEP_FINAL_SIGPROV">
        <Result value="800B0100">No signature was present in the subject.</Result>
      </StepError>
      <StepError stepID="34" stepName="TRUSTERROR_STEP_FINAL_CERTPROV">
        <Result value="800B0100">No signature was present in the subject.</Result>
      </StepError>
      <EventAuxInfo ProcessName="powershell.exe" />
      <CorrelationAuxInfo TaskId="{3B47B6AD-542A-4B0E-AAD6-CD74EA298B9E}" SeqNumber="2" />
      <Result value="800B0100">No signature was present in the subject.</Result>
    </WinVerifyTrust>
  </UserData>

Is there any way to get the right-click "run with powershell" error text? 

If I sign the script, would this avoid the issues I'm having with right-click and run with powershell? 

Thanks


Randy in Marin

Viewing all 21975 articles
Browse latest View live


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